-1

如果我想更改一些数据,但保留一些原始名称,当我按 Enter 时如何跳到下一个用户输入?

  for (int i = 0; i < myVector.size(); i++)
{
    System.out.println("Press Enter to skip to next input");
    System.out.print("Enter Name: ");
//If user presses Enter/newline, go to the next part where it asks for Name2

    Name = keyboard.nextLine();
    System.out.println("You've entered: " + Name);
    myVector.elementAt(i).setName(Name);

    System.out.println("Press Enter to skip to next input");
    System.out.print("Enter Name2: ");

    Name2 = keyboard.nextLine();
    System.out.println("You've entered: " + Name2);
    myVector.elementAt(i).setName(Name2);

//...etc
}
4

3 回答 3

1

使用 continue 关键字(来自 oracle 文档)。

于 2012-09-23T18:23:36.807 回答
1
loop: for (int i = 0; i < myVector.size(); i++)
{
    Scanner sc = new Scanner(System.in);
    if(user presses enter) {
        System.out.println("Press Enter to skip to next input");
        System.out.print("Enter Name: ");
        //If user presses Enter/newline, go to the next part where it asks for Name2

        continue loop;
    }    
    else {
        Name = keyboard.nextLine();
        System.out.println("You've entered: " + Name);
        myVector.elementAt(i).setName(Name);

        System.out.println("Press Enter to skip to next input");
        System.out.print("Enter Name2: ");

        Name2 = keyboard.nextLine();
        System.out.println("You've entered: " + Name2);
        myVector.elementAt(i).setName(Name2);

        //...etc
    }
}
于 2012-09-23T18:24:34.590 回答
1
Name = keyboard.nextLine();
if (!Name.isEmpty()) {
  System.out.println("You've entered: " + Name);
  myVector.elementAt(i).setName(Name);
}

即,如果Name为空,则跳至Name2

于 2012-09-23T18:26:43.983 回答