本帖最后由 刘治广 于 2013-5-17 22:49 编辑
package home_work;
import java.util.InputMismatchException;
import java.util.Scanner;
public class CaiZi {
/**
* @param args
* InputMismatchException
*/
public static void main(String[] args) {
System.out.println("你一共输入了"+guess()+"才猜对");
}
public static int guess() {
int num=(int)(Math.random()*100+1);
int min=1;
int max=100;
int count=0;
while(true){
Scanner sc = new Scanner(System.in);
count++;
System.out.println("请输入"+min+"-"+max+"之间的整数");
int x=sc.nextInt();
if (num == x)
{
System.out.println("恭喜你猜对了");
break;
}
else if(num>x)
{
System.out.println("你输入的"+x+"数字小了");
min=x+1;
}
else if(num<x)
{
System.out.println("你输入的"+x+"大了");
max=x-1;
}
}
return count;
}
}
这段代码怎么加异常啊,异常就是输入字符的时候能抛出异常 |
|