2017-01-27 14 views
-1
import java.util.*; 

public class GuessNumber{ 
    public static void main(String[]args){ 
     Scanner in = new Scanner(System.in); 
     int x = 0; 
     String num = "65854"; // This is the secret code 
     String s; 
     System.out.println("This program asks you to guess the code of 5 digits. "); 
     System.out.println("You have 5 attempts. "); 

     for(int i=0; i<5; i++){ 
      do{ 
       s = in.nextLine(); 


       for(int c=0; c<s.length(); c++){ 
        if(s.charAt(c)==num.charAt(c)) //if digit in 's' equals the digit in the same position in 'num', increment variable x 
         x++; 
       } 

       System.out.println("Number of correct digits in right position: " + x); // here the execution goes out of bounds 
      } 
      while(!s.equals(num)); 
      System.out.println("Congrats! You guessed the secret code. "); 
      System.exit(0); 

     } 
    } 
} 

사용자가 다섯 자리 숫자의 접두어로 된 코드를 추측 할 수있게 해주는 간단한 자바 프로그램을 만들려고했습니다. do-while 루프는 처음 두 번의 시도에 대해서만 올바른 값을 표시 한 다음 범위를 벗어납니다 (값이 5보다 큼 (5 자리 숫자의 코드에서는 불가능). 왜 누군가가 설명 할 수 있습니까?루프가 제대로 작동하지 않습니다.

+2

* 무엇이 범위를 벗어나니까? 오류가 정확히 어디에 있습니까? 기본적으로 무수히 많은 추측을하는'do/while' 루프가있는 이유는 무엇입니까? "값> 5"로 무엇을 의미합니까? "값"변수가 없습니다. (힌트 : 사용자 입력의 다음 줄을 읽을 때'x '를 0으로 재설정하지 않는 것이 유일한 문제 일 수 있습니다 ...) –

+1

'if (s.charAt (c) == num.charAt c))'-'num'은 접두사가'5'이고's'는 사용자 입력에서옵니다. 's'가'num'보다 길면 어떻게됩니까? – BackSlash

+0

's'에 대한 제한을 정의해야한다는 뜻입니까? – catzbro1

답변

0

do-while 루프를 제거하십시오. 사용자가 올바른 코드를 추측 할 때까지 실행됩니다. 코드를 다음
삽입 당신은 입력 문자열에서 아무 문자에 대한 더 많은 제한을 추가 할 수 있습니다 문자열

의 길이
if(s.length()!=5){ 
    System.out.println("code should be of length 5"); 
    continue; 
} 

을 확인합니다. 또한 외부 루프 시작시마다 x을 재설정하십시오. 입력 문자열마다 외부 루프에 맞는지

또한 확인

if(s.equals(num)){ 
    System.out.println("Congrats! You guessed the secret code. "); 
    System.exit(0); 
} 
+0

이것은 사실이 아닙니다! 당신은 정확하게 5 기회가 있어야합니다! –

+0

당신은 기회를 무시합니다 –

+0

@Mohsen_Fatemi 정확한 숫자의 문자를 제공하지 않는다면 여전히 사용자가 시도를 사용하고있는 것 같아 –

0

현재 코드 -

for (int i = 0; i < 5; i++) { 
    do { 
     s = in.nextLine(); 
     for (int c = 0; c < s.length(); c++) { // the length of s can exceed 5 as of **num = "65854"** 
      if (s.charAt(c) == num.charAt(c)) //if digit in 's' equals the digit in the same position in 'num', increment variable x 
      x++; 
      System.out.println("Number of correct digits in right position: " + x); 
     } 
     } 
     while (!s.equals(num)); // this ensures currently N number of attempts NOT JUST 5 as stated otherwise. 
     System.out.println("Congrats! You guessed the secret code. "); 
     System.exit(0); // with this line the for loop would execute just once 
} 

하기 권장 코드 -

,912,853 당신은 당신이 처음에는 do-while를 제거해야하므로 그 조건이 !s.equals(num) 말하는 것을 do-while을 가지고 있기 때문에210
+0

Pro Tipp :'count> = 5'를 확인하십시오. – Fildor

+0

@Fildor - 어쨌든'>'이 변경 될 수 있습니까? – nullpointer

+1

그곳에갔습니다. 동료가 코드를 변경하므로 카운트가 "5"로 건너 뜁니다. 그렇다면 당신은 다시 영원히 돌아갑니다 ... – Fildor

0

이 코드는 예측 코드가 동일한 경우는,이 ​​켜지지 아닌, 이제까지 당신이 진정한 코드를 입력 이후에 거 실행 num이면 변수 x5과 같아야하므로 인쇄 성공 후 return 문을 사용하여 프로그램을 종료 할 수 있습니다. x의 값을 알고 있어야하며, 각 반복마다 0과 같아야합니다. 즉, x=0을 의미합니다!

for(int i=0; i<5; i++){ 
    s = in.nextLine(); 
    if(s.length!=5){ 
     System.out.println("code should be of length 5"); 
     continue; 
    } 
    x = 0; 
    for(int c=0; c<5; c++){ 
     if(s.charAt(c)==num.charAt(c)) //if digit in 's' equals the digit in the same position in 'num', increment variable x 
     x++; 
    } 
    System.out.println("Number of correct digits in right position: " + x); // here the execution goes out of bounds 
    if(x==5){ 
     System.out.println("Congrats! You guessed the secret code. "); 
     return; 
    } 
} 
System.out.println("Sryy !! :(("); 
관련 문제