I am really struggling to understand how to write this while loop based on the instructions. Can someone please show me what to do? I already tried to write my own code below and it's bad.
Here are the instructions:
Write a sentinel controlled while loop that will allow you to calculate the average low temperature for any month. The average temperature should be displayed as a properly calculated double value. Explain why you chose the sentinel value. The code for the input of the initial temperature value is provided.
Here is my code:
Scanner scan = new Scanner(System.in);
int temp = scan.nextInt();
while ()
{
temp = 5.0/9.0 * (temp - 32.0);
System.out.println()
}
The sentinel is any non-numeric string:
public class Sentinel {
public static void main(String args []) {
Scanner scan = new Scanner(System.in);
String temp = scan.next();
int count = 0;
double total = 0;
while (isNumeric(temp))
{
total += Double.parseDouble(temp);
count++;
temp = scan.next();
}
System.out.println(BigDecimal.valueOf(total/count).setScale(3, RoundingMode.HALF_UP).doubleValue());
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
}
Your original code is also trying to convert from fahrenheit to celsius even though the problem statement doesn't say anything about the scale.
int n = scan.nextInt(); //to input number of days in a given month
int[] temp = new int[n]; //an array to store the low temps of all days
int i=0, total=0;
double avg=0.0;
while (i<n)
{
temp[i] = scan.nextInt(); //input temperature per day one at a time
total=total+temp[i]; //to get the sum total of all days of the month
i++ //increment the counter i
}
avg=total/n;
System.out.println("the average low temperature is :"+avg);```
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.