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

标签 java

此代码仅将输出显示为

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/

相关文章:

java - Spring-Boot REST 服务基本 http auth 排除一个端点

java - LinearLayout WeightSum 不起作用

java - GLSL 阵列不工作

java - 合并多个流并写入排序的输出流

java - XML 解析失败

java - 调度程序客户端启动失败 -> 无法获取远程调度程序的句柄 : Sched1_$_NON_CLUSTERED

java - 用于精确提取 {} 之间的字符串的正则表达式

javascript - 文件下载后重新加载页面

java - 使用 Lucene 索引 NTriples

java - JNI 'problematic frame' 导致 JVM 崩溃