我编写了一个程序,我需要获取用户输入(价格)并将所有价格的总和作为输出。自然价格不可能是负数,所以我的问题是:程序如何只接受正数?
6070 次
1 回答
1
你想要这样的东西
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a price: ");
double number = input.nextDouble();
while (number < 0 ) {
System.out.print("Sorry, but your price must be a positive decimal. Enter a price: ");
number = input.nextDouble();
}
System.out.println("Your price is " + number);
}
}
使用 while 循环继续重新检查输入的价格是否符合您的标准。
于 2019-09-09T19:42:29.080 回答