2013-09-16 48 views
1

我目前正试图解决onlinge判断器上的以下问题:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=310Java读取来自CONSOL的粘贴输入,然后停止

我不知道如何来确定何时程序应该退出,换言之,当我应该停止输入回路和退出程序?

示例代码:

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 
    } 
} 

我唯一的想法就是让当所有输入已经在控制台被粘贴输入读卡器停止,但我不知道我将如何做到这一点。

+2

你为什么要使用一个循环?你必须阅读3个数字。简单地用in.nextLine()读取数字,然后计算结果 – JohnnyAW

+0

从我在Online Judge的小经验中,他们使用的输入可能与描述中的输入不一样,但我会尝试在3之后中断并查看我得到答案 – AbbeHall

+0

我试图设置循环只循环3次,这给了我错误的答案。换句话说,他们可能希望计算更多的投入。 – AbbeHall

回答

0

你可以尝试这样的事情

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

你必须使用一个技巧像上面打破while循环。否则在循环继续运行。

我输入:

hi 
hi 
hi 
hi 
hi 

输出地说:

[hi, hi, hi, hi, hi] 
+0

使用扫描仪时,我会使用'nextLine()'和'hasNextLine()'或'next()'和'hasNext()',但我不会混合在一起,它可以给你在行尾等空字符串 – kajacx

+0

但是这个解决方案要求我知道输入组的数量,这不是我正在寻找的确切的东西。或者,也许我错过了我发布的链接中的问题描述 – AbbeHall

0

决定输入这是一个破碎的条件。例如, “EXIT”
然后

if(in.nextLine().equalsIgnoreCase("EXIT")){ 
    break; 
    } 

或者,如果没有可能,这样

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; 
    } 
} 

}

+0

无法工作,因为我的代码将由Online Judges计算机运行。如果您查看下面的链接,您将选择允许的唯一输入类型和预期输出。 http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=310 – AbbeHall

+0

我添加了一个变体 – blackbird014

0

如果输入System.in我这样做:

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在线法官,但我做了类似的程序,得到正确的输出后终止您的程序,所以这种解决方案将是好的,但我不知道如何UVA在线法官的作品。

如果不工作

如果法官仍给你的错误,很少有更复杂的代码替换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; 
    } 
} 

吃,是最后一个空行