这个是我做的一个练习,但是不管你输入什么数都得不到“你答对了”,不知道哪错了,比如我输入的81,就输出太大,输入80则输出太小。而已经经过数据的强制转换到INT行了,是不是哪个方法错了?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class TestRandom { public static void main(String[] args) throws IOException {
int i= (int) Math.floor(Math.random()*106+20);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
int y;
System.out.println("请输入一个数字:");
str= br.readLine();
y = Integer.parseInt(str);
while(y!=i){
if(Integer.parseInt(str)>i)
{
System.out.println("你输入的数字太大了");
}else{
System.out.println("你输入的数字太小了!");
}
System.out.println("请输入的数值:");
str = br.readLine();
}
System.out.println("恭喜你答对了!答案是:" + str);
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class TestRandom { public static void main(String[] args) throws IOException {
int i= (int) Math.floor(Math.random()*106+20);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
int y;
System.out.println("请输入一个数字:");
str= br.readLine();
y = Integer.parseInt(str);
while(y!=i){
if(Integer.parseInt(str)>i)
{
System.out.println("你输入的数字太大了");
}else{
System.out.println("你输入的数字太小了!");
}
System.out.println("请输入的数值:");
str = br.readLine();
}
System.out.println("恭喜你答对了!答案是:" + str);
}
}
你的while循环出问题了
while(y!=i){
if(Integer.parseInt(str)>i)
{
System.out.println("你输入的数字太大了");
}else{
System.out.println("你输入的数字太小了!"); }
System.out.println("请输入的数值:");
str = br.readLine();
y = Integer.parseInt(str);//新加的
}
循环判定的条件是y
所以每次循环必须给y重新赋值
要不然你的y值一直是你第一次输入的数值(str)