0

The following code is part of my program, not all of it. In lasTal(), I let the user enter numbers in a number sequence. Once the user is done, he is supposed to press enter so that my program reacts on the empty string entered and returns the list of numbers.

public class Nastaord{
    public static int bFinal, cFinal;
    public static ArrayList<Integer> tallistaFinal;

    private static ArrayList<Integer> lasTal(){
        Scanner scanner = new Scanner(System.in);
        ArrayList<Integer> tallista = new ArrayList<Integer>(); //Det vi ska ha talföljden i

        int i = 0;  //räknare för tallista
        while(true){
            System.out.print("Enter number, or press enter if you are done: ");
            String input = scanner.nextLine();
            if(input == ""){
                return tallista;}
            int nytt_tal = Integer.parseInt(input);
            tallista.add(nytt_tal);
            i++;
        }

I get the following runtime error:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:592)
    at java.lang.Integer.parseInt(Integer.java:615)
    at Nastaord.lasTal(Nastaord.java:18)
    at Nastaord.main(Nastaord.java:45)

it seems to me that the program never enters the if-statement for the empty string, and instead tries to convert the string "" to an int, which is impossible. Why is this and what can I do to fix it?

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
Sahand
  • 7,980
  • 23
  • 69
  • 137

1 Answers1

0

Try "".equals(input) instead of input == "".

Everv0id
  • 1,862
  • 3
  • 25
  • 47