如何让扫描仪读取预设变量

时间:2013-05-03 10:17:40

标签: java interface java.util.scanner

我正在尝试使用扫描仪获取用户输入以将新项目添加到我创建的库存清单中,该项目必须具有属性itemID,itemDesc,price,quantity和reorderlevel。

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

我已经去了,但它似乎并不认为它们是我的变量

非常感谢任何帮助。 感谢

MY ATTEMPT:

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)    :>");
    }

3 个答案:

答案 0 :(得分:1)

每次进行输入时,无需创建新的扫描仪。您可以按如下方式使用先前定义的扫描仪:

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();

答案 1 :(得分: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); 

答案 2 :(得分:0)

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

Scanner scanner = new Scanner(System.in);

然后每次你想阅读输入时使用

scanner.nextLine()

但是如果你知道你正在读int等,你可以使用像

这样的特定方法
scanner.getInt()

有关详细信息,请参阅here