循环输入?

时间:2015-10-16 00:42:30

标签: java while-loop java.util.scanner

我是学习java编程的初学者。基本上,我无法弄清楚在之前的输入和处理数据之后多次从控制台输入输入的方法。在我向您展示我的代码之前,我认为展示结果应该是一个好主意。 该计划的结果应该是:

Please Enter either S(supply) or R(replenish) followed by ID and quantity.
R     p122.   10
New Stock-level for p122(Chain) is 58
S.    p124.   20
New Stock-level for p125(Pedal) is 18
S.    p905.   20
No part found with ID p905
.....// enter empty string to terminate

有不同类的用途。我已经能够通过一行输入使我的程序正常工作。

Please Enter either S(supply) or R(replenish) followed by ID and quantity.
R     p122.   10
New Stock-level for p122(Chain) is 58

然而,我无法弄清楚如何让用户第二次输入输入等等。我尝试在while循环中包含但是它没有按预期工作。

Please Enter either S(supply) or R(replenish) followed by ID and quantity.
R     p122.   10
//It stops showing the result altogether...

这是我的代码。请告诉我我做错了什么。

import java.util.Scanner;

public class TestPart {
  public static void main(String[] args) {

    // Array of 5 Part objects
    // Part[] part = new Part[5];
    Part[] part = new Part[5];
    part[0] = new Part("p122", "Chain", 48, 12.5);
    part[1] = new Part("p123", "Chain Guard", 73, 22.0);
    part[2] = new Part("p124", "Crank", 400, 11.5);
    part[3] = new Part("p125", "Pedal", 3, 6.5);
    part[4] = new Part("p126", "Handlebar", 123, 9.50);

    ///////// Test Class 2 ////////
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please Enter either S (supply) or R (replenish) followed by ID and quantity.");
    while(!scanner.nextLine().equals("")){

    String sOrR = scanner.next();
    String inputId = scanner.next();
    int amount = scanner.nextInt();
    System.out.println(sOrR);

    for (int i = 0; i < 5; i++) {
        String id = part[i].getID();
        // Find ID in array
        if (id.equals(inputId)) {
            // S or R
            if (sOrR.equals("R")) {
                part[i].replenish(amount);
            } else {

                part[i].supply(amount);

            }
            System.out.println("New Stock-level for " + part[i].getID() + "(" + part[i].getName() + ") is "
                    + part[i].getStockLevel());
        }


    }
    if ((inputId.equals(part[0].getID()) == false) && (inputId.equals(part[1].getID()) == false)
            && (inputId.equals(part[2].getID()) == false) && (inputId.equals(part[3].getID()) == false)
            && (inputId.equals(part[4].getID()) == false)) {
        System.out.println("No part found with ID " + inputId);
    }

    }

    }
}

1 个答案:

答案 0 :(得分:3)

替换此行:

while(!scanner.nextLine().equals("")){

使用:

while(scanner.hasNext()){

否则您已经在测试中跳转到nextLine()