Java: stopping input when empty

2285 views java
8

In my program im reading numbers and signs until user gives us empty line.

import java.util.*;
public class Zadanie3 {
public static void main(String[] args) {
        // TODO Auto-generated method stub
         Scanner input = new Scanner(System.in);
         String znak = input.nextLine();
         if(znak.isEmpty()){                               
                System.exit(0);                     
            }
         char helper;
         int stack[]=new int[10];

         int i =-1;
         List<String> outcome = new ArrayList<>();


        while (input.hasNext() && !input.equals("")){

            znak=input.nextLine();
            if(znak.equals("")){
                break;
            }

            if(znak.charAt(0)=='+' && i<9){
                znak=input.nextLine();
            if(znak.equals("")){
                break;
            }
            i++;
            stack[i]=Integer.parseInt(znak);
            outcome.add(":)");

            }else if(znak.charAt(0)=='-' && i>=0 && i<=9){
            outcome.add(String.valueOf(stack[i]));
            i--;
            }
            else{
                outcome.add(":(");

            }
            znak=input.nextLine();

            if(znak.equals("")){
                break;
            }

            if(znak.charAt(0)=='+' && i<9){
                znak=input.nextLine();
            if(znak.equals("")){
                break;
            }
            i++;
            stack[i]=Integer.parseInt(znak);
            outcome.add(":)");

            }else if(znak.charAt(0)=='-' && i>=0 && i<=9){
            outcome.add(String.valueOf(stack[i]));

            i--;

            }

            else{
                outcome.add(":(");
            }

            }


        for(String s: outcome) {
            System.out.println(s);
        }



    }

}

After entering empty line input still doesnt stop - i've tried using input.isEmpty() in while and if's but it didnt work too.(As you can see i added multiple if statements, after each input but somehow they dont react when after few values I give empty space instead. Removing hasNext() from while and replacing it by isEmpty(), Equals() gives the same result.)

answered question

!input.equals("") input is a Scanner - how can this be true?

change the code from znak.equals("") to if(znak.isEmpty()) inside while loop to break from loop and remove condition && !input.equals(""), this does not make any sense

1 Answer

10

Try to make conditions

Ex;

if(userInput == ""){
//do something
}

posted this

Have an answer?

JD

Please login first before posting an answer.