Robert Tossly Robert Tossly - 18 days ago 6
Java Question

Using variables inside loops and if-statements in Java

I have to complete a question.

The question is: Write a program that takes the daily amount of sunlight hours(input of sunlight for each day) for the given amount(input of days) of days. Output the day with the highest amount of sunlight hours and the day with the lowest amount of sunlight hours.

I have completed this question using a list, but my teacher said that she wants me to use a

nested loop
or a
loop
and
if
statement.

So far, I take the input of days and run a
while loop
to ask the user the amount of sunlight hours for each day. The problem is comparing inputs of each loop iteration (to find the highest and lowest total amount of sunlight of a day).

CODE:

import java.util.Scanner;
public class temp {

public static void main(String[] args) {

Scanner new_scan = new Scanner(System.in);
System.out.println("Enter the amount of days you wish to enter the daylight hours for: ");
int loop_num = new_scan.nextInt();

for(int x=0; x<=loop_num;x++){

//Here I ask the user to input the number of sunlight hours for each day, I don't know how to compare separate input iterations (to find the highest and lowest days of sunlight).

System.out.println("Enter the number of daylight hrs for day "+ x);
int next_num = new_scan.nextInt();
int c = 0;
int old_num = c + next_num;

if(next_num>old_num){
int highest_num = next_num;
} else{ int highest_num = old_num; }


if(next_num<old_num){
int lowest_num = next_num;
} else{ int lowest_num = old_num; }

}
System.out.println("The lowest amount of sunlight of the days given was: "+ lowest_num);
System.out.println("The highest amount of sunlight of the days given was: "+ highest_num);
}
}


My question is: How can I compare iterations to find the amount of sunlight on the days with the highest and lowest amount of sunlight?
In other words, how can I compare the input data of different iterations in a loop?

Answer

The variable should be defined out of the loop to be persistent, otherwise it is recreated on each iteration. You need something like that:

int min = Integer.MAX_VALUE;
int max = -1;
for(int x=0; x<=loop_num;x++){ 

    System.out.println("Enter the number of daylight hrs for day "+ x);
    int next_num = new_scan.nextInt();

    if(next_num>max){
        max = next_num;
    } 
    if (nex_num <min) {
        min = nex_num;
    }

}
System.out.println("The lowest amount of sunlight of the days given was: "+ min);
System.out.println("The highest amount of sunlight of the days given was: "+ max);

I suggest to add the input sanity check here since the number should be within 0 - 24 hours range.