iT邦幫忙

0

發問Java 猜數字遊戲

  • 分享至 

  • xImage

大家好 最近剛開始在學java
遇到一些問題想請教

有個題目設定是在0-99之間猜一數字
若猜錯的話系統會以(min,max)回覆猜過的區間

假設答案是80
若玩家猜到(79,81)系統會顯示GG
想請問這個條件應該怎麼加進程式碼裡面?
我的邏輯好像有點錯誤 但不知道應該從哪邊調整...

import java.util.Scanner;

public class NumberGuess {

public static void main(String[] args) {
	// TODO Auto-generated method stub
	
	int N = (int)(Math.random()*100);
	int min = 0;
	int max = 99;
	
	System.out.println("guess a number between 0~99:");
	Scanner input = new Scanner(System.in);
	
	int A = input.nextInt();
	
	while (A != N) {
		
		if (A<0 || A>99) {
			System.out.println("Out of range, try again?");
			A = input.nextInt();
		}
		else if (A==min+1 && A==max-1) {
			System.out.println("GG");
		}
			
		else if (A>N) {
			max = A;
			System.out.println("("+min+","+max+")?");
			A = input.nextInt();
		}
		else if (A<N) {
			min = A;
			System.out.println("("+min+","+max+")?");
			A = input.nextInt();
			
		}
	
		
	}
	System.out.println("You win!");
	

}
}

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
johncoc
iT邦新手 3 級 ‧ 2022-10-31 16:24:53
最佳解答
	while (A != N) {
		
		if (A<0 || A>99) {
			System.out.println("Out of range, try again?");
			A = input.nextInt();
		}
		else if (A==min+1 && A==max-1) {
			System.out.println("GG");
		}
			
		else if (A>N) {
			max = A;
			System.out.println("("+min+","+max+")?");
			A = input.nextInt();
		}
		else if (A<N) {
			min = A;
			System.out.println("("+min+","+max+")?");
			A = input.nextInt();
			
		}
	
		
	}

改成

	while (A != N) {
		
		if (A<0 || A>99) {
			System.out.println("Out of range, try again?");			
		}			
		else if (A>N) {
			max = A;
			System.out.println("("+min+","+max+")?");
		}
		else if (A<N) {
			min = A;
			System.out.println("("+min+","+max+")?");			
		}
        
        if (min==N-1 && max==N+1) {
            System.out.println("GG");
        }
        
        A = input.nextInt();
	
		
	}

我要發表回答

立即登入回答