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!

2
  • Swap around the Double and if lines? Commented Sep 22, 2021 at 11:38
  • @Andy Turner Thanks, it works! Amazing! Commented Sep 22, 2021 at 11:47

1 Answer 1

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);
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Your way of thinking is much better than mine!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.