Write the complete java program called Temperature that includes a for loop structure, prompting the user to enter 5 temperature values. The program should add up each temperature entered within the loop and this is stored in a variable called total. Using a system statement, output the total temperature value and the average temperature value. Use the sample output below as a guide:
The total temperature =
The average temperature =
My answer is the statement below but im still getting errors:-
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner temp = new Scanner (System.in);
double total = 0;
for(int=1;int<=5;int++);
{
System.out.println ("Enter temperature #" + temp +":");
double temperature = temp.nextDouble ();
total = temperature;
}
System.out.println("The total temperature =" +total);
System.out.println("The average temperature=" +(double)(total/5));
}
}
The OP does not state what errors you are getting exactly, but I can guess some of them are from:
for(int=1;int<=5;int++);
You cannot use int like that. It is a type and should be used like the following:
for(int itr = 1; itr <= 5; itr++) { ...
Also, the semi-colon on your for loop doesn't need to be there.
for(int i=1;i<=5;i++) {
System.out.println ("Enter temperature #" + temp +":");
double temperature = temp.nextDouble ();
total += temperature;
}
I am currently taking an intro to java class at my school due to my growing interest in programming.
I am to create a program that takes user input for a min and max integer. I am also to take user input for the size of the array as well as whether or not the user would like both the sorted and unsorted lists printed out.
After I collect this information, I need to generate random values within the given min/max range and sort those values(I had no problem completing these steps).
My code:
//Third Project by John Mitchell
package thirdProject;
//Imported library
import java.util.*;
//First class
public class thirdProject {
//Created scanner and random class as well as variables
public static Scanner scan = new Scanner(System.in);
public static Random rand = new Random();
public static int min, max, rand_num, sum, total, temp, i, j;
public static boolean sorted;
public static int[] values = new int[];
//Allowing for the average output to be of type double
public static double average;
//Main method
public static void main(String[] args) {
//Prompt user to enter minimum value to be sorted
System.out.println("Please enter a minimum value: ");
min = scan.nextInt();
//Prompt user to enter maximum value to be sorted
System.out.println("\nPlease enter a maximum value: ");
max = scan.nextInt();
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
//Prompt the user whether or not they would like both lists
System.out.println("\nWould you like to see both the sorted and unsorted lists? Please enter 'True' for yes or 'False' for no.");
sorted = scan.nextBoolean();
//Prints lists that were generated
if (sorted == true) {
gen_random_val();
System.out.println("\nThe unsorted list is: " + Arrays.toString(values) + ".");
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
} else {
gen_random_val();
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
}
}
//Second method
public static void gen_random_val() {
//For loop that generates values within the range of values given
for(int i = 0; i < values.length; i++) {
values[i] = rand_num = Math.abs(rand.nextInt(max) % (max - min + 1) + min);
sum = sum + values[i];
average = (sum*1.0) / values.length;
}
}
//Third method
public static void sort_values() {
//For loop that sorts values
for(i=0; i<(total-1); i++) {
for(j=0; j<(total-i-1); j++) {
if(values[j] > values[j+1]) {
temp = values[j];
values[j] = values[j+1];
values[j+1] = temp;
}
}
}
}
}
Currently, the hard codes length of 10 values in the array works fine as I have recycled part of my code from a previous project. I am looking for guidance on how to simply make the size determined by user input.
Thank you.
For example you can do this:
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
values = new int[total];
You don't have to give values to variables when you declare them.
I have a file named Numbers.txt with the following content:
8.5
83.45, 90.2
120.00, 11.05
190.00
I have written code that uses the contents of the file to compute the sum and average of the numbers in the file however when I run the code, for the average the result is "NaN"
CODE:
package lab13;
import java.util.Scanner;
import java.io.*;
public class problem1 {
public static void main(String[] args) throws IOException
{
double sum = 0;
int count = 0;
double num,total = 0;
double average = total/count;
File file = new File("Numbers.txt");
Scanner scan = new Scanner(file);
while (scan.hasNext())
{
double number = scan.nextDouble();
sum = sum + number;
}
while (scan.hasNextDouble())
{
num = scan.nextDouble();
System.out.println(num);
count++;
total += num;
}
scan.close();
System.out.println("The sum of the numbers in " +
"Numbers.txt is " + sum );
System.out.println("The average of the numbers in " +
"Numbers.txt is " + average );
}
}
Output:
The sum of the numbers in Numbers.txt is 503.2
The average of the numbers in Numbers.txt is NaN
You need to do
double average = total/count;
after you have the values for total and count
But also note that
when while (scan.hasNext()) stream is exhausted then while (scan.hasNextDouble()) will also be exhausted
This can be overcome but just looping once
Current i am scanning in 4 exam score grades, each to their own variable that has been declared and initialized. I was wondering if there was better way i should be doing this to make it less clutters. Please bear with me though as i am currently in my first java class at uni and dont have any prior experience so i dont want the solution to be super complex, not yet at least but something easily understandable. Not sure if it helps/matters but i am using BlueJ as my IDE.
import java.util.*;
public class GradeCalculatorDriver
{
public static void main(String [] args){
String s1 = "student";//Declare student string variable;
String s2;
double exam1 = 0;//Declare and initalize variables.
double exam2 = 0;//Declare and initalize variables.
double exam3 = 0;//Declare and initalize variables.
double exam4 = 0;//Declare and initalize variables.
do{
Scanner input = new Scanner(System.in);
System.out.println("This program will calculate the average of 4 exam scores, and return the lowest, highest, and letter grade associated with the average");
System.out.println("Please enter the name of the student");//Request student name and scans it into a string.
String student = input.next();
System.out.println("Please enter one exam score, then hit enter and repeat for following grades.");//Request exam scores and scan them into variables.
exam1 = input.nextDouble();
exam2 = input.nextDouble();
exam3 = input.nextDouble();
exam4 = input.nextDouble();
double highest = GradeCalculator.high(exam1, exam2, exam3, exam4);//Calls highest grade method.
double lowest = GradeCalculator.low(exam1, exam2, exam3, exam4);//Calls lowest grade method.
double average = GradeCalculator.avg(exam1, exam2, exam3, exam4);//Calls average grade method.
char letterGrade = GradeCalculator.letter(exam1, exam2, exam3, exam4);//Calls letter grade method.
System.out.printf("The highest exam score is : %.2f " + highest);//Displays highest grade.
System.out.printf("The lowest exam score is : %.2f " + lowest);//Displays lowest grade.
System.out.printf("The average exam score is : %.2f " + average);//Displays average grade.
System.out.print("The letter grade is " + letterGrade);//Displays letter grade associated with average.
System.out.println("Would you like to enter another students grades? (yes/no)");//asks the user if they would like to calculate another factorial.
s2 = input.next();
} while (s2.equalsIgnoreCase("YES"));//checks to see what the users response was.
System.out.print("Thank you for using my program!");//Ending statement.
}
}
public class GradeCalculator{
public static double high(double exam1, double exam2, double exam3, double exam4){//Calculates the highest exam score entered.
double highest;//Declare and initilize variable.
highest = Math.max(Math.max(Math.max(exam1, exam2), exam3), exam4);
return highest;//Returns highest exam score.
}
public static double low(double exam1, double exam2, double exam3, double exam4){//Calculates the lowest exam score entered.
double lowest = 0;//Declare and initilize variable.
lowest = Math.min(Math.min(Math.min(exam1, exam2), exam3), exam4);
return lowest;//Returns highest exam score.
}
public static double avg (double exam1, double exam2, double exam3, double exam4){//Calculates the average exam score.
double average;//Declare variable.
double count = 4;//Declare and initilize variable.
average = ((exam1 + exam2 + exam3 + exam4) / count);
return average;//Returns average grade.
}
public static char letter (double exam1, double exam2, double exam3, double exam4){//Calculates the letterGrade based on the average exam score.
char letterGrade;//Declare and initilize variable.
double count = 4;//Declare and initilize variable.
double average = ((exam1 + exam2 + exam3 + exam4) / count);//declare and calculate average score.
if (average >= 90)
letterGrade = 'A';
else if (average >= 80)
letterGrade = 'B';
else if (average >= 70)
letterGrade = 'C';
else if (average >= 60)
letterGrade = 'D';
else
letterGrade = 'E';
return letterGrade;//Returns letter grade.
}
}
You can use a List<Double> scores = new ArrayList<>() to hold the exam score values and reduce code clutter. Then as you added new exam scores from user input, you would call scores.add(input.nextDouble()) for each input value.
Well, in my opinion, if this is your first kick at the cat (so to speak) then you're well on your way to being a successful Java programmer. As for reducing clutter, I suppose it depends upon what you have already learned, like the Java methods and statements already covered and are now at your disposal to create an application to accomplish the task at hand. There is really no way to know the extent of your learning and therefore the suggestions provided below should only be defined as mere suggestions:
There is nothing wrong with your current model other than a few minor errors which will generate a MissingFormatArgumentException and that is within the code lines:
System.out.printf("The highest exam score is : %.2f " + highest);
System.out.printf("The lowest exam score is : %.2f " + lowest);
System.out.printf("The average exam score is : %.2f " + average);
Any errors within your code should be repaired first. Each of the code lines above contains a fault and it's simply because there is no argument supplied for the format specifier (%.2f). This is because you placed a plus (+) character in place of where a comma separator character is to go so as to indicate the argument for %.2f to represent. In this case the + will append the following string or variable content to the string before it. The code should be:
System.out.printf("The highest exam score is : %.2f ", highest);
System.out.printf("The lowest exam score is : %.2f ", lowest);
System.out.printf("The average exam score is : %.2f ", average);
Or just utilize the String.format() method:
System.out.println("The lowest exam score is: " + String.format("%.2f",lowest));
System.out.println("The highest exam score is: " + String.format("%.2f", highest));
System.out.println("The average exam score is: " + String.format("%.2f", average));
Declaring Scanner should not be done upon every iteration of your do/while loop. Place this declaration above the do/while code block so as not to open unnecessary instances of Scanner.
Explaining application functionality does not need to be done upon each iteration of the do/while loop. Move this message above the do/while code block.
When prompting for User input don't use the Scanner#next() method unless you are expecting to receive string tokens. Sometimes it's just plain easier to use the Scanner#nextLine() method. In my opinion I feel it can give more flexibility and allows you a better opportunity to prevent possible exceptions (don't rely on exceptions if you can prevent them).
Believe it or not...sometimes comments can be the biggest source of code clutter. There is absolutely no need to comment the obvious. Yes, I might have done so but it's only so as to explain the code. It is expected to be deleted.
You can get rid of the code line: String s1 = "student";//Declare student string variable;. You don't seem to use this variable anywhere.
As already suggested an array or collection mechanism can be used to hold student scores however in the sense of reducing clutter, it won't for a mere 4 scores but it will for many more scores and therefore is a good way to handle this portion of the code. It is still a good way to go in any case if your course has already covered the use of Arrays and or ArrayLists. Not sure if your requirements are to utilize only what you've already learned. In any case....
To utilize an array to store Student scores you would also need to modify all your methods within the GradeCalculator Class. This in itself will remove parameter clutter since all you would need is a single parameter instead of 4 for each method. The methods in that class might look something like this if you want to use Arrays:
public class GradeCalculator {
public static double high(double[] exams) {//Calculates the highest exam score entered.
double highest = 0.0d;//Declare and initilize variable to 0.0
for (int i = 0; i < exams.length; i++) {
if (exams[i] > highest) {
highest = exams[i];
}
}
return highest;//Returns highest exam score.
}
public static double low(double[] exams) {//Calculates the lowest exam score entered.
double lowest = exams[0];
for (int i = 0; i < exams.length; i++) {
if (exams[i] < lowest) {
lowest = exams[i];
}
}
return lowest;//Returns lowest exam score.
}
public static double avg(double[] exams) {//Calculates the average exam score.
double average = 0.0d; //Declare variable.
double sum = 0.0d;
for (int i = 0; i < exams.length; i++) {
sum+= exams[i];
}
average = sum / exams.length;
return average; //Returns average grade.
}
//Calculates the letter-Grade based on the average exam score.
public static char letter(double average) {
char letterGrade;//Declare and initilize variable.
if (average >= 90) {
letterGrade = 'A';
}
else if (average >= 80) {
letterGrade = 'B';
}
else if (average >= 70) {
letterGrade = 'C';
}
else if (average >= 60) {
letterGrade = 'D';
}
else {
letterGrade = 'E';
}
return letterGrade; //Returns letter grade.
}
}
The letter() method only ever needed one parameter instead of the 4 you had forced to provide and that is the value that is returned from the average() method. You see, you don't need to calculate the average again within the letter() method since you already have a method that does, and has done that. Just pass the already calculated average to the letter() method.
To fill an array with User input it's best to carry out the task using a loop of some sort but then again, it depends upon exactly how you want the User to provide that information (like Test Scores). Perhaps you would like the User to supply all the scores from a single input by separating each score with a white-space:
Please enter all student scores (separated with a space):
65 112 75 88
The code for this might look something like this:
String s2;
boolean invalidEntry;
String LS = System.lineSeparator();
double[] exams; // Declare Array
Scanner input = new Scanner(System.in);
System.out.println("This program will calculate the average of any number of "
+ LS + "desired exam scores and return the lowest, highest, and "
+ LS + "letter grade associated with that determined average." + LS);
do {
s2 = "";
invalidEntry = false;
// Request Student Name
System.out.println("Please enter the name of the student (nothing to exit):");
String student = input.nextLine();
if (student.equals("")) { break; }
// Request exam scores
System.out.println("Please enter all student scores (each separated with a space): ");
String scores = input.nextLine();
// If nothing was supplied break out of loop
if (scores.equals("")) {
invalidEntry = true;
break;
}
String[] scoresArray = scores.split("\\s+"); // Split the input into single scores (regex "\\s+" is used to split on one or more whitespaces).
exams = new double[scoresArray.length]; // Initalize Array.
// Convert scores to double data type...
for (int i = 0; i < scoresArray.length; i++) {
/* Is the string value actually a numerical signed
or unsigned integer or double type value. Save
this Regular Expression. It's handy to have. */
if (scoresArray[i].matches("-?\\d+(\\.\\d+)?")) {
exams[i] = Double.parseDouble(scoresArray[i]);
}
else {
System.out.println("One or more of the Scores supplied are invalid! "
+ "Enter Student Scores again!" + LS);
invalidEntry = true;
break;
}
}
if (invalidEntry) { continue; } // Redo loop on Invalid Entry
double highest = high(exams);
double lowest = low(exams);
double average = avg(exams);
char letterGrade = letter(average);
System.out.println(LS + "Results For Student: " + student);
System.out.println("From " + String.format("%02d" , exams.length) +
" exam scores: " +
Arrays.toString(exams).replaceAll("[\\[\\]]", ""));
System.out.println("The lowest exam score is: " + String.format("%.2f",lowest));
System.out.println("The highest exam score is: " + String.format("%.2f", highest));
System.out.println("The average exam score is: " + String.format("%.2f", average));
System.out.println("The letter grade is: " + letterGrade + LS);
while (s2.equals("")) {
System.out.println("Would you like to enter another Students Scores? (yes/no)");
s2 = input.nextLine();
if (!s2.equalsIgnoreCase("yes") && !s2.equalsIgnoreCase("no")) {
System.out.println("Invalid Response! 'Yes' or 'No' only!");
s2 = "";
}
}
} while (s2.equalsIgnoreCase("yes") || invalidEntry);
System.out.println("Thank you for using my program!");
Sometimes it is just easier for the User to enter all the scores on one line as demonstrated within the above code however, you set the rules towards how your application is to function. If you want each score to be entered individually then so be it. The code might then look something like this:
String s2;
int indexCounter; // Declare an index counter for array.
boolean invalidEntry;
String LS = System.lineSeparator();
double[] exams; //Declare Array.
Scanner input = new Scanner(System.in);
System.out.println("This program will calculate the average of any number of "
+ LS + "desired exam scores and return the lowest, highest, and "
+ LS + "letter grade associated with that determined average." + LS);
do {
s2 = "";
indexCounter = 0; // Set index counter to 0
invalidEntry = false;
// Request Student Name
System.out.println("Please enter the name of the Student (nothing to exit):");
String student = input.nextLine();
if (student.equals("")) { break; }
// Get number of Scores to enter from User
int numberOfScores = 0;
while (numberOfScores == 0) {
System.out.println("Please enter the number of scores you wish to enter:");
String numScores = input.nextLine();
// Is the value supplied a String Integer value
if (!numScores.matches("\\d+")) {
System.out.println("Invalid number of scores provided! Try Again..." + LS);
continue;
}
numberOfScores = Integer.parseInt(numScores);
}
exams = new double[numberOfScores]; // Initialize Array
// Request exam scores
while (indexCounter < numberOfScores) {
System.out.println("Please enter exam score #" + (indexCounter + 1) +
" then hit enter: ");
exams[indexCounter] = input.nextDouble();
input.nextLine(); // Clear the scanner buffer
indexCounter++;
}
double highest = high(exams);
double lowest = low(exams);
double average = avg(exams);
char letterGrade = letter(average);
System.out.println(LS + "Results For Student: " + student);
System.out.println("From " + String.format("%02d" , exams.length) +
" exam scores: " +
Arrays.toString(exams).replaceAll("[\\[\\]]", ""));
System.out.println("The lowest exam score is: " + String.format("%.2f",lowest));
System.out.println("The highest exam score is: " + String.format("%.2f", highest));
System.out.println("The average exam score is: " + String.format("%.2f", average));
System.out.println("The letter grade is: " + letterGrade + LS);
while (s2.equals("")) {
System.out.println("Would you like to enter another Student's Scores? (yes/no)");
s2 = input.nextLine();
if (!s2.equalsIgnoreCase("YES") && !s2.equalsIgnoreCase("NO")) {
System.out.println("Invalid Response! 'Yes' or 'No' only!");
s2 = "";
}
}
} while (s2.equalsIgnoreCase("YES") || invalidEntry);
System.out.println("Thank you for using my program!");
You will have noticed that some of the code above takes advantage of Regular Expressions such as "\\s+", "\\d+", "[\\[\\]]", or even "-?\\d+(\\.\\d+)?". It's never to late to learn how to utilize Java's java.util.regex package for pattern matching. It can quickly become a close friend for you and once learned, you will find yourself using it all the time. To test Regular Expressions and to get explanations of what a particular expression does you can use the website RegEx101.com for example: this regex.
I'm writing a program where at the end I have to display the numbers I entered and the maximum and minimum of those entered numbers. However I'm running into a little problem, here is my code,
import java.util.*;
public class question3controlstructures {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
int numberEntered;
int numbersinput = 0;
String answer ="";
double sum = 0;
do {
System.out.println("Enter a number");
numberEntered = in.nextInt();
numbersinput ++;
System.out.println("do you want to enter another number?");
answer = in.next();
sum = sum + numberEntered;
} while (answer.equals("yes"));
System.out.println("The sum is: " + sum);
System.out.println("The average is: " + sum/numbersinput);
System.out.println(numberEntered);
}
}
The above comment are absolutely useful. However, here is little code
package com.mars;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Question3controlstructures {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (scan.hasNextInt()) {
list.add(scan.nextInt());
}
Integer[] nums = list.toArray(new Integer[0]);
int sum = 0;
int i = 0;
for ( ; i < nums.length; i++) {
sum = sum + nums[i];
}
System.out.println("sum..." + sum);
System.out.println("The average is: " + sum / i);
System.out.println(i);
System.out.println("max.. "+Collections.max(list));
System.out.println("min.. "+Collections.min(list));
scan.close();
}
}
As suggent in comments , you need a list to store the multiple numbered entered.
just compare the min and max every time you enter a number
int min = Integer.MAX_VALUE
int max = Integer.MIN_VALUE
int numberEntered;
int numbersinput = 0;
String answer ="";
double sum = 0;
do {
System.out.println("Enter a number");
numberEntered = in.nextInt();
System.out.println("YOU HAVE ENTERED: " + numbersEntered);
if (min > numberEntered) min = numberEntered;
if (max < numberEntered) max = numberEntered;
numbersinput ++;
sum = sum + numberEntered;
System.out.println("do you want to enter another number?");
answer = in.next();
} while (answer.equals("yes"));
System.out.println("The sum is: " + sum);
System.out.println("The average is: " + sum/numbersinput);
System.out.println(numberEntered);
//you can print your min max here.
The IntSummaryStatistics class together with Java 8's Stream API may be less verbose than dealing with min, max, sum and avg calculation manually.
public static void main(String[] args) {
// Get user input.
List<Integer> numbers = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
// No user friendly way to gather user input, improve!
numbers.add(scanner.nextInt());
}
// Transform input to statistics.
IntSummaryStatistics stats = numbers.stream()
.collect(Collectors.summarizingInt(Integer.intValue()));
// Print statistics.
String jointNumbers = numbers.stream()
.collect(Collectors.joining(", "));
System.out.printf("You entered %d numbers: %s\n, stats.getCount(), jointNumbers);
System.out.println("Min: " + stats.getMin());
System.out.println("Max: " + stats.getMax());
System.out.println("Sum: " + stats.getMax());
System.out.println("Avg: " + stats.getAverage());
}