Finding an average of a loop from a different method? - java

I am in the middle of an exercise on arrays and I am currently stuck on one of the variations in which
I have to use an Array (no arraylists) to gather user input with a
max number of 100 inputs and the inputs must stop if a negative
number is inserted.
The program then prints each value input by the user on a separate
line with the "Above", "Below", or "EqualTo" relating to the average
of the inputs.
Issue :- I am currently stuck in how I am supposed to get the value of the inputs from the load method into the correct spots on the print method. The program will compile but will only return an average1 equal to zero. Any help is appreciated, I just can't use an arraylist
import java.util.Scanner;
public class ScoreSetNumber3
{
private int[] scores;
private static final int SIZE= 100;
private double average1;
Scanner keyboard = new Scanner(System.in);
public ScoreSetNumber3()
{
scores = new int[SIZE];
}
public void load()
{
System.out.println("Please enter scores");
double sum = 0;
for( int used = 0; used < scores.length; used++)
{
scores[used] = keyboard.nextInt();
if(scores[used] >= 0)
{
sum += scores[used];
}
else
{
System.out.println("End of Inputs");
double average1 = sum / used;
System.out.println("Average value of array elements is" + " " + average1);
break;
}
}
}
public double getAverage()
{
return average1;
}
public void print()
{
for(int used=0; used < scores.length; used++)
{
if(scores[used] > getAverage())
{
System.out.println(scores[used] + " Above");
}
else if(scores[used] == getAverage())
{
System.out.println(scores[used] + " EqualTo");
}
else
{
if(scores[used] < 0)
{
break;
}
System.out.println(scores[used] + " Below");
}
}
}
}

That's because you are not saving the average to the global variable average1 but to a local variable. That is why average1 returned by getAverage() equal to zero.
Change the below line in load() method from
double average1 = sum / used;
to
average1 = sum / used;

Related

Java Average of integers

i seem to be having trouble figuring out what to set the variable intValue to under the read value methods. The program is supposed to take 10 integers and average them, it works fine as far as catching exceptions and input, but the output displays all the numbers as 0 (because i set it to 0 temporarily but can not figure out what to change it to). Heres the code
package averagenumdriver;
import static java.lang.Integer.parseInt;
import java.util.Scanner;
public class AverageOfIntegers {
//Declare variables
private int numberOfValues;
private int[] integerValues;
private double average;
public AverageOfIntegers(int numberOfValues){
this.numberOfValues = numberOfValues;
}
//Define the readValues()
public void readValues(){
String stringValue = null;
int intValue = 0, i;
Scanner console = null;
i = 0;
integerValues = new int[numberOfValues];
while(i < numberOfValues){
try
{
console = new Scanner(System.in);
System.out.print("Enter value : ");
//read the value
stringValue = console.nextLine();
//check for number
intValue = 0;
parseInt(stringValue);
//Store only integer values
integerValues[i++] = intValue;
}
catch(NumberFormatException ex)
{
//Catch exception and handle it
System.out.println("Invalid Number entered" + "Reenter again ");
continue;
}
}
}
//read integer values
public void printValues()
{
System.out.println("Given values are ");
for (int i = 0; i < numberOfValues; i++)
{
System.out.println("Number: " + (i + 1) + " = " +
integerValues[i]);
}
}
public double getAverage()
{
int sum = 0;
//Calcualte the sum of integer values
for (int i = 0; i < numberOfValues; i++)
{
sum += integerValues[i];
}
//calculate average
average = (double)sum / numberOfValues;
return(average);
}
}
EDIT* question seems to be marked as a duplicate, but I am not asking about why division with two integers where the denominator is greater than numerator yields a 0.
Change
//check for number
intValue = 0;
parseInt(stringValue);
TO
//check for number
intValue = parseInt(stringValue);

Arrays with for loop and if statements

So when i i have tried to save and compile everything works fine until I run it. There seems to be an issue with my array syntax. Could someone help me find it?When I do run this program the grades()method outputs "AAA" . What I'm trying to do in this program is read text from a txt file and list each line, outputting a student name and score. Now in the grades() method I am trying to output calculate a letter grade for each of the students grades and make that go into a loop until the last score has been read.
public class ReadData
{
private static String[] names = new String[3];
private static int line;
private static int[] scores = new int[3];
private static float mean;
private static double stdDeviation;
public static void readData() throws FileNotFoundException
{
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
int l = 0;
// float sum = 0 ;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String [] words = line.split("\t");
names[l] = words[0];
scores[l] = Integer.parseInt(words[1]);
// sum+=scores[l];
System.out.println(" name: " + names[l] + ", score: " + scores[l]);
l++;
}
// System.out.println(scores[0]+ " " + scores[1]+ " " + scores[2]);
}
public static void fndMean()
{
float mean = ((25+65+89)/3);
System.out.println(" The mean is: " + mean);
}
public static void fndStandard() throws FileNotFoundException
{
double stdDeviation = Math.sqrt(((Math.pow(25-59, 2)+(Math.pow(65-59,2))+
(Math.pow(89-59, 2))))/3);
System.out.println("The Standard Deviation is: " + stdDeviation);
}
Grades method
public static void grades()
{
for(int i = 0; i < (scores.length); i++)
{
if(mean + stdDeviation <= scores[i])
{
System.out.print("A");
}
else if( (scores[i] >= mean+(stdDeviation/3)) &&
(mean +stdDeviation)> scores[i])
{
System.out.print("B");
}
else if( (scores[i] >= mean-(stdDeviation/3)) &&
(mean +(stdDeviation/3))> scores[i])
{
System.out.print("C");
}
else if( (scores[i] >= mean-(stdDeviation)) &&
(mean - (stdDeviation/3))> scores[i])
{
System.out.print("D");
}
else
{
System.out.println("F");
}
}
}
You are re-declaring your variables in methods like fndMean() and fndStandard() when you do the following
double stdDeviation = Math.sqrt(((Math.pow(25-59, 2)+(Math.pow(65-59,2))+
(Math.pow(89-59, 2))))/3);
float mean = ((25+65+89)/3);
You already declare them up top and don't need to do it again, otherwise it will only set the local variables inside the methods and not inside your class. you should do
stdDeviation = Math.sqrt(((Math.pow(25-59, 2)+(Math.pow(65-59,2))+
(Math.pow(89-59, 2))))/3);
mean = ((25+65+89)/3);
Which will set those variables to what you were expecting when you call those methods BEFORE calculating the grades.
This is what fndMean and fndStandard methods print:
The mean is: 59.0
The Standard Deviation is: 26.407069760451147
Sum of mean and stdDeviation is 85.40706976045115.
Now, the condition if(mean + stdDeviation <= scores[i]) checks whether that sum is less than equal to score[i] and if yes, prints 'A'. It can be true in either of these two cases:
Values in second column (tab) in txt files are all more than 85
score array gets altered between two method calls
Printing score value before those conditions should give you some more idea.

Java program will not recognize sentinel value

My program accept input data from a user (up to 20 values) and calculate the average/find the distance from the average. If the user enters "9999" when no numbers have been added yet it will display an error message and tell the user to re-enter a value. Otherwise entering "9999" will collect what the user has entered and do its calculations. My program will have to collect all 20 inputs from the user and also ignore when the value "9999" is entered completely but, it will do the other calculations correctly. I'm not sure why its not recognizing my sentinel value whatsoever.
package labpack;
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers = new double[20];
double sum = 0;
int sentValue = 9999;
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the numbers you want up to 20");
do {
for (i = 0; i < numbers.length; i++) {
if (numbers[0] == sentValue){
System.out.println("Error: Please enter a number");
break;
}
else {
numbers[i] = input.nextDouble();
sum += numbers[i];
}
}
while (i<numbers.length && numbers[i]!=sentValue); //part of do-while loop
//calculate average and distance from average
double average = (sum / i);
System.out.println("This is your average:" + average);
for (i = 0; i < numbers.length; i++) { //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}
}
}
You can do this without doing the do-while and doing while instead.
if (numbers[0]== sentValue){
System.out.println("Error: Please enter a number");
break;
Here you are trying to compare the value without initializing the array with the user input.
This can be done in a much simple way :
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers =new double[10];
double sum =0;
double sentValue=9999;
int count = 0;
System.out.println(numbers.length);
System.out.print("Enter the numbers you want up to 20");
Scanner input = new Scanner(System.in);
while (i<numbers.length){
double temp = input.nextDouble();
if (temp >= sentValue){
if(i==0){
System.out.println("Error Message Here");
} else {
break;
}
}//if
else {
numbers[i] = temp;
sum += numbers[i];
i++;
count++;
}
} //part of while loop*/
//calculate average and distance from average
double average=(sum/i);
System.out.println("This is your average:" + average);
for (i=0;i < count;i++){ //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}//for loop
}//main bracket
}//class lab4 bracket
You need to store the value of the input.nextDouble() into a variable because when the compiler reads input.nextDouble(), each time it will ask the user for an input.
PS. You dont need to re-initialize this part :
java.util.Scanner input = new java.util.Scanner(System.in);
The above line can simply be written as :
Scanner input = new Scanner(System.in);
because you already imported Scanner.
import java.util.Scanner;
Hope this helps :)

Arrays JOptionPane version

can anyone help me with this.
the assignment is to use JOptionPane in arrays. the user will input the length of the array. then at the end of the program, it will display the largest number.
here is what i got so far:
import javax.swing.JOptionPane;
public class array
{
public static void main(String[] args)
{
String L;
int lenght;
L=JOptionPane.showInputDialog(null,"enter lenght: ");
lenght=Integer.parseInt(L);
int[]num = new int[lenght];
for(int counter = 0; counter < lenght ;counter++)
{
JOptionPane.showInputDialog(null,"enter #: "+(counter+0));
int max=num[0];
if (num[counter] > max)
{
max = num[counter];
}
}
JOptionPane.showMessageDialog(null,"the largest number is: " + max);
}
}
then there is this error:
error: cannot find symbol
maxis defined in scope of for loop. So it is not available outside of for.
Define it outside of the for loop and it should work:
public static void main(String[] args) {
String L;
int lenght;
L = JOptionPane.showInputDialog(null, "enter lenght: ");
lenght = Integer.parseInt(L);
int[] num = new int[lenght];
int max=0;
for (int counter = 0; counter < lenght; counter++) {
JOptionPane.showInputDialog(null, "enter #: " + (counter + 0));
max = num[0];
if (num[counter] > max) {
max = num[counter];
}
}
JOptionPane.showMessageDialog(null, "the largest number is: " + max);
}
Update:
You never store the input value to num[counter]
num[counter] = Integer.parseInt(JOptionPane.showInputDialog(null, "enter #: " + (counter + 0)));
package retedunits;
import java.util.Scanner;
public class RentedUnits {
private Integer TOTAL_NUMBER_RENT_UNITS; //Total number of rented units
private Double rentPerUnit; //Rent Per Unit
private Double maintainancePerUnit; //Average Maintainance cost per unit
private Integer currentUnitsRented; //Number of units currently occupied
private Double rentIncreaseFactor; //The level at which people leave
//PROFIT MAX
private Double maxRentForProfit;
private Integer maxUnitsForProfit;
public RentedUnits(Integer totalUnits, Double initalRentPerUnit, Double initialMaintainanceCost, Integer currentRented, Double rentIncreaseFactor){
this.TOTAL_NUMBER_RENT_UNITS = totalUnits;
this.rentPerUnit = initalRentPerUnit;
this.maintainancePerUnit = initialMaintainanceCost;
this.currentUnitsRented = currentRented;
this.rentIncreaseFactor = rentIncreaseFactor;
}
public Double getMaxRentForProfit() {
return maxRentForProfit;
}
public Integer getMaxUnitsForProfit() {
return maxUnitsForProfit;
}
private void increaseRent(Double increasedRent){
//For each $40 increase in rent one unit is vacant.
if(increasedRent > this.rentIncreaseFactor) {
//The number of units that will become vacant is one for every increase of rentIncreaseFactor
int numberVacate = (int) (increasedRent % this.rentIncreaseFactor);
this.currentUnitsRented -= numberVacate;
this.rentPerUnit += increasedRent;
}
else {
this.rentPerUnit += increasedRent;
}
}
private Double calculateProfit(){
//Calculate total rent collected from units that are rented
Double totalRent = this.currentUnitsRented * this.rentPerUnit;
//calculate the maintainanec of all units
Double totalMaintainence = this.TOTAL_NUMBER_RENT_UNITS * this.maintainancePerUnit;
return totalRent - totalMaintainence;
}
public void maximizeProfit(){
/*Keep increasing rent, and let people leave till the total collected
* rent keeps increasing.
*/
/* Assume you begin at all units occupied*/
Double maximumProfit = 0.0;
Double maxProfitRent = 0.0;
Integer maxProfitUnits = 0;
/* Keep increasing rent till all people leave while tracking max profit*/
while(this.currentUnitsRented == 0){
increaseRent(this.rentIncreaseFactor);
if(this.calculateProfit() > maximumProfit){
maximumProfit = this.calculateProfit();
maxProfitRent = this.rentPerUnit;
maxProfitUnits = this.currentUnitsRented;
}
}
this.maxRentForProfit= maxProfitRent;
this.maxUnitsForProfit = maxProfitUnits;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
RentedUnits rentedUnits = new RentedUnits(50, 600.0, 27.0, 50, 40.0);
rentedUnits.maximizeProfit();
System.out.println(rentedUnits.getMaxUnitsForProfit() + " units needs to be rented at " + rentedUnits.getMaxRentForProfit() + " rent per unit to get maximum profit.");
}
}

In Java how do i find the max and min from a text file?

#rayryeng has been very helpful to me in my most recent attempt at correcting this file. Since my question has now slightly changed, I've decided to create a new question. I have the following code and I am trying to make it find my maximum and minimum based on the list from the txt file. The text file looks like this:
6
88
77
92
82
84
72
The top number should not be calculated in the sum and average which is why I have put a -6 and -1 in my code (as seen below).
package trials;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class trials2 {
public static void main(String[] args) throws IOException {
// Create new Scanner object to read from the keyboard
Scanner in = new Scanner(System.in);
// Grab the name of the file
System.out.println("Please enter the name of your data file: ");
String fileName = in.next();
// Access the file
Scanner fileToRead = new Scanner(new File(fileName));
// While there is still stuff in the file...
double sum = -6;
int numStudents = -1;
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble()) {
numStudents++;
sum += fileToRead.nextDouble();
} else {
fileToRead.next();
}
}
{
fileToRead.close();
}
System.out.println("***Welcome to the Exam Statistics Program!!***");
System.out.println("Minimum = " + Math.min(sum,sum));
System.out.println("Maximum = " + Math.max(sum,sum));
System.out.println("Average score: " + sum/numStudents);
System.out.println();
System.out.println("Number of scores by letter grade: ");
System.out.println();
System.out.println("There are " + numStudents + " scores");
}
}
I know that the sum,sum is wrong, but I needed something to fill in there so that I would remember to get it filled.
I've already tried searching through these posts as well as many others for help:
How to find min and max, Finding min/max
but I continue to get errors. Today is my very first day doing Java, so I have little to no clue where to go from here :-/
Final changes to code
package trials;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class trials2 {
public static void main(String[] args) throws IOException {
// Create new Scanner object to read from the keyboard
Scanner in = new Scanner(System.in);
// Grab the name of the file
System.out.println("Please enter the name of your data file: ");
String fileName = in.next();
// Access the file
Scanner fileToRead = new Scanner(new File(fileName));
// While there is still stuff in the file...
double sum = -6;
int numStudents = -1;
double maxVal = 0, minVal = 0; //NEW
boolean bFirstTime = true; //NEW
double currVal; //NEW
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble()) {
numStudents++;
currVal = fileToRead.nextDouble(); //NEW
//NEW
if (bFirstTime) {
maxVal = currVal;
minVal = currVal;
bFirstTime = false;
} else {
maxVal = Math.max(maxVal,currVal);
minVal = Math.min(minVal, currVal);
}
sum += currVal;
} else {
fileToRead.next();
}
}
System.out.println("***Welcome to the Exam Statistics Program!!***");
System.out.println("Minimum = " + minVal);
System.out.println("Maximum = " + maxVal);
System.out.println("Average score: " + sum/numStudents);
System.out.println();
System.out.println("Number of scores by letter grade: ");
System.out.println();
System.out.println("There are " + numStudents + " scores");
}
}
Math.min(x,y) returns the minimum of x and y. Math.max(x,y) returns the maximum of x and y. You should create two double variables called maxVal and minVal. In your loop, as you are getting each double value, use Math.min() and Math.max() to compare the current double value to maxVal and minVal. For example:
// While there is still stuff in the file...
double sum = -6;
int numStudents = -1;
double maxVal, minVal; //NEW
boolean bFirstTime = true; //NEW
double currVal; //NEW
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble()) {
numStudents++;
currVal = fileToRead.nextDouble(); //NEW
//NEW
if (bFirstTime) {
maxVal = currVal;
minVal = currVal;
bFirstTime = false;
} else {
maxVal = Math.max(maxVal,currVal);
minVal = Math.min(minVal, currVal)
}
sum += currVal;
} else {
fileToRead.next();
}
}
You could try writing to an array list and using the collections class.
ArrayList<type> list = new ArrayList<type>"();
while (fileToRead.hasNext()) {
list.add(fileToRead.nextDouble());
}
int max = Collections.max(list);
int min = Collections.min(list);
How to find min and max:
Have two variables. Call them min and max.
Set min with the biggest number you can find.
If min and max are Integer, then you already have MAX_VALUE and MIN_VALUE sets.
Set max with the smallest number around.
Then for every number you find, do:
max = Math.max(max, number);
min = Math.min(min, number);

Categories