有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在Java中使用for循环和扫描程序添加数组

我对块底部的enterItemInfo()方法有问题。我希望用户输入一个项目名称,然后输入一个项目价格,并循环多次,循环次数等于项目名称。长我遇到的问题是,当我运行这个方法时,它以某种方式直接跳到第二个输入,然后任何给定的输入都会导致错误。我不知道我哪里出了问题

import java.util.Scanner;

public class Item {
    //FIELDS
    private int itemAmount;
    private String[] itemNames;
    private double[] itemPrices;

    Scanner item = new Scanner(System.in);

    public int getItemAmount() {
        return this.itemAmount;
    }

    public void setItemAmount() {
        System.out.println("Please enter the number of items: ");
        this.itemAmount = item.nextInt();
        System.out.print("There are " + this.itemAmount + " items.");
    }

    public void enterItemInfo() {
        itemNames = new String[this.itemAmount];
        for (int i = 0; i < itemNames.length; i++) {
            System.out.println("Enter the next item name: ");
            itemNames[i] = item.nextLine();
            System.out.println("Enter the price for " + itemNames[i] + ": ");
            itemPrices[i] = item.nextDouble();
            item.nextLine();
        }
    }
}

共 (2) 个答案

  1. # 1 楼答案

    您错过了为itemprices数组创建对象。您的代码也跳过了输入产品名称的部分。 这个代码应该是有效的:

    public void enterItemInfo() {
        itemNames = new String[this.itemAmount];
        itemPrices = new Double[this.itemAmount];
        for (int i = 0; i < itemNames.length; i++) {
            System.out.println("Enter the next item name: ");
            itemNames[i] = item.next();
            item.nextLine();
            System.out.println("Enter the price for " + itemNames[i] + ": ");
            itemPrices[i] = item.nextDouble();
            item.nextLine();
        }
    }
    

    运行代码的屏幕截图:

    enter image description here

  2. # 2 楼答案

    nextInt()方法在按enter键时不读取新行,因此nextLine()方法只读取这一新行

    有两种变通方法:

    你可以这样把nextLine()放在nextInt()后面:

    itemAmount = item.nextInt();
    item.nextLine();
    

    或者,更好的是,您可以使用nextLine()读取所有输入,并将字符串解析为您需要的任何内容:

    itemAmount = 0; // give a standard amount if somethings fail in the try-catch
    try {
        itemAmount = Integer.parseInt(item.nextLine()); // parse the read line to Integer
    } catch(Exception e) {  // catch the exception if the entered line can't be parsed into an Integer. In this case the itemAmount value will be 0
        e.printStackTrace();
    }