0

スレッドだからプログラムの目的は、ユーザが1秒(のThread.sleepの期間)内に番号を入力しない場合、すなわちスレッドの終了後、このforループをどのように続けるのですか?

import java.util.Scanner; 
public class FastMath 
{ 
    public static void main(String[] args) 
    { 
     System.out.println("How many questions can you solve?"); 
     Scanner in = new Scanner(System.in); 
     int total = in.nextInt(); 
     MissedThread m = new MissedThread(); 
     int right = 0; 
     int wrong = 0; 
     int missed = 0; 

     for(int i = 0;i<total;i++) 
     { 
      int n1 = (int)(Math.random()*12)+1; 
      int n2 = (int)(Math.random()*12)+1; 
      System.out.print(n1+" * "+n2+" = "); 
      m.start(); 
      int answer = in.nextInt(); 
      if(answer==n1*n2) 
      { 
       right++; 
       continue; 
      } 
      if(answer!=n1*n2) 
      { 
       wrong++; 
       continue; 
      } 
     } 
    } 
} 

前述のスレッドを使用

public class MissedThread extends Thread 
{ 
    public synchronized void run() 
    { 
     try 
     { 
      Thread.sleep(1000); 
      System.out.println("Too slow"); 
     }catch(InterruptedException e){return;} 
    } 
} 

プログラムを使用メッセージを出力し、次の繰り返しに進む。しかし、時間内に答えが出たら、プログラムを止めるだけです。そして、それが時間内に答えられなければ、それは立ち往生し、forループの次の反復に移動しないように思われる。

+0

これには「スレッド」を使用する必要がありますか?実装が容易な他のソリューションもあります。 – KDecker

+0

'Thread'ではなく' Runnable'を拡張します。 'run'メソッドを同期させないでください。 'InterruptedException'を扱う方法を研究します。ここではそうしません。冗長な 'return'と' continue'文を取り除く。あなたのメインスレッドはタイミングスレッドを待たないので、後者は効果がありません。スレッドは情報を共有しないので、時間制約が違反しているかどうかをメインスレッドが知る方法はありません。 –

答えて

1

別のスレッドからの回答を待つ必要はありません。これは、1つのスレッドを使用して行う方法です:

public class FastMath { 

    public static void main(String[] args) throws IOException { 
     int answer; 

     System.out.println("How many questions can you solve?"); 

     BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 

     int total = Integer.valueOf(in.readLine()); 

     int right = 0; 
     int wrong = 0; 
     int missed = 0; 

     for (int i = 0; i < total; i++) { 
      int n1 = (int) (Math.random() * 12) + 1; 
      int n2 = (int) (Math.random() * 12) + 1; 
      System.out.print(n1 + " * " + n2 + " = "); 

      long startTime = System.currentTimeMillis(); 
      while ((System.currentTimeMillis() - startTime) < 3 * 1000 
        && !in.ready()) { 
      } 

      if (in.ready()) { 
       answer = Integer.valueOf(in.readLine()); 

       if (answer == n1 * n2) 
        right++; 
       else 
        wrong++; 
      } else { 
       missed++; 
       System.out.println("Time's up!"); 
      } 
     } 
     System.out.printf("Results:\n\tCorrect answers: %d\n\nWrong answers:%d\n\tMissed answers:%d\n", right, wrong, missed); 
    } 
} 
関連する問題