javastringintegerjava.util.scanner

How to get a String and an int vs. just a String with Scanner?


I have some code that runs an addition or subtraction of two numbers based on a user's input, wherein they can either type a String followed by an integer to perform an operation, OR just a String to close the program.

My code looks like this:

private static int result = 0;

public static void main(String[] args){
  Scanner kb = new Scanner(System.in);
  String operation = "";
  int num = 0;
  boolean finished = false;
  
  while(!finished){
    System.out.println("Enter the operation you'd like to perform on " + result + " or type q to quit.");
    operation = kb.next();
    if(kb.hasNextInt()){ num = kb.nextInt(); } //The problem
    
    switch (operation){
      case "add":
        add(num);
        break;
      case "subtract":
        subtract(num);
        break;
      case "q":
        finished = true;
        break;
    }
    System.out.println("New result: " + result);
  }
  System.out.println("Bye!");
}

public static void add(int num){
  result += num;
} 
public static void subtract(int num){
  result -= num;
} 

With my program, a user can input "add 3" to add 3 to result, or "subtract 7" to subtract 7 from result, however inputting "q" only prompts the user to continue entering inputs, rather than closing the program as intended. I was hoping the if(kb.hasNextInt()) method would detect if the user typed an integer, and only run num = kb.nextInt() if they did, but this doesn't seem to be the case. Typing "q" should close the program, but instead it keeps searching for an input. How can I tell my program not to look for an int after the string if there isn't one there?

I considered taking the whole input as a string and using .split() to extract the int, but that seems like a poor solution and I'm sure there must be something easier I'm not thinking of. Any help is appreciated!


Solution

  • IMO this is more about how you arrange the flow of your program. You may check first for 'q' (and break if yes), and proceed for arithmetic operations if not 'q'.

    private static int result = 0;
    
    public static void main(String[] args){
      Scanner kb = new Scanner(System.in);
      String operation = "";
      int num = 0;
      
      while(true){
        System.out.println("Enter the operation you'd like to perform on " + result + " or type q to quit.");
        operation = kb.next();
        if(operation.equals("q")) { break; }    
    
        switch (operation){
          case "add":
            num = kb.nextInt();
            add(num);
            break;
          case "subtract":
            num = kb.nextInt();
            subtract(num);
            break;
        }
        System.out.println("New result: " + result);
      }
      System.out.println("Bye!");
    }
    
    public static void add(int num){
      result += num;
    } 
    public static void subtract(int num){
      result -= num;
    }