我正在尝试获取用户输入的最高和最低数字。下面的代码似乎主要是工作,但我似乎无法获得最低值的正确数字。我做错了什么?
import java.io.*;
public class jem3
{
public static void main(String []args)
{
BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in ));
int high=0;
int lowest=1;
int num=0;
int A=0;
System.out.println("Enter number");
for(int a=0;a<10;a++)
{
try
{
num=Integer.parseInt(dataIn.readLine());
}
catch(IOException e)
{
System.out.println("error");
}
if(num>high)
{
high=num;
}
if(num>=A)
{
A=lowest;
}
}
System.out.println("highest is:"+ high);
System.out.println("lowest is: "+A);
}
}
答案 0 :(得分:1)
A
的目的是什么?你也没有修改lowest
。你很亲密,试试这个:
num = ...
if ( num > max ) max = num;
if ( num < min ) min = num;
System.out.println("Highest: " + max);
System.out.println("Lowest: " + min);
答案 1 :(得分:-1)
import java.io.*;
public class jem3
{
public static void main(String []args)
{
BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in ));
int high;
int lowest;
int num;
System.out.println("Enter number");
num=Integer.parseInt(dataIn.readLine());
lowest = highest = num;
for(int a=0;a<10;a++)
{
try
{
num=Integer.parseInt(dataIn.readLine());
}
catch(IOException e)
{
System.out.println("error");
}
if(num>high)
{
high=num;
}
if(num<lowest)
{
lowest=num;
}
}
System.out.println("highest is:"+ high);
System.out.println("lowest is: "+lowest);
}
}
我在读取第一行后添加代码设置为高和最低,所以如果用户给你10个数字'9',它将输出最低数字为'9'而不是1(与高相似)。
答案 2 :(得分:-1)
您正在抓住highest
的正确轨道。您需要为lowest
应用类似的逻辑。
答案 3 :(得分:-1)
import java.io.*;
public class jem3{
public static void main(String []args){
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
int high=0;
int lowest=0;
int num=0;
boolean test = true;
System.out.println("Enter number");
for(int a=0;a<10;a++)
{
try
{
num=Integer.parseInt(dataIn.readLine());
}
catch(IOException e)
{
System.out.println("error");
}
if(num>high)
{
high=num;
}
//add an initial value to 'lowest'
if (test)
lowest = num;
test = false;
if(num < lowest)
{
lowest = num;
}
}
System.out.println("highest is:"+ high);
System.out.println("lowest is: "+ lowest);
}
}