2013-08-29 2 views
0

메서드 내에서 2 초 동안 기다렸다가 다시 실행을 반복하는 메서드가있는 randomText() 메서드를 실행하려고합니다. 매번 난수 1 또는 0을 만들어야합니다. 0이면 LEFT를 표시하고 1이면 오른쪽을 표시합니다. 그러나 실제로는 항상 LEFT를 표시하고 변경되지 않습니다! 스레드 문제 또는 원래 코드인지 여부는 알 수 없습니다.메서드에서 중첩

public class MainActivity extends Activity { 
Scanner in = new Scanner(System.in); 

Button left , right ; 
TextView text ; 
int value , mistake , pressed ; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    //value = 0; // 0:left 1:right 2:didnt pressed any 
    mistake = 0; // max mistake = 3 

    left = (Button) findViewById(R.id.button1); // value of the key is 0 
    right = (Button) findViewById(R.id.button2); // value of the key is 1 
    text = (TextView) findViewById(R.id.textView1); 
    randomText(); 
    //*** set actions 

    left.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      pressed = 1; 
      if(value != 0)  { mistake++; } 
     } 
    }); 
    right.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      pressed = 1; 
      if(value != 1)  { mistake++; } 
     } 
    }); 

} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

public void randomText(){ 
    Random r = new Random(); 
    for (int i=0;i<10 && mistake <=2 ;i++){ 
     value = r.nextInt(2); 
     pressed = 0; // 
     if (value == 1) 
      text.setText("RIGHT"); 
     else 
      text.setText("LEFT"); 
     try { 
       Thread.sleep(2000); 
      } catch (InterruptedException e) { 
       // We've been interrupted 

      } 

     if (pressed == 0) mistake++; 
    } 
} 
} 
+0

실행이 100 배를 볼 - 그 난수의 아름다움, 그들은 반복 할 수 있습니다 값 "0"으로 99 번, "1"또는 없음으로 한 번만. 코드에서 알 수 있듯이,'Textview'의이 텍스트를 2 초 간격으로 (무작위로) 바꿀 수 있습니다 - 맞습니까? – g00dy

답변

0

하나의 경우, 당신은 주 스레드에서 randomText()를 호출하고 있습니다. 즉, 루프 내에서 0을 눌렀으므로 다른 스레드에서 변경하지 않으면 0으로 유지됩니다. 버튼 클릭은 또한 주 스레드에서 발생하므로 randomText()가 실행되는 동안 다른 버튼을 눌렀을 때 변경할 수 없습니다.

즉, text.setText()를 호출하기 전에 randomText() 메서드에서 정확히 세 번 반복됩니다.

또한 임의의 r에 대해 Random (long seed) 생성자를 호출해야합니다. 그것은 일반적으로 당신의 임의의 객체가과 같이 초기화 할 필요가 있으므로, 씨앗의 현재 시간을 사용하는 것이 좋습니다 :이 정말 무작위 경우

Random r = new Random(System.currentTimeMillis()); 
관련 문제