为什么要使用 Integer.parseInt(sc.nextLine());在这个程序中而不是 sc.nextInt()?

Why should I use Integer.parseInt(sc.nextLine()); in this program and not sc.nextInt()?

我正在尝试 运行 下面的代码在使用 int numTest = sc.nextInt() 时不起作用,而在 int numTest = Integer.parseInt(sc.nextLine()) 被使用。但是我试图在这里只获取一个整数值,我可以用它从用户那里获取字符串集的数量。那么为什么我不能使用 sc.nextInt()?

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        **try{
          int numTest = Integer.parseInt(sc.nextLine());
          for(int i = 0; i < numTest; i++){
              String ch = sc.nextLine();
           if(isBalanced(ch)){
               System.out.println("YES");
           } else {
               System.out.println("NO");
           }
          }**
        } catch(Exception e){
            System.out.println("Invalid Input");
        }
    }
    public static boolean isBalanced(String s){
        if(s == null || s.length() % 2 != 0) return false;
        Stack<Character> stack = new Stack<Character>();
        for(int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            if(c == '(' || c == '{' || c == '['){
                stack.push(c);
            } else if(c == ')' || c == '}' || c == ']'){
                if(!stack.isEmpty()){
                    char latestOpenP = stack.pop();
                    if(latestOpenP == '(' && c != ')'){
                        return false;
                    } else if(latestOpenP == '{' && c != '}'){
                        return false;
                    } else if(latestOpenP == '[' && c != ']'){
                        return false;
                    }
                } else {
                    return false;
                }
            }
        }
    
        return stack.isEmpty();
    }
}

sc.nextLine() 将整个文本带到下一个换行符(输入您按下的)。 如果您使用 nextInt() 扫描器将在您下次尝试使用它时挂断。

它们具有不同的功能:

  • nextInt() 将读取下一个标记(并转换为 int),即直到下一个空白字符(默认)——它不会消耗该空白字符
  • nextLine() 将读取整行(或未从当前行读取的内容) 将在行尾使用换行符 -所以下一次扫描将从下一行开始

如果要阅读整行,请使用 nextLine(),如果需要整数,则最后使用 parseInt()。如果一行中可以给出多个数字,请使用 nextInt(),但请参阅 Scanner is skipping nextLine() after using next() or nextFoo()?.

注意:您也可以在 nextInt() 之后调用 nextLine() 来忽略该行的其余部分并跳到下一行(忽略 或隐藏 输入错误!)IMO 最好使用 parseInt(nextLine()) 组合来表示最终无效输入。