Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k 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 (19.7k 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, 2021 in Java by Jake (7k points)
0 votes
1 answer
0 votes
1 answer
asked Mar 9, 2021 in Java by dante07 (13.1k points)
0 votes
0 answers
0 votes
1 answer

Browse Categories

...