gpt4 book ai didi

java - 为什么只接受数字作为输入?

转载 作者:行者123 更新时间:2023-12-02 13:07:27 25 4
gpt4 key购买 nike

此代码仅将输出显示为

Enter Name of the item you want to add Enter the price of item

虽然它应该在接受 double 作为输入之前接受名称。

newMenu = new Scanner(System.in);

System.out.println("Please select on of the menuItems \n 1. Premium \n 2. Discount \n 3. Standard ");
FileWriter file = new FileWriter(f,true);

//Create an instance of the PrintWriter class using output as the argument
PrintWriter abc = new PrintWriter(file);

if(newMenu.nextInt()==1){
abc.println("Premium");
System.out.println("Enter Name of the item you want to add");
String name=newMenu.nextLine();
abc.println(m1.getNoOfItems()+1+" "+name);

System.out.println("Enter the price of item");
double price=newMenu.nextDouble();
abc.println(price);
m1.setNoOfItems(m1.getNoOfItems()+1);
}

最佳答案

而不是:

if(newMenu.nextInt() == 1){

您可以使用 newMenu.nextLine() 来代替,如下所示:

if (Integer.parseInt(newMenu.nextLine()) == 1) {
<小时/>

While it should take the name before it take the double as input.

您不会遇到这种情况,因为您没有消耗所有线路。

关于java - 为什么只接受数字作为输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44084774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com