0

我正在尝试使用扫描仪获取用户输入以将新项目添加到我创建的库存列表中,该项目必须具有属性 itemID、itemDesc、价格、数量和再订购级别。

我将如何阅读用户输入,并将其识别为我创建的变量之一,然后将其添加到我的列表中?

我试过了,但它似乎没有将它们识别为我的变量

任何帮助将非常感激。谢谢

我的尝试:

else if (i==1)
    {
        StockListInterface.doAddItem(item);

        System.out.println("Add New Item");
        System.out.println("****************");

        System.out.println("Enter ID    :>");
        Scanner scanner1 = new Scanner(System.in);
        String itemID = scanner1.nextLine();

        System.out.println("Enter Description    :>");
        Scanner scanner2 = new Scanner(System.in);
        String itemDesc = scanner2.nextLine();

        System.out.println("Enter Price    :>");
        Scanner scanner3 = new Scanner(System.in);
        String price = scanner3.nextLine();

        System.out.println("Enter Quantity    :>");
        Scanner scanner4 = new Scanner(System.in);
        String quantity = scanner4.nextLine();

        System.out.println("Enter Re-Order Level    :>");
        Scanner scanner5 = new Scanner(System.in);
        String reOrderLevel = scanner5.nextLine();

        System.out.println("Enter another? (Y/N)    :>");
    }
4

3 回答 3

1

您无需在每次输入时都创建一个新的 Scanner。您可以使用之前定义的扫描仪,如下所示:

else if (i==1)
{
    StockListInterface.doAddItem(item);

    System.out.println("Add New Item");
    System.out.println("****************");

    System.out.println("Enter ID    :>");
    Scanner scanner1 = new Scanner(System.in);
    String itemID = scanner1.nextLine();

    System.out.println("Enter Description    :>");
    String itemDesc = scanner1.nextLine();

    System.out.println("Enter Price    :>");
    String price = scanner1.nextLine();

    System.out.println("Enter Quantity    :>");
    String quantity = scanner1.nextLine();

    System.out.println("Enter Re-Order Level    :>");
    String reOrderLevel = scanner1.nextLine();

    System.out.println("Enter another? (Y/N)    :>");
}

此外,您应该考虑在末尾再添加一行,以获得“Y”或“N”的输入,如下所示:

String addAnother = scanner1.nextLine();
于 2013-05-03T10:23:35.720 回答
0
One problem in your code i can see is you are creating Object of scanner every time when you get input.

I Suggest you to use class BufferedReader like this. It works perfectly.

BufferedReader br = null
try{
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   String tmp = br.readLine();
  } catch(IOException ie){
System.out.println(e)
}

br.readLine() : always returns String
You need to convert String into related to datatype. Let's say i want to convert that string to integer, Then i can use wrapper class like this

Integer num = Integer.parseInt(tmp); 
于 2013-05-03T10:30:38.630 回答
0

您无需每次要读取输入时都创建新的扫描仪,只需使用

Scanner scanner = new Scanner(System.in);

然后每次你想读取输入使用

scanner.nextLine()

但是如果你知道你正在阅读 int 等,你可以使用特定的方法,比如

scanner.getInt()

看到这里了解更多信息

于 2013-05-03T10:31:19.463 回答