2012/03/24

[java]猜數字


package kevin.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class GuessApp
{

/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException
{
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int Guess; //存放使用者輸入的數字
int Ans; //存放隨機產生的數值(答案)

Ans = (int)(Math.random()*100+1); //Math.random()產生的型別為double(介於0.0~1.0),需用(int)轉換成int型別

for(int i=5; i>0; i--)
{
System.out.print("請猜一個數字:");
Guess = Integer.parseInt(br.readLine());

if(Guess == Ans)
{
System.out.println("恭喜您!答對了!");
break;
}
else if(Guess < Ans)
{
System.out.println("再大一點,您還剩下"+(i-1)+"次機會");
}
else if(Guess > Ans)
{
System.out.println("再小一點,您還剩下"+(i-1)+"次機會");
}
}

System.out.println("正解為:"+Ans);
}

}