mport java.io.*;
public class basic
{public static void main(String args[])
{
InputStreamReader ir;
BufferedReader in;
ir =new InputStreamReader(System.in);
in =new BufferedReader(ir);
int ranNum=(int)(Math.random()*10+1);
int guessNum=-1;
String str;
while(guessNum!=ranNum)
{
try{
System.out.print("Please Input:");
str=in.readLine();
guessNum=Integer.parseInt(str);
}
catch(Exception e)
{
}
if(guessNum>ranNum)
System.out.print("Try smaller......");
else
System.out.print("Try bigger......");
}
System.out.print("Great!");
}
}
我去掉try...catch..语句后:
mport java.io.*;
public class basic
{public static void main(String args[]) throws Exception
{
InputStreamReader ir;
BufferedReader in;
ir =new InputStreamReader(System.in);
in =new BufferedReader(ir);
int ranNum=(int)(Math.random()*10+1);
int guessNum=-1;
String str;
while(guessNum!=ranNum)
{
System.out.print("Please Input:");
str=in.readLine();
guessNum=Integer.parseInt(str);
if(guessNum>ranNum)
System.out.print("Try smaller......");
else
System.out.print("Try bigger......");
}
System.out.print("Great!");
}
}
public class basic
{public static void main(String args[])
{
InputStreamReader ir;
BufferedReader in;
ir =new InputStreamReader(System.in);
in =new BufferedReader(ir);
int ranNum=(int)(Math.random()*10+1);
int guessNum=-1;
String str;
while(guessNum!=ranNum)
{
try{
System.out.print("Please Input:");
str=in.readLine();
guessNum=Integer.parseInt(str);
}
catch(Exception e)
{
}
if(guessNum>ranNum)
System.out.print("Try smaller......");
else
System.out.print("Try bigger......");
}
System.out.print("Great!");
}
}
我去掉try...catch..语句后:
mport java.io.*;
public class basic
{public static void main(String args[]) throws Exception
{
InputStreamReader ir;
BufferedReader in;
ir =new InputStreamReader(System.in);
in =new BufferedReader(ir);
int ranNum=(int)(Math.random()*10+1);
int guessNum=-1;
String str;
while(guessNum!=ranNum)
{
System.out.print("Please Input:");
str=in.readLine();
guessNum=Integer.parseInt(str);
if(guessNum>ranNum)
System.out.print("Try smaller......");
else
System.out.print("Try bigger......");
}
System.out.print("Great!");
}
}
try{
System.out.print("Please Input:");
str=in.readLine();
guessNum=Integer.parseInt(str);
}
catch(IOException e)
{
//对应readLine()
}
catch(NumberFormatException e){
//对应parseInt(str)
}
第二段代码里,你想不捕捉异常,把他吞掉,就要在main后面加上
public static void main(String[] args) throws IOException,NumberFormatException{
//不用再写try catch子句
}
不过由于是main函数,已经没有代码能处理异常,使用不建议这样做。