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 자리 숫자의 코드에서는 불가능). 왜 누군가가 설명 할 수 있습니까?루프가 제대로 작동하지 않습니다.
* 무엇이 범위를 벗어나니까? 오류가 정확히 어디에 있습니까? 기본적으로 무수히 많은 추측을하는'do/while' 루프가있는 이유는 무엇입니까? "값> 5"로 무엇을 의미합니까? "값"변수가 없습니다. (힌트 : 사용자 입력의 다음 줄을 읽을 때'x '를 0으로 재설정하지 않는 것이 유일한 문제 일 수 있습니다 ...) –
'if (s.charAt (c) == num.charAt c))'-'num'은 접두사가'5'이고's'는 사용자 입력에서옵니다. 's'가'num'보다 길면 어떻게됩니까? – BackSlash
's'에 대한 제한을 정의해야한다는 뜻입니까? – catzbro1