随机生成一个字符a-z之间 然后猜这个产生的字符是什么但我的程序会多运行两行,帮我看下这是为什么啊?
import java.io.*;
class MyException extends Exception
{public String toString()
{return "输入值应在a-z之间!";}
};
public class lettergame
{
public static void main(String args[])
{
String charstring=new String("abcdefghijklmnopqrstuvwxyz");
int number=(int)(Math.random()*26);
char a=charstring.charAt(number);
System.out.println(a);
boolean flag=true;
String str="";
int i=0;
char ch=0;
while(flag)
{
try { if (ch==0)
{ System.out.println("请输入字符:");
ch=(char)System.in.read();
if ((ch<'a')||(ch>'z'))
{throw new MyException();
}
i=i+1;
str="";
if (ch>a)
{str="你猜大了,你共猜了:"+i+"次!";
flag=true;
System.out.println(str);
}
else
if(ch<a)
{str="你猜小了,你共猜了:"+i+"次!";
flag=true;
System.out.println(str);
}
else
{flag=false;
str="你猜对了,你共猜了:"+i+"次!";
System.out.println(str);}
}
ch=0;
}
catch (Exception e)
{System.out.println(e);}
}
}
}
import java.io.*;
class MyException extends Exception
{public String toString()
{return "输入值应在a-z之间!";}
};
public class lettergame
{
public static void main(String args[])
{
String charstring=new String("abcdefghijklmnopqrstuvwxyz");
int number=(int)(Math.random()*26);
char a=charstring.charAt(number);
System.out.println(a);
boolean flag=true;
String str="";
int i=0;
char ch=0;
while(flag)
{
try { if (ch==0)
{ System.out.println("请输入字符:");
ch=(char)System.in.read();
if ((ch<'a')||(ch>'z'))
{throw new MyException();
}
i=i+1;
str="";
if (ch>a)
{str="你猜大了,你共猜了:"+i+"次!";
flag=true;
System.out.println(str);
}
else
if(ch<a)
{str="你猜小了,你共猜了:"+i+"次!";
flag=true;
System.out.println(str);
}
else
{flag=false;
str="你猜对了,你共猜了:"+i+"次!";
System.out.println(str);}
}
ch=0;
}
catch (Exception e)
{System.out.println(e);}
}
}
}
b
请输入字符:
a
你猜小了,你共猜了:1次
请输入字符:
输入值应在a-z之间!
请输入字符:
输入值应在a-z之间!
请输入字符:下面的4行不要掉!!!! 帮我看下错哪了?
你定义的:char ch=0;
if ((ch<'a')||(ch>'z'))
字符的比较实际上是比较其各自对应的ascii码,而a--z的ascii码都大于0,故此处永真,所以每次都会输出你所定义的异常。
System.in.read(bytes);
ch = (char) bytes[0];