0 votes
1 view
in Java by (9.2k points)

Below is the code:

import java.util.Scanner;

public class Test3 {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        double total = 0;

        do {

            System.out.print("Enter dog sizes or END to end: ");

            while (scanner.hasNextDouble()) {

                total += scanner.nextDouble();

            }

            scanner.nextLine();

            String q = scanner.nextLine();

            if (q.equals("END")) {

                break;

            }

        } while (true);

        System.out.println("Total dog sizes: " + total);

    }

}

Below is the output I get:

Enter dog sizes or END to end: 1

2

3

4

END

Total dog sizes: 10.0

This is my expected output:

Enter dog sizes or END to end: 1

Enter dog sizes or END to end: 2 3

Enter dog sizes or END to end: 4

Enter dog sizes or END to end: END

Total dog sizes: 10.0

Can anyone tell me how I can achieve this?

1 Answer

0 votes
by (19k points)

Check out the code below: 

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        double total = 0;

        do {

            System.out.print("Enter dog sizes or END to end: ");

            String q = scanner.nextLine();

            // Create a new Scanner with the input string

            Scanner doubles = new Scanner(q);

            while (doubles.hasNextDouble()) {

                total += doubles.nextDouble();

            }

            if (q.equals("END")) {

                break;

            }

        } while (true);

        System.out.println("Total dog sizes: " + total);

    }

}

Interested in Java? Check out this Java tutorial by Intellipaat.   

Related questions

0 votes
1 answer
asked Feb 16 in Java by Jake (6.8k points)
0 votes
1 answer
0 votes
1 answer
asked Mar 9 in Java by dante07 (13.1k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...