JAVA - 最高和最低的数字 [英] JAVA - Highest and Lowest numbers

查看:114
本文介绍了JAVA - 最高和最低的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我找到最高和最低的数字。

Please help me in finding the Highest and Lowest number.

我发誓,在我决定发布代码之前,我确实在网站上阅读了关于这个问题的无数帖子在这里,因为他们都有已知的输入数量。

I swear, I did read countless posts on the site about this problem before I decided to post the code here, because all of them had known numbers of input.

我有来自用户的未知输入。它可以是任何给定的正数或负数。在尝试了将近一天后,我现在完全空白了。任何帮助都会得到极大的赞赏。

I have "unknown" input from the user. It could be any given positive or negative numbers. I am totally blank now after trying it for almost a day. Any helps is Greatly Appreciated.

    package test;

import java.util.Scanner;
import java.lang.*;
import java.io.*;

public class Test {

    public static void main(String[] args){

int highest=Integer.MIN_VALUE;
int lowest=Integer.MAX_VALUE;

Scanner in = new Scanner(System.in);

System.out.println("Enter any positive or negative number");
int n = in.nextInt();

if(n > highest){
    lowest = highest;
    highest = n;
}

if (n < lowest){
    highest=lowest;
    lowest=n;
}

System.out.println(highest);
System.out.println(lowest);


    }
}


推荐答案

这是您的代码破解的地方。

This is where your code is breaking.

highest=lowest;
lowest=n;

现在关于初始化这些变量。

Now about initializing these variables.

我个人如何开始这个程序将初始化最低和最高的 n。所以你不要不必担心任何限制。

How I, personally would start this program would be initializing both the lowest and highest with n. So you don't have to worry any bounds.

System.out.println("Enter any positive or negative number");
int n = in.nextInt();
int highest = n;
int lowest = n;

for(int i = 0; i < 9; i++){
    System.out.println("Enter any positive or negative number");
    n = in.nextInt();
    if(n > highest){
        highest = n;
    }else if (n < lowest){
        lowest=n;
    }
}

System.out.println(highest);
System.out.println(lowest);

这要求用户输入10个不同的数字。然后打印出最高和最低值。

This asks the user to input 10 different digits. then prints out the highest and lowest values.

否则如果(n <最低)这也可能是否则如果因为如果 n 是最高值,它也不能是最低值,因为我在开始时初始化。

else if (n < lowest) this could also be a else if because if n is the highest value it cant be also the lowest value because of my initialization at the start.

这篇关于JAVA - 最高和最低的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆