2016-09-24 59 views
-2

所以这里的问题是,当我尝试再次运行它不会做任何事情。 它会运行一次,然后休息。我知道我没有使用currentTimeMillis,没有人知道这里有什么问题。如果你有一些改进我的代码的建议可以随意告诉我,我不擅长编码。 是的,我试图在网上看an but,但我没有找到任何东西。对不起,英文不好!Java:扫描仪行为调试

public static String list(ArrayList<String> lause2) { 
    Collections.shuffle(lause2); 
    String pleb = lause2.get(lause2.size() - 1); 

    return pleb; 
} 

public static void main(String[] args) throws Exception { 
    Scanner printer = new Scanner(System.in); 
    ArrayList<String> lause2 = new ArrayList<>(); 
    ArrayList<Integer> keskiarvo = new ArrayList<>(); 

    long start = System.currentTimeMillis(); 
    long end = start + 10 * 6000; 
    int laskuri = 0; 

    boolean go = true; 
    boolean run = true; 

    System.out.println("Welcome to Typefaster"); 
    System.out.println("Program will give you random words you will write them as fast as you can for an minute if you fail ones it's over Good luck!"); 

    lause2.add("hello"); 
    //Loads of different lause2.add("random"); 
    lause2.add("vacation"); 

    System.out.println(list(lause2)); 
    while (System.currentTimeMillis() < end) { 
     laskuri++; 
     String something = list(lause2); 
     System.out.println("Write " + something); 
     String kirjoitus = printer.nextLine(); 
     if (kirjoitus.equals(something)) { 
      System.out.println("yee"); 
     } else { 
      break; 

     } 

    } 
    System.out.println("You wrote " + laskuri + " words"); 
    keskiarvo.add(laskuri); 
    int laskuri2 = 0; 



     System.out.println("Run again?"); 

    char again = printer.next().charAt(0); 
    if (again == 'y') { 
     run = true; 

    } else if (again == 'n') { 
     System.out.println("Byebye"); 
     go = false; 
    } 

    long start2 = System.currentTimeMillis(); 
    long end2 = start2 + 10*6000; 

    while (System.currentTimeMillis() < end2 && run) { 
     laskuri2++; 
     String something1 = list(lause2); 
     System.out.println("Write " + something1); 
     String kirjoitus1 = printer.nextLine(); 
     if (kirjoitus1.equals(something1)) { 
      System.out.println("yee"); 
     } else { 
      break; 

     } 
     System.out.println("You wrote " + laskuri2 + " words"); 
     keskiarvo.add(laskuri2); 

    } 

} 
+0

标题是有点误导,因为你已经确定了错误的源作为代码的漏洞。 – Zabuza

回答

0

如果你知道Scanner是如何工作的,答案相当简单。在第二次运行中,您有以下行:

String kirjoitus1 = printer.nextLine(); 

您认为该方法现在等待用户执行一些输入。然后你比较它在第一次运行等。显然你的第二个循环执行break。为什么?您可以通过将System.out.println("Debug: " + kirjoitus1);放在它的前面来轻松检查。 你看,这个值是一个空文本,它不等于something1,所以break得到执行。

为什么文本是空的而不是等待用户输入?您的Scanner的最后一次使用是在这一行:

char again = printer.next().charAt(0); 

此时的方法next没有等待用户输入。 但是它只读取书面输入的第一个标记。输入的其余部分保留在Scanner的内部缓冲区中。所以在这种方法Scanner我们还有一些未读的输入还剩,它会在下次调用nextLine()时返回这个未读的东西。

所以你需要做的是清除yes/no后的缓冲区。你可以简单地做,通过使用nextLine()代替next()这里:

char again = printer.nextLine().charAt(0); 

更多信息的文档:api/.../Scanner.html