1

I am trying to run the below code which does not work when int numTest = sc.nextInt() is used whereas works fine when int numTest = Integer.parseInt(sc.nextLine()) is used. But I am trying to get only an integer value here with which I can get the number of string set from user. So why can't I use 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();
    }
}

2 Answers2

0

sc.nextLine() takes the whole text to the next line break (enter you pressed). If you use nextInt() the scanner will hang up the next time you try to use it.

Toxicvipa
  • 16
  • 1
0

They have different functionality:

  • nextInt() will read the next token (and convert to int), that is, up to the next whitespace character (default) - it will not consume that whitespace character
  • nextLine() will read the whole line (or what is not already read from the current line) and will consume the newline character at the end of the line - so the next scan will start on next line

If you want to read the whole line, use nextLine() and eventually parseInt() if an integer is desired. If more than one number can be given in one line, use nextInt(), but see Scanner is skipping nextLine() after using next() or nextFoo()?.

Note: you could also just call nextLine() after nextInt() to ignore the rest of the line and skip to the next line (ignoring can be desired or hide input errors!) IMO it is better to use the parseInt(nextLine()) combination to signal an eventual invalid input.

user16320675
  • 135
  • 1
  • 3
  • 9