跳转到for循环中的下一个用户输入

时间:2012-09-23 18:21:48

标签: java loops

如果我想更改某些数据,但保留一些原始名称,当我按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
}

3 个答案:

答案 0 :(得分:1)

使用continue关键字(from oracle documentation)。

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

答案 2 :(得分:1)

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

也就是说,如果Name为空,请将其跳至Name2