Java: nextDouble 从用户消息中获取号码未打印

Java: nextDouble get numbers from user message doesn't get printed

我的输出是:

Enter dog sizes or END to end: 1
2
3
4
END
Total dog sizes: 10.0

为什么我需要它

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
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);

    }
}

该消息未被打印仅仅是因为您在阅读代码中的下一个 double 后没有打印它。您可以在 while 循环中输入打印语句 re-print 您描述的消息:

while (scanner.hasNextDouble()) {
    total += scanner.nextDouble();
    System.out.print("Enter dog sizes or END to end: ");
}

编辑:

您的父级 do..while 循环只执行一次,因此消息只会打印一次。如果你想把它打印在每一行,那么你可以这样做:

Scanner scanner = new Scanner(System.in);
double total = 0;

do {
    System.out.print("Enter dog sizes or END to end: ");
    String q = scanner.nextLine();              
    try {
        String[] str = q.split("\s+");
        for(String s: str) {
            total += Double.parseDouble(s);
        }
    }catch(NumberFormatException e) {   //invalid double
        if(q.toUpperCase().equals("END")) {
            break;  //stop if END or end is entered
    }               
        continue;   //skip over other invalid doubles
    }
       
} while(true);

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

我读了一整行,然后在空格处拆分数字。

也许你应该这样做(阅读代码中的注释):

Scanner scanner = new Scanner(System.in);
double total = 0;
String dogSizeStrg = "";
while (dogSizeStrg.isEmpty()) {
    System.out.print("Enter dog sizes or END to end: ");
    dogSizeStrg = scanner.nextLine().trim();
    if (dogSizeStrg.equalsIgnoreCase("end")) {
        break;
    }
    // Is the entered numerical value a signed or 
    // unsigned Integer or floating point number?
    if (dogSizeStrg.matches("-?\d+(\.\d+)?")) {
        // Yes...it is.
        total+= Double.valueOf(dogSizeStrg); // Convert to double and add to total.
    }
    else {
        // No... it isn't so inform User and let
        // him/her try again.
        System.err.println("Invalid numerical value supplied! (" + 
                           dogSizeStrg + ") Try Again...");
    }
    dogSizeStrg = ""; // Reset to loop again...
} 

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

Scanner#nextLine() method is used here along with the String#matches() method and a Regular Expression (RegEx) 验证 提供了有符号或无符号整数或浮点值。

您的输入由 space 分隔,因此您必须如下所示使用 nextLine().split(“ ”) 并获得所需的输出:

public class Test3 
{
    public static void main(String[] args) 
    {
        Scanner scanner = new Scanner(System.in);
        double total = 0;
        String q = "";
        do 
        {
            System.out.print("Enter dog sizes or END to end: ");

            if(scanner.hasNextDouble())
            {
               String s[]= scanner.nextLine().split(" ");
               for(int i =0 ;i < s.length;i++)
                     total+= Double.parseDouble(s[i]);
            }      
            else
            {
               q = scanner.nextLine();
            }          
        } while (!q.equals("END"));
        
        scanner.close();
        System.out.println("Total dog sizes: " + total);
    }
}

按如下操作:

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);
    }
}

样本运行:

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: 5
Enter dog sizes or END to end: END
Total dog sizes: 15.0

此外,请注意,当您在无限循环中使用条件来打破它时,您可以简单地使用 while (true) {//...} 而不是 do {//...} while(true);,例如以下代码的行为方式与上述代码相同。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double total = 0;

        while (true) {
            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;
            }
        }

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