Reputation: 109
Is there any easy way to ignore hyphens while using scanner? I have a program that will allow you to buy an area (2D array) so if the user want to buy area 3-6, I want scanner to put the number before the hyphen in row and the number after in column. Is there any easy way to do this?
String[][] buyer = new String[10][15];
int row;
int column;
System.out.print("Specify which area you want to buy: ");
row = scan.nextInt();
column = scan.nextInt();
String name;
System.out.print("Name of the buyer: ");
name = scan.nextLine();
buyer[row][colum] = name
Upvotes: 1
Views: 1218
Reputation: 20442
I think you can use Scanner.skip
row = scan.nextInt();
scan.skip("-");
column = scan.nextInt();
Upvotes: 0
Reputation: 2486
Scanner has some bad and some good side, the bad side is this not work if you not know what next chars is.
You can use Scanner.hasNextInt()
and if not this is true, read char for char unto hasNextInt
is true.
Upvotes: 0
Reputation: 771
if your input is always in this format (num1-num2) then you can use :
String area = scan.next();
StringTokenizer st = new StringTokenizer(area);
st.split("-");
int row = Integer.parse(st.nextToken());
int col = Integer.parse(st.nextToken());
Upvotes: 1
Reputation: 5674
Personally I'd read it as a String, then you can use String.split()
to split it in to two values that you can then parse to ints. There may be other options though.
Upvotes: 0