[英]How do I determine the highest and lowest value in user-entered input?
I'm trying to get the highest and lowest numbers entered by the user. 我正在尝试获取用户输入的最高和最低数字。 The code below seems to be mostly working but I can't seem to get the right number for the lowest value.
下面的代码似乎在大多数情况下都可以正常工作,但是我似乎无法获得最低值的正确数字。 What am I doing wrong?
我究竟做错了什么?
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);
}
}
What is the purpose of A
? A
的目的是什么? You're not modifying lowest
either. 您也没有修改
lowest
。 You're close, try this: 您接近了,试试这个:
num = ...
if ( num > max ) max = num;
if ( num < min ) min = num;
System.out.println("Highest: " + max);
System.out.println("Lowest: " + min);
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);
}
}
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);
}
}
i added code after reeading first line to set high and lowest, so if user will give you 10 numbers '9' it will output lowest number being '9' and not 1 as it would (similiar with high). 我在重新设置第一行以设置高和低之后添加了代码,因此,如果用户给您10个数字“ 9”,它将输出的最小数字为“ 9”,而不是1(与高类似)。
you are on the right track for capturing highest
. 您在把握
highest
的正确道路上。 you need to apply similar logic for lowest
. 您需要将类似的逻辑应用于
lowest
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.