Java从控制台读取粘贴的输入,然后停止

Java从控制台读取粘贴的输入,然后停止,java,input,Java,Input,我目前正在尝试解决以下有关onlinge judge的问题: 我想知道如何确定程序应该何时退出,换句话说,我应该何时停止输入循环并退出程序 示例代码: public static void main(String[] args) { //Something here Scanner in = new Scanner(System.in); while(?) //How do I determine when to end? { //Doi

我目前正在尝试解决以下有关onlinge judge的问题:

我想知道如何确定程序应该何时退出,换句话说,我应该何时停止输入循环并退出程序

示例代码:

public static void main(String[] args) 
{   
    //Something here

    Scanner in = new Scanner(System.in);
    while(?) //How do I determine when to end?
    {
        //Doing my calculation
    }
}

我唯一的想法是在控制台中粘贴完所有输入后停止输入读取器,但我不知道该怎么做。

您可以尝试类似的方法

    Scanner in = new Scanner(System.in);
    System.out.println("Your input: \n");
    List<String> list=new ArrayList<>();
    while(in.hasNextLine()) 
    {
       list.add(in.nextLine());
        if(list.size()==5){ //this will break the loop when list size=5
            break;
        }
    }
    System.out.println(list);
输出:

[hi, hi, hi, hi, hi]

确定一个中断条件的输入。e、 g“退出”
然后

或者,如果不可能,像这样

 public static void main(String[] args) 
 {   
  //Something here
  int i = 0
  Scanner in = new Scanner(System.in);
  while(in.hasNext()) //How do I determine when to end?
  {
    //code
    i++;
    if(i==3){

     //Doing my calculation
     break;
    }
}

}

如果输入是
系统。在
中,我会这样做:

Scanner s = new Scanner(System.in);

int r, b, p, m;

while (true) {
    b = Integer.parseInt(s.nextLine());
    p = Integer.parseInt(s.nextLine());
    m = Integer.parseInt(s.nextLine());

    r = doYourWoodooMagic(b, p, m);

    System.out.println(r);

    s.nextLine(); //devour that empty line between entries
}
所以有一个问题:为什么要在打印r后“吞食”这一空行?简单回答:在最后一组三个数字之后,可能根本不会有任何行,因此
s.nextLine()将永远被卡住

我不知道UVa Online Judge的情况,但我制作了类似的程序,在获得正确的输出后终止了您的程序,所以这个解决方案很好,但我不知道UVa Online Judge是如何工作的

如果那不起作用

如果Judge仍然给出错误,请替换
s.nextLine()使用稍微复杂一些的代码:

while (true) {
    // ...

    if(s.hasNextLine()) {
        s.nextLine(); //devour that empty line between entries
    } else {
        break;
    }
}
但是,如果在必须输入的最后一个数字之后还有一个空行,则输入将以最后一个数字结束

while (true) {
    // ...

    s.nextLine(); //devour that empty line between entries
    if(!s.hasNextLine()) {
        break;
    }
}
吃最后一条空行可能会有帮助:


这是来自Online Judge的示例Java代码,您可以自定义void Begin()并在那里进行计算

为什么要使用循环?你必须读3个数字。简单地用in.nextLine()读取数字,然后根据我的在线经验计算结果,判断他们使用的输入可能与描述中的输入不同,但我会尝试在3后中断,看看我得到了什么答案。我尝试将循环设置为仅循环3次,这给了我错误的答案。换句话说,他们可能期望计算更多的输入。为什么循环?您只需要使用.nextInt()中的
读取3个整数,不需要循环!当使用扫描仪时,我会使用
nextLine()
hasNextLine()
next()
hasNext()
但我不会将它们混合在一起,它可以在行尾等处给你空字符串。但是这个解决方案要求我知道输入集的数量,这不是我想要的。或者可能我在我发布的链接中的问题描述中遗漏了一些东西,因为我的代码将由在线计算机运行。如果您查看下面的链接,您将看到唯一允许的输入类型和预期的输出。这是通过使用他们在示例代码中使用的相同方法解决的。谢谢
while (true) {
    // ...

    if(s.hasNextLine()) {
        s.nextLine(); //devour that empty line between entries
    } else {
        break;
    }
}
while (true) {
    // ...

    s.nextLine(); //devour that empty line between entries
    if(!s.hasNextLine()) {
        break;
    }
}