0

Here is my problem I've been struggling with:

I want the input to be in this form: 1

So I wrote the code like this. Unfortunately, it either gives me an InputMismatchException at line 6 or cannot break at "END_PRICES".

        Scanner input =new Scanner(System.in);
        ArrayList<String> fruitName = new ArrayList<>();
        ArrayList<Double> fruitPrice = new ArrayList<>();
        while(true) {
            String str=input.next();
            Double v=input.nextDouble();
            if(str.equals("END_PRICES")) break;
            fruitName.add(str);
            fruitPrice.add(v);
            input.nextLine();
        }

Anyone knows how to solve this? Thanks in advance!

Tina
  • 13
  • 3

1 Answers1

0

The condition in while loop can be changed to check first if there is a nextLine and then find contents of the line like this:

while (sc.hasNextLine()){
            String s = sc.nextLine();
            if (s.trim().equalsIgnoreCase("END_PRICES")){
                break;
            }
            String[] values = s.split(" ");
            double price = Double.parseDouble(values[1]);
            fruitName.add(values[0]);
            fruitPrice.add(price);
        }
Harshita
  • 85
  • 5