这是本人看完循环之后写出来的程序,有点错误改了很久没有改出来,请各位大虾帮帮忙
这是一个猜数字的游戏,数字随机产生,然后输入数字直到猜对为止。
package com.shijian.ch04;
import java.math.*;
import java.io.*;
public class Guess
{
int i,num;
char s;
public void beginG() throws java.io.IOException
{
while(true)
{
System.out.println("Do you want to play the number-guess game?");
System.out.println("(y/n)?");
s=(char)System.in.read();
//System.out.println(s);
switch(s)
{
case 'y':GuessN();
case 'n':System.exit(1);
}
}
}
public void GuessN() throws java.io.IOException
{
num=(int)(100*Math.random());
for(;;)
{
System.out.println("Please input a number between 0-100:");
System.out.print("What is it:");
do
{
i=System.in.read();
}while(i=='\n'||i=='\r');
//System.out.println(i);
if(i==num)
{
System.out.println("you are talent");
break;
}
else
{
if(i<num)
{
//System.out.println("the "+i+" is lower than "+num+",try it again");
System.out.println("the "+i+" is lower than the nummber,try it again");
continue;
}
else
{
//System.out.println("the "+i+" is larger than "+num+",try it again");
System.out.println("the "+i+" is larger than the number,try it again");
continue;
}
}
}
}
}
package com.shijian.ch04;
import java.io.*;
public class TestGuess
{
public static void main(String args[]) throws java.io.IOException
{
System.out.println("Welcome to the game");
Guess g;
char s;
while(true)
{
g=new Guess();
g.beginG();
System.out.println("Would you like to play it again?");
s=(char)System.in.read();
switch(s)
{
case 'y':continue;
case 'n':System.exit(1);
}
}
}
}
谢谢
----------------解决方案--------------------------------------------------------
有什么问题?
----------------解决方案--------------------------------------------------------
我输入10,i就变成了49;输入21,i就变成了50,这是怎么回事啊?
----------------解决方案--------------------------------------------------------
它读入的是ascii码
1的ASCII码是49,2的ASCII码是50
你应该用一个完整的流来读完整的数
你可以用Scanner或者用别的来读它
----------------解决方案--------------------------------------------------------
请问版主应该怎么改比较好,我的jdk是1.4.2的,谢谢!!
----------------解决方案--------------------------------------------------------
用java.io;下的
BufferedReader
它有readLine()方法 读进来String 再转换就可以了
例如:
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String temp = br.readLine();
... 转换....就可以了
[此贴子已经被作者于2006-12-25 22:29:28编辑过]
----------------解决方案--------------------------------------------------------