简体   繁体   中英

Comparing multiple integers in IF statement, Java

I am brand new to coding. I'm currently using "Java:How to program" by Deitel, and one of the early exercises has me stumped.

It is asking me to use simple, chapter 1 if statements to compare 5 integers (input by the user) and display both the largest and the smallest. I am limited to the language used in the first chapter, so I made the assumption that I could list int values in the parenthetical after the if statement. Something like:

int firstInt;
int secondInt;
int thirdInt;
int fourthInt;
int fifthInt;

if (first Int> secondIt, thirdInt, fourthInt, fifthInt)

etc. but this is a syntax error. Does anyone know how to compare multiple values simultaneously? A google search proves to be no help since all the answers have some convoluted solution that I don't understand.

If I try something like this:

     if (one > two)
     System.out.println("%d is the largest number!", one);

     if (one > three)

etc. for all 1 - 5, The issue I run into is when I continue with if statements 1>2,3,4,5 2>1,3,4,5 etc. then there will be 1 true for each integer regardless except for the smallest number, and it will display 4 outputs, when all I'm after is the larges and the smallest.

I'm stumped.

The expression:

firstInt > secondInt, thirdInt, fourthInt, fifthInt

is not valid because Java is a computer language rather than a natural language (like English).

If you want to do it that way, what you need is the and conjunction, with multiple complete conditions (using a,b,c,d,e to minimise the code):

if ((a >= b) && (a >= c) && (a >= d) && (a >= e)) { // a >= b,c,d,e
    System.out.println ("Largest is: " + a);
} else if ((b >= c) && (b >= d) && (b >= e)) {      // b >= c,d,e
    System.out.println ("Largest is: " + b);
} else if ((c >= d) && (c >= e)) {                  // c >= d,e
    System.out.println ("Largest is: " + c);
} else if (d >= e) {                                // d >= e
    System.out.println ("Largest is: " + d);
} else {                                            // e > d
    System.out.println ("Largest is: " + e);
}

keeping in mind that, once you decide a (or any of the others in later steps) isn't the largest, you never need to check it again, as one of the others will be larger than it.


Or you can use the facilities of the Java standard Math package, where Math.max(a,b) will give you the largest of the values from a and b :

int largest = Math.max(a,Math.max(b,Math.max(c,Math.max(d,e))));

Here, you define the largest of all five numbers as the maximum of the pair {a, maximum-of-bcde} then use a similar method to work out maximum-of-bcde as the maximum of the set {b, maximum-of-cde} and so on.

Or, in other words, choose the largest from {d,e} and call it x . Then choose the largest from {c,x} and call it y . Then the largest from {b,y} and call it z . Finally the largest from {a,z} and that's your largest value of the five.

Though, to be honest, if you're on chapter one of an introductory text, it probably hasn't covered much in the Java standard libraries yet.


But, if you're after a method where it's perhaps easier for a beginner to understand the flow, I don't think you can go past this one:

int maxOfFive (int a, int b, int c, int d, int e) {
    int largest = a;
    if (b > largest) largest = b;
    if (c > largest) largest = c;
    if (d > largest) largest = d;
    if (e > largest) largest = e;
    return largest;
}

This is basic selection of the largest value as a person would do it, scanning the list one by one and just remembering which value was the highest, then returning that.

Or, if you haven't learned about functions yet (and reverting to your original variables), just implement the same code without a function call:

int largest = firstInt;
if (secondInt > largest) largest = secondInt;
if (thirdInt  > largest) largest = thirdInt;
if (fourthInt > largest) largest = fourthInt;
if (fifthInt  > largest) largest = fifthInt;
System.out.println ("Largest is: " + largest);

I believe that's probably only using stuff you've already indicated that you know about (variables, single-condition if statement, and output).

Using multiple integers to store number does work BUT it is not the way to code. You should at least use an array.

Array crash course:

Array is a group of variables with similar datatype.

To create an array:

<datatype>[] arrayName = new <datatype>[size];

//Example
int[] myValues = new int[5];   //create 5 int variables.

myValues[0];    //is similar to your firstInt
myValues[1];    //is similar to your secondInt
myValues[2];    //is similar to your thirdInt
myValues[3];    //is similar to your forthInt
myValues[4];    //is similar to your fifthInt

Using an array, you can just use a for loop to iterate through the variables. Doing it simultaneously (I guess you mean iteratively), you need arrays .

Solution 1:

//To find the largest
int largest = array[0];
for(int x=0; x<5; x++)
    if (array[x] > largest)
        largest = array[x];

//To find the smallest
int smallest= array[0];
for(int x=0; x<5; x++)
    if (array[x] < smallest)
        smallest= array[x];

Alternatively, without using loop and array (Not so elegant but might be what you want): Use Math.max() or Math.min() .

Solution 2:

int largest = Math.max(var1, var2);
largest = Math.max(largest, var3);
largest = Math.max(largest, var4);
largest = Math.max(largest, var5);

Solution 3:

Lastly, without using loops and arrays .

int largest = 0;
if(firstInt > secondInt)
    largest = firstInt
else
    largest = secondInt;

if(thirdInt > largest)
    largest = thirdInt;
if(forthInt > largest)
    largest = forthInt;
if(fifthInt > largest)
    largest = fifthInt;

To find smallest, just change the operator from > to < .

I would suggest if you know the number of integers to compare use array instead. Below is a sample code -

This is not actual answer as I am not using if statement. Though this is one way to get what you want. As you are new in java, wanted to share my approach.

import java.util.Arrays;

public class JavaTest {
    public static void main(String[] args) {
        int values[] = {2,6,10,4,8};
        Arrays.sort(values);
        System.out.println("Min value : "+values[0]);
        System.out.println("Max value : "+values[values.length-1]);
    }
}

Have a great time with java.

The only way to compare multiple if statements is to use:

if(integer > 1 && integer > 2 && integer > 3) //etc

Otherwise you can have:

if(integer>1)
    if(integer>2) //etc

You cannot list multiple integers in an if statement using commas

You can use the following approach:

if (one > two && one > three)
 System.out.println("%d is the largest number!", one);

Or the best solution, fill your values in array, then iterate over them like:

for(int i=1; i<list.length; i++) { //suppose the first element is one
   if(one <= list[i]) {
       break;
   }
   System.out.println("%d is the largest number!", one);
}

I believe what you are trying to do is

if (i1 > i2 
    && i1 > i3 
    && i1 > i4 
    && i1 > i5) {
    // i1 is the largest
}

It does not look very elegant though. Normally we would want to store multiple integer in a List or an array, and find the biggest value by sorting it or iterate through the list.

Create an array of given 5 numbers, and try this:

int numbers[] = new int[]{1,2,3,4,5};

 //assign first element of an array to largest and smallest
 int smallest = numbers[0];
 int largetst = numbers[0];

 for(int i=1; i< numbers.length; i++)
    {
      if(numbers[i] > largetst)
           largetst = numbers[i];
      else if (numbers[i] < smallest)
           smallest = numbers[i];
     }

System.out.println("Largest Number is : " + largetst);
System.out.println("Smallest Number is : " + smallest);

Depending on how you want to use your variable after the assignment you also might create an array and sort it

int firstInt = 4;
int secondInt = 2;
int thirdInt = 3;
int fourthInt = 1;
int fifthInt = 5;

int[] arr = new int[5];
arr[0] = firstInt;
arr[1] = secondInt;
arr[2] = thirdInt;
arr[3] = fourthInt;
arr[4] = fifthInt;

Arrays.sort(arr);
System.out.println("smallest = " + arr[0]);
System.out.println("largest = " + arr[arr.length - 1]);

I don't know how simple chapter1 is and what is the functionalists that you didn't study yest, but simple define two variables and give them min and max value:

int smallest = firstInt;
int largest = secondInt;

if(firstInt > secondInt ){
   largest = firstInt;
   if(thirdInt > firstInt ){
     largest = thirdInt;
      if(fourthInt > thirdInt ){
        largest = fourthInt;
         if(fifthInt > fourthInt){
            largest = fifthInt;
          }
       }
     }
 }

if(secondInt < firstInt){
   smallest= secondInt;
   if(thirdInt < secondInt){
     smallest = thirdInt;
      if(fourthInt < thirdInt ){
        smallest = fourthInt;
         if(fifthInt < fourthInt){
            smallest = fifthInt;
          }
       }
     }
}

System.out.println(smallest);
System.out.println(largest);

SO I also kind of had the same problem but I was able to solve it with this rather long algorithm. I don't think that it has anything to do with Java but I would like to hear what you think about it. Btw this is an algorithm to find the biggest and smallest value from five given values by the user.

int [] vector = new int [5];
   for (int i=0; i<=4;i++)
   {
       System.out.print ("enter a number for vector [ "+i+"] :");
               vector [i]=input.nextInt();
   }
   for (int i =0; i<=4;i++)
   {
       System.out.print ("vector ["+i+"] is : "+vector [i]+"\n");
   }
  if (vector[0]>vector[1])
  {
      if (vector[0]>vector[2])
      {
          if (vector [0]>vector[3])
          {
              if(vector[0]>vector[4])
              {
                  System.out.print ("the biggest number is : "+vector[0]+"\n");
              }
          }
      }
  }
  if (vector[1]>vector[0])
  {
      if (vector[1]>vector[2])
      {
          if (vector [1]>vector[3])
          {
              if(vector[1]>vector[4])
              {
                  System.out.print ("the biggest number is : "+vector[1]+"\n");
              }
          }
      }
  }
  if (vector[2]>vector[0])
  {
      if (vector[2]>vector[1])
      {
          if (vector [2]>vector[3])
          {
              if(vector[2]>vector[4])
              {
                  System.out.print ("the biggest number is : "+vector[2]+"\n");
              }
          }
      }
  }
  if (vector[3]>vector[0])
  {
      if (vector[3]>vector[1])
      {
          if (vector [3]>vector[2])
          {
              if(vector[3]>vector[4])
              {
                  System.out.print ("the biggest number is : "+vector[3]+"\n");
              }
          }
      }
  }
  if (vector[4]>vector[0])
  {
      if (vector[4]>vector[1])
      {
          if (vector [4]>vector[2])
          {
              if(vector[4]>vector[3])
              {
                  System.out.print ("the biggest number is : "+vector[4]+"\n");
              }
          }
      }
  }
  if (vector[0]<vector[1])
  {
      if (vector[0]<vector[2])
      {
          if (vector[0]<vector [3])
          {
              if (vector[0]<vector[4])
              {
                  System.out.print ("the smallest number is : "+vector [0]+"\n");
              }
          }
      }
  }
  if (vector[1]<vector[0])
  {
      if (vector[1]<vector[2])
      {
          if (vector[1]<vector [3])
          {
              if (vector[1]<vector[4])
              {
                  System.out.print ("the smallest number is : "+vector [1]+"\n");
              }
          }
      }
  }
  if (vector[2]<vector[0])
  {
      if (vector[2]<vector[1])
      {
          if (vector[2]<vector [3])
          {
              if (vector[2]<vector[4])
              {
                  System.out.print ("the smallest number is : "+vector [2]+"\n");
              }
          }
      }
  }
  if (vector[3]<vector[0])
  {
      if (vector[3]<vector[1])
      {
          if (vector[3]<vector [2])
          {
              if (vector[3]<vector[4])
              {
                  System.out.print ("the smallest number is : "+vector [3]+"\n");
              }
          }
      }
  }
  if (vector[4]<vector[0])
  {
      if (vector[4]<vector[1])
      {
          if (vector[4]<vector [2])
          {
              if (vector[4]<vector[3])
              {
                  System.out.print ("the smallest number is : "+vector [4]+"\n");
              }
          }
      }
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM