Creating a Temperature Application in Dr. Java - java

Create a Temperature application that prompts the user for the temperature each day for the
past 5 days and then displays the lowest temperature of the five days, the highest temperature
of the five days and the average temperature. The application output should look similar to the
followings :
Enter the high temperature on day 1: 89
Enter the high temperature on day 2: 65
Enter the high temperature on day 3: 22
Enter the high temperature on day 4: 78
Enter the high temperature on day 5: 63
The average high temperature is 63.4
The lowest temperature is 22.0
The highest temperature is 89.0
This is basically what I have:
System.out.print ("Enter the temperature on day 1: ");
double day1 = kbReader.nextDouble();
System.out.print ("Enter the temperatre on day 2: ");
double day2 = kbReader.nextDouble();
System.out.print ("Enter the temperature on day 3: ");
double day3 = kbReader.nextDouble();
System.out.print ("Enter the temperature on day 4: ");
double day4 = kbReader.nextDouble();
System.out.print ("Enter the temperature on day 5: ");
double day5 = kbReader.nextDouble();
double average = day1 + day2 + day3 + day4 + day5;
double finalaverage = average/5;
System.out.println ("The average high temperature is " + finalaverage);
I want to know how to find the highest and lowest temperture using a loop

Please refer to this code Works fine in java
double temp[]=new double[5];
double avgTemp=0;
double highTemp=0;
double lowTemp=0;
Scanner sc=new Scanner(System.in);
for(int i=0;i<5;i++){
System.out.print ("Enter the temperature on day "+(i+1)+" :");
temp[i]=sc.nextDouble();
}
//for calculation average temp
double sum=0;
for(int i=0;i<5;i++){
sum+=temp[i];
}
System.out.println("Average temp is "+(sum/5));
//for calculation high temp
for(int i=0;i<5;i++){
if(temp[i]>highTemp){
highTemp=temp[i];
}
}
System.out.println("hightemp is "+highTemp);
lowTemp=temp[0];
for(int i=1;i<5;i++){
if(temp[i]<lowTemp){
lowTemp=temp[i];
}
}
System.out.println("hightemp is "+lowTemp);

Related

Simple Retirement Fund Using Loops

I'm trying to make a program that calculates the amount of money someone would have after retiring at 67 and started saving at the age the entered.
The program should show how much the save each year at a rate of 2.5% and then the total after the entered amount of years.
So far I got the income to display for each year but the total seems to be 2.5% more than what it needs to be.
int age = 0;
double income;
double total = 0;
Scanner keyboard = new Scanner(System.in);
System.out.print("How old are you? ");
age = keyboard.nextInt();
System.out.print("What is your annual income? ");
income = keyboard.nextDouble();
System.out.print("Age(years) Income($)");
while(age < 68) {
System.out.print(age + " " + income);
income += (income * .025);
total += income;
age ++;
}
System.out.print("total($) " + total);
keyboard.close();
I've been using 62 as my age and 60000 as the amount per year. But when I print the total instead of getting ~383000 I'm getting ~392000.
you are not counting the last iteration 67-68 when you have <68 in the while loop
meaning when the age is 67 the loop doesn't run and therefore the last year's income is not calculated
should be while(age<=68)

Using an Array's Element to Populate Another Array - Java

I am learning Java on my own and have just finished learning the basics of arrays, or so I think. I want to create a class grade sheet that keeps each student's grades and average. I have a for loop that asks each of the 10 students to enter their 4 test grades. Once I get those 4 grades, I take the average. I then store the student's grades and average into an array, one array per student. I essentially create 10 arrays with these 5 elements, for each student using the for loop. I now want to take the 5th element, the average of the 4 grades, from each student's array and populate another array called averages so I can perform other calculations. Is this possible with my logic? I think I could hard code 10 arrays, 1 for each student like so:
double averages[] = {student1[4], student2[4], ..., student10[4]};
Isn't this a bad way to go about this though? Any constructive help or guidance would be appreciated. Please do not post code that gives away the answer, as I won't learn from that. I just want a hint in the right direction. :)
Here's my code up until the point of confusion:
import java.util.Scanner;
public class ClassAverages {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double grade1 = 0.0, grade2 = 0.0, grade3 = 0.0, grade4 = 0.0, average = 0.0;
// get grades from each of the 10 students
for (int student = 1; student <= 3; student++) {
System.out.println("Student " + student);
System.out.println("---------\n");
System.out.print("Enter the first grade: ");
grade1 = keyboard.nextDouble();
while (grade1 < 0) { // input validation for grade 1
System.out.print("You entered a negative value for grade. Please re-enter a positive grade: ");
grade1 = keyboard.nextDouble();
}
System.out.print("Enter the second grade: ");
grade2 = keyboard.nextDouble();
while (grade2 < 0) { // input validation for grade 2
System.out.print("You entered a negative value for grade. Please re-enter a positive grade: ");
grade2 = keyboard.nextDouble();
}
System.out.print("Enter the third grade: ");
grade3 = keyboard.nextDouble();
while (grade3 < 0) { // input validation for grade 3
System.out.print("You entered a negative value for grade. Please re-enter a positive grade: ");
grade3 = keyboard.nextDouble();
}
System.out.print("Enter the fourth grade: ");
grade4 = keyboard.nextDouble();
System.out.println();
while (grade4 < 0) { // input validation for grade 4
System.out.print("You entered a negative value for grade. Please re-enter a positive grade: ");
grade4 = keyboard.nextDouble();
System.out.println();
}
// calculate the current student's average
average = (grade1 + grade2 + grade3 + grade4) / 4;
// for each student, 1 to 10, create an array with their 4 grades and average
double studentX[] = { grade1, grade2, grade3, grade4, average };
System.out.println("SCORE 1\t\tSCORE 2\t\tSCORE 3\t\tSCORE 4\t\tAVERAGE");
System.out.print(studentX[0] + "\t\t");
System.out.print(studentX[1] + "\t\t");
System.out.print(studentX[2] + "\t\t");
System.out.print(studentX[3] + "\t\t");
System.out.print(studentX[4] + "\n");
System.out.println();
// I want to use each student's average for each corresponding element in the averages array
// create an array of all student's averages
// double averages[] = {student1average, student2average,...student10average} ???
}
}
}
OUTPUT AS OF NOW:
Student 1
---------
Enter the first grade: 100
Enter the second grade: 100
Enter the third grade: 100
Enter the fourth grade: 100
SCORE 1 SCORE 2 SCORE 3 SCORE 4 AVERAGE
100.0 100.0 100.0 100.0 100.0
Student 2
---------
Enter the first grade: 90
Enter the second grade: 90
Enter the third grade: 90
Enter the fourth grade: 80
SCORE 1 SCORE 2 SCORE 3 SCORE 4 AVERAGE
90.0 90.0 90.0 80.0 87.5
Student 3
---------
Enter the first grade: 100
Enter the second grade: 100
Enter the third grade: 90
Enter the fourth grade: 80
SCORE 1 SCORE 2 SCORE 3 SCORE 4 AVERAGE
100.0 100.0 90.0 80.0 92.5
You could use a for loop. However this will require you to have a collection of items to iterate through. I think the best way for you to do this is to organize your students into their own separate class (give that class all the grades as parameters in its constructor and have it do the calculations for average within that class).
So if you call your class student then your constructor could look like thisstudent(int grade1, int grade2, int grade3, int grade4). Use these parameters to calculate the average for each student object.
Then in your ClassAverage class just instantiate new student objects as you want and add them to an array of student objects and then its as simple as iterating through the array of student, extracting the average field that you created for each student object (extract this simply by stating studentName.average, assuming you named your average field average in the student class).
So by the end you should have something that looks like this. Let's assume that the array of student objects is called studentArray
int[] averageArray = new int[studentArray.length];
for (int i = 0; i < studentArray.length; i++){
averageArray[i] = studentArray[i].average;
}
Good luck!
Arrays are very bad form of storing information. Mostly because they don't contain logic that uses data inside this arrays and any other code can make that data invalid because array doesn't check what values you give it. This is what classes are for: to have data and code that works with it in one place, and to protect data from changes from other places in code.
So for your case arrays are OK for fields of the same type(for example, array of students is OK), but not for values of that types(array of arrays of students grades is NOT OK). So what you should do here is to use a class:
class Student
{
int grades[] = new int[4];
public Student(int grade1, grade2, int grade3, int grade4)
{
grades[0] = grade1;
grades[1]=grade2;
grades[2]=grade3;
grades[3]=grade4;
}
public double average()
{
double result = 0;
for(int i =0; i<grades.count; i++)
result += grades;
return result / grades / count;
}
// and so on
}
They allow you to take logic inside object, sou you can use it like this:
Student albert = new Student(5, 4, 2, 1);
System.out.println(albert.avarage()); // prints 3

Electricity/Energy Bill Calculator: Java

I am having issues figuring out exactly what is wrong with this little Electricity/Energy calculator used to calculate computer energy costs.
I'd appreciate any help.
Program:
import java.util.Scanner;
public class ElectricityCalculations {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
double usageHoursPerDay = 0; // Hours computer is on per day
double usageDaysPerWeek = 0; // Days computer is used per week
double usageWeeksPerYear = 0; // Weeks computer is used per year
double wattsPerHour = 0; // Watts used by computer per hour
final double COST_PER_KWH = 0.145; // Prices of power per kilowatt hour
final double LBS_CO2_PER_KWH = 0.58815; // Pounds of CO2 generated per KWH
double usageHoursPerYear = 0; // Amount of hours on per year
double usageWattHoursPerYear = 0; // Amount of watt hours consumed per year
double usageKWHPerYear = 0; // Amount of KWH used in a year
double costPerYear = 0; // Total cost per year
double lbsCO2PerYear = 0; // Total amount of CO2 in pounds released per year
// Input Values
System.out.println("How many hours is your computer on per day?");
usageHoursPerDay = scnr.nextDouble();
System.out.println("How many days per week is your computer used?");
usageDaysPerWeek = scnr.nextDouble();
System.out.println("How many weeks per year is your computer used?");
usageWeeksPerYear = scnr.nextDouble();
System.out.println("How many watts per hour does your computer use? (Suggestive value for desktop: 100, laptop: 30).");
wattsPerHour = scnr.nextDouble();
// Calculations
usageHoursPerYear = usageHoursPerDay * 365;
usageWattHoursPerYear = wattsPerHour * 8760; // 8760 is the number of hours in a year
usageKWHPerYear = usageWattHoursPerYear / 1000;
costPerYear = usageKWHPerYear * COST_PER_KWH;
lbsCO2PerYear = LBS_CO2_PER_KWH * usageKWHPerYear;
// Printing Energy Audits
System.out.println("Computer Energy Audit");
System.out.println("You use your computer for " + usageHoursPerYear + " hours per year.");
System.out.println("It will use " + usageWattHoursPerYear + " KWH/year.");
System.out.println("Whih will cost " + costPerYear + "$/year for electricity.");
System.out.println("Generating that electricity will produce " + lbsCO2PerYear + " lbs of CO2 pollution.");
return;
}
}
Inputs:
8 hours/day
5 days/week
50 weeks/year
100 watts/hour
My (wrong output):
Computer Energy Audit:
You use your computer for 2920.0 hours per year.
It will use 876000.0 KWH/year.
Whih will cost 127.02$/year for electricity.
Generating that electricity will produce 515.2194 lbs of CO2 pollution.
Correct Output:
Computer Energy Audit:
You use your computer for 2000.0 hours per year.
It will use 200.0 KWH/year.
Which will cost 28.999999999999996 $/year for electricity.
Generating that electricity will produce 117.63 lbs of CO2 pollution.
You take in the number of days per week and weeks per year as input, but forget to use them in your calculations. Also, instead of printing KWH, you are displaying the variable storing Watt Hours.
// Calculations
usageHoursPerYear = usageHoursPerDay * usageDaysPerWeek * usageWeeksPerYear; //calculate based on time used, not 365 days in the year
usageWattHoursPerYear = wattsPerHour * usageHoursPerYear; //use variable from above line
usageKWHPerYear = usageWattHoursPerYear / 1000;
costPerYear = usageKWHPerYear * COST_PER_KWH;
lbsCO2PerYear = LBS_CO2_PER_KWH * usageKWHPerYear;
// Printing Energy Audits
System.out.println("Computer Energy Audit");
System.out.println("You use your computer for " + usageHoursPerYear + " hours per year.");
System.out.println("It will use " + usageKWHPerYear + " KWH/year."); //changed to correct variable
System.out.println("Whih will cost " + costPerYear + "$/year for electricity.");
System.out.println("Generating that electricity will produce " + lbsCO2PerYear + " lbs of CO2 pollution.");

grade avg calculator not returning correct answer

This is a program to calculate average grades and I cant figure out whats wrong with my code. It is returning the wrong answer.
Editing post to remove personal information.
:
/**
* This program will calculate grade average of user input
* Date: 10/2/2015
*/
import java.util.Scanner;
public class GradeAVG {
public static void main(String[] args) {
avgGrade();
}
public static void avgGrade() {
Scanner keyboard = new Scanner (System.in);
double count = 0;
double avgGrade = 0 ;
double grade;
double total = 0;
System.out.println("Please input the grade");
grade = keyboard.nextDouble();
while(true){
System.out.println("Please input the grade");
grade= keyboard.nextDouble();
count = count + 1;
if (grade < 0) break;
total += grade;
avgGrade = total/count;
}
System.out.println ("Sum is " +total);
System.out.printf("The average of the %.0f grades are %.2f " ,count ,avgGrade);
}
}
Output:
Please input the grade
100
Please input the grade
50
Please input the grade
-9
Sum is 50.0
The average of the 2 grades are 50.00
Sum should have been 150 and average 75.
The problem is that you are reading a grade from the user before the while loop begins and you are ignoring this value afterwards.
You should remove those 2 lines and things will work as expected. I commented those lines in the snippet below to explicitely show you the problem.
public static void avgGrade() {
Scanner keyboard = new Scanner(System.in);
double count = 0;
double avgGrade = 0;
double grade;
double total = 0;
// System.out.println("Please input the grade");
// grade = keyboard.nextDouble();
while(true){
System.out.println("Please input the grade");
grade = keyboard.nextDouble();
count = count + 1;
if (grade < 0) break;
total += grade;
avgGrade = total/count;
}
System.out.println ("Sum is " +total);
System.out.printf("The average of the %.0f grades are %.2f " ,count ,avgGrade);
}
As a side note, you should always try to minimize the scope of each of your variable. Here, the grade variable is only use inside the while loop so you can directly write double grade = keyboard.nextDouble(); and remove the declaration in the beginning of the method.
You are not adding the first grade which you are accepting outside of the while loop to the total.
Also there is no point in incrementing the count, if the grade is not acceptable, so increment your count only after the grade check.
You can rewrite your while block something like
while (true) {
System.out.println("Please input the grade");
grade = keyboard.nextDouble();
if (grade < 0)
break;
count = count + 1;
total += grade;
}
avgGrade = total / count;
System.out.println("Sum is " + total);
System.out.printf("The average of the %.0f grades are %.2f ", count,
avgGrade);
}
Thanks guys. Here is the final code
/**
* This program will calculate grade average of user input
*
* Date: 10/2/2015
*/
import java.util.Scanner;
public class GradeAVG {
public static void main(String[] args) {
avgGrade()
}
public static void avgGrade()
{
Scanner keyboard = new Scanner (System.in);
double count = 0;
double avgGrade = 0 ;
double total = 0;
while(true){
System.out.println("Please input the grade");
double grade= keyboard.nextDouble();
if (grade < 0) break;
count = count + 1;
total += grade;
avgGrade = total/count;
}
System.out.println ("Sum is " +total);
System.out.printf("The average of the %.0f grades are %.2f " ,count ,avgGrade);
}
}
Several problems:
First, you do two assignments into grade before first reading from it (first one before the while loop and second inside the while loop), so the first input will be ignored entirely
Second, you increment the count variable before checking whether to break the while loop, so you end up with count higher by 1 than should be
Third, the average is computed inside the loop and will not be recalculated in the last (partial) iteration
The program will go like this:
input: 100, count: 0, total: 0, avg: 0
input was ignored
input: 50, count: 1, total: 50, avg: 50
input: -9, count: 2, total: 50, avg: 50
loop exit, but incremented count before; did not recalculate avg

How do I add String elements from a text file into an ArrayList?

The text file contains numbers separated by commas (ex. 458.58, 1598.45...).
I want to add an entire line from the text file into an ArrayList.
Here is my code so far:
// to calculate final output
ArrayList<String> weeklySales = new ArrayList<String>(7);
// week 1 sales
while(file.hasNext()) {
weeklySales.add(file.nextLine());
System.out.println("I ran!");
}
System.out.println(weeklySales);
EDIT: Sorry my question wasn't clear. My question is after running this code, it adds ALL the elements of the ENTIRE text file into my array, BUT I need to only add 1 LINE to its own individual ArrayList. So in total I will have as many array lists as there are lines of text in the file.
This is code, you can use :
String line = "458.58, 1598.45";
String array[] = line.split(", ");
Changing from String to double is possible by this way :
Double.valueOf(array[i]);
Changing array into list can be done with this :
ArrayList<String> list = new ArrayList<>();
list.addAll(Arrays.asList(array));
I finally got it working. I realized that the most convenient method for working with individual lines and separating individual numbers from the text file was using StringTokenizer. Here is the fully working code, all you will need is the text file, which is named 'SalesData.txt' and mine includes the following 3 lines:
1245.67,1490.07,1679.87,2371.46,1783.92,1461.99,2059.77
2541.36,2965.88,1965.32,1845.23,7021.11,9652.74,1469.36
2513.45,1963.22,1568.35,1966.35,1893.25,1025.36,1128.36
This program outputs the following:
-Total sales for each week
-Daily average for each week
-Total sales of all the weeks
-Average weekly total
-The week with the highest sales
-The week with the lowest sales
DecimalFormat formatter = new DecimalFormat("#0.00");
// create file object
File salesData = new File("SalesData.txt");
// open file
Scanner file = new Scanner(salesData);
// declare 2 dimensional array
double[][] weeklySales = new double[3][7];
// loop to initialize token
int row = 0;
while(file.hasNext()) {
// initialize token
String line = file.nextLine();
StringTokenizer tokens = new StringTokenizer(line, ",");
// fill columns and rows
int col = 0;
while(tokens.hasMoreTokens()) {
// convert to double and assign to token
weeklySales[row][col] = Double.parseDouble(tokens.nextToken());
// move up 1 column
col++;
}
// move down 1 row
row++;
}
// calculate weekly sales
double week1Sales = 0, week2Sales = 0, week3Sales = 0;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 5; j++) {
double daily = weeklySales[i][j];
if(i == 0)
week1Sales += daily;
else if(i == 1)
week2Sales += daily;
else if(i == 2)
week3Sales += daily;
}
}
// week 1 sales
System.out.println("Week 1 total sales: $" +formatter.format(week1Sales));
// week 2 sales
System.out.println("Week 1 total sales: $" +formatter.format(week2Sales));
// week 3 sales
System.out.println("Week 1 total sales: $" +formatter.format(week3Sales));
// average daily for week 1
System.out.println("Daily average for week 1: $" +formatter.format(week1Sales / 7));
// average daily for week 2
System.out.println("Daily average for week 2: $" +formatter.format(week2Sales / 7));
// average daily for week 3
System.out.println("Daily average for week 3: $" +formatter.format(week3Sales / 7));
// total for all weeks
double weeklyTotal = week1Sales + week2Sales + week3Sales;
System.out.println("Total sales of all the weeks: $" +formatter.format(weeklyTotal));
// average weekly sales
System.out.println("Average weekly total: $" + formatter.format(weeklyTotal / 3));
// week number with highest sales
if(week1Sales > week2Sales)
if(week1Sales > week3Sales)
System.out.println("The week with the highest sales is week 1.");
else
System.out.println("The week with the highest sales is week 3.");
else if(week2Sales > week3Sales)
if(week2Sales > week1Sales)
System.out.println("The week with the highest sales is week 2.");
else
System.out.println("The week with the highest sales is week 1.");
else
System.out.println("The week with the highest sales is week 3.");
// week number with the lowest
if(!(week1Sales > week2Sales))
if(!(week1Sales > week3Sales))
System.out.println("The week with the lowest sales is week 1.");
else
System.out.println("The week with the lowest sales is week 3.");
else if(!(week2Sales > week3Sales))
if(!(week2Sales > week1Sales))
System.out.println("The week with the lowest sales is week 2.");
else
System.out.println("The week with the lowest sales is week 1.");
else
System.out.println("The week with the lowest sales is week 3.");

Categories

Resources