Mick Jones
Mick Jones

Reputation: 11

Using a Scanner with a String Splitter

I am trying to use a string splitter to display user input e.g. 1,2 coordinates to display on a console. I don't get any errors when I run my code. However, my attempt to use the splitter does not seem to work.

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a row and column number at which to shoot (e.g., 2,3): ");
String[] coordinates = scanner.nextLine().split(",");
if (coordinates.length != 2) {
    System.out.println("Please enter coordinates in the correct format.");
    System.out.println("\nPlayer 1 Please take your turn:");
    continue;
}

System.out.println("\nEnter Mine location:");

System.out.println("\nPlease Enter x position for your Mine:");
System.in.read(byt);
str = new String(byt);
row = Integer.parseInt(str.trim()); 

System.out.println("\nPlease Enter y position for your Mine:");
System.in.read(byt);
str = new String(byt);
col = Integer.parseInt(str.trim());

Upvotes: 0

Views: 186

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Your use of System.in.read(...) is dangerous code and is not doing what you think it's doing:

System.in.read(byt); // *****
str = new String(byt);
row = Integer.parseInt(str.trim()); 

Instead use a Scanner, something that you already have, and either call getNextInt() on the Scanner, or get the line and parse it.

Also, you never use the Strings held in the coordinates array -- why get the Strings if you are ignoring them?


You ask about:

Scanner scanner = new Scanner(System.in); 
System.out.println("Enter a row and column number at which to shoot (e.g., 2,3): "); 
str = scanner.nextInt().split(","); 

but then see that the compiler won't allow this since you're trying to call a method on the int primitive that scanner.nextInt() returns.

My recommendation to use Scanner#nextInt() was as a replacement for you misuse of System.in.read(...). If instead you want the user to enter two numbers on one line, separated by a comma, then you're best bet is to use String.split(","), although, I think it might be better to use String.split("\\s*,\\s*") to get rid of any white space such as spaces hanging about. This way the split should work for 1,1 as well as 1, 2 and 1 , 2, and then you can parse the items held in the array via Integer.parseInt(...).

Upvotes: 2

Related Questions