자바 코드에 조건을 추가하면 사용자는 4 개 시도를 할 수있는

SAMER g :

나는 사용자가 0부터 9까지 임의의 숫자를 입력하고 숫자를 추측하는이 코드를 가지고 있지만 그가 잘못 4 번 짐작하면 내가 4 사용자의 시련을 제한 할 수 있도록 시스템이 중지되고 디스플레이는 메시지가 "당신은 당신의 허용 초과 시험 "이 내 코드는 지금까지 있습니다 :

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int nb,x;
    int count= 0;
    Scanner inp= new Scanner(System.in);
    nb= (int)(Math.random()*10);
    System.out.print("Guess the number between 0 and 9");
    x=inp.nextInt();

    while(x!= nb) {
        if(x>nb) System.out.println("Lesser");
        else if (x<nb) System.out.println("Bigger");
        System.out.println("Try another Number");
        x=inp.nextInt();
        count++;

    }

    System.out.println("Found!!");
    System.out.println("Number of Guesses:" +count);


    inp.close();

}
셰리 :

당신은 또한 당신에게 사용 할 수 있습니다 count당신이 파괴하여 프로그램을 종료 할 수 있습니다 한계와 사용자 끝나면 시도의 트랙을 유지하기 위해 변수를 while사용하여 루프 break문을.

import java.util.Scanner;
public class Main
{
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    int nb,x;
    int count= 1;
    Scanner inp= new Scanner(System.in);
    nb= (int)(Math.random()*10);
    System.out.print(nb);
    System.out.print("Guess the number between 0 and 9:");
    x=inp.nextInt();

    while(x!= nb) {
        if (count <= 3){
        if(x>nb) System.out.println("Lesser");
        else if (x<nb) System.out.println("Bigger");
        System.out.println("Try another Number");
        x=inp.nextInt();
        }
        else{
            System.out.print("you exceeded your allowed trials");
            break;

        }
        count++;

    }

    System.out.println("Found!!");
    System.out.println("Number of Guesses:" +count);


    inp.close();

   }
}

추천

출처http://43.154.161.224:23101/article/api/json?id=365376&siteId=1