In my program im reading numbers and signs until user gives us empty line. EDIT: Basicly program should simulate adding/removing numbers from stack(array of 10 elements) and there are two basic operations(adding: + and in next line a number and taking off: for every succesfully added number program should print :) when action is impossible(out of range of an array) print: :( and for possible removal print the number;(as below)
*SAMPLE:* INPUT: + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 0 + 1 - - - - - - - - - - - OUTPUT: :) :) :) :) :) :) :) :) :) :) :( 0 9 8 7 6 5 4 3 2 1 :(
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;
char helper;
int stack[]=new int[10];
int i =-1;
List<String> outcome = new ArrayList<>();
while (input.hasNext()){
znak=input.nextLine();
if(znak.isEmpty()){
break;
}
if(znak.charAt(0)=='+' && i<9){
znak=input.nextLine();
if(znak.isEmpty()){
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.isEmpty()){
break;
}
if(znak.charAt(0)=='+' && i<9){
znak=input.nextLine();
if(znak.isEmpty()){
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.)