Why Wont My Java Scanner Take In input?

前端 未结 3 758
南方客
南方客 2021-01-23 05:52
package Lessons;

import java.util.Scanner;

public class Math {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.         


        
相关标签:
3条回答
  • 2021-01-23 06:03

    Try this for the section of taking a String input.

    `System.out.print(" Now enter ur operator ");
        String b1 =s.next();
        if (b1.equalsIgnoreCase("-")) {
            System.out.println("You chose " + b1 + "as ur operator");
    }`
    
    0 讨论(0)
  • 2021-01-23 06:11

    Calling s.nextInt() reads the next int, but does not read the new line character after that. So the new line would be read on line 15. If you are sure that every input will be put in a separate line, then you can resolve this problem by putting an extra s.nextLine() before line 15:

    ...
    System.out.print(" Now enter ur operator ");
    s.nextLine();
    String b1 = s.nextLine();
    ...
    
    0 讨论(0)
  • 2021-01-23 06:14

    You need to call in.nextLine() right after the line where you call in.nextInt() The reason is that just asking for the next integer doesn't consume the entire line from the input, and so you need skip ahead to the next new-line character in the input by calling in.nextLine().

    int a2 = s.nextInt();
    s.nextLine();
    

    This pretty much has to be done each time you need to get a new line after calling a method that doesn't consume the entire line, such as when you call nextBoolean() etc.

    0 讨论(0)
提交回复
热议问题