user1655752
user1655752

Reputation: 45

What is a simple way to read an input that can be either an integer or a character?

Since there is no way to call nextChar(), I am not sure how I am supposed to read an input which could either be 2 integers (separated by a white space) or a character. Help?

Upvotes: 3

Views: 208

Answers (3)

arshajii
arshajii

Reputation: 129517

You'll have to use next.equals("q") instead. == should generally be used only on primitives. Try this:

Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a coordinate [row col] or press [q] to quit: ");
String next = keyboard.nextLine();

if (next.equals("q")){  // You can also use equalsIgnoreCase("q") to allow for both "q" and "Q".
    System.out.println("You are a quitter. Goodbye.");
    isRunning=false;
}
else {
    String[] input = next.split(" ");
    // if (input.length != 2) do_something (optional of course)
    int r = Integer.parseInt(pair[0]);
    int c = Integer.parseInt(pair[1]);
    // possibly catch NumberFormatException...
}

Upvotes: 2

kosa
kosa

Reputation: 66647

String comparison should be

"q".equals(next)

== compares two references pointing to same object or not. Generally used for primitives comparison.

.equals() compares values objects have to determine equality.

Upvotes: 2

João Silva
João Silva

Reputation: 91329

First of all, instead of if (next=="q") use if (next.equals("q")) to compare strings. Note that even though "q" is a single character, it's still a String object. You could use next.charAt(0) to get the char 'q', and then, you could indeed use next == 'q'.

Also, instead of next() use nextLine(), and if the user didn't type "q", split the line to get the two integers. Otherwise, if you call next() two times, and you just type "q", you'll never exit the program, since the scanner will wait for the user to type something to return from the second next():

String next = keyboard.nextLine();
if (next.equals("q")) {
  System.out.println("You are a quitter. Goodbye.");
}
else {
  String[] pair = next.split(" ");
  int r = Integer.valueOf(pair[0]);
  int c = Integer.valueOf(pair[1]);
  System.out.printf("%d %d\n", r, c);
}

Upvotes: 3

Related Questions