Arrays with for loop and if statements - java

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.

Related

Sending output of a java program with methods to file

I have a program that I already created in Java that has several methods that ask for user input.
This is the program:
static Scanner numberscanner = new Scanner(System.in);
static Integer[] houses = {0,1,2,3,4,5,6,7};
public static void main(String[] args)
{
askForCrates();
getTotal();
int max = houses[0];
getMin();
getMaxHouse(max);
//Display the house number that recycled the most
}
//asks for the crates for each specific house number
public static void askForCrates()
{
for (int i = 0; i < houses.length; i++)
{
System.out.println("How many crates does house " + i + " have?") ;
Integer crates = numberscanner.nextInt();
houses[i] = crates;
}
}
//uses a for statement to get the total of all the crates recycled
public static void getTotal()
{
//Get total
Integer total = 0;
for (int i = 0; i < houses.length; i++)
{
total = total + houses[i];
}
System.out.println("Total amount of recycling crates is: " + total);
}
//Displays and returns the max number of crates
public static Integer getMax(Integer max)
{
for (int i = 0; i < houses.length; i++)
{
if(houses[i] > max)
{
max = houses[i];
}
}
System.out.println("Largest number of crates set out: " + max);
return max;
}
// gets the house numbers that recycled the most
// and puts them in a string
public static void getMaxHouse(Integer max)
{
ArrayList<Integer> besthouses = new ArrayList<Integer>();
String bhs = "";
for (int i = 0; i < houses.length; i++)
{
if(houses[i].equals(max))
{
besthouses.add(houses[i]);
}
}
for (Integer s : besthouses)
{
bhs += s + ", ";
}
System.out.println("The house(s) that recycled " + max + " crates were: " + bhs.substring(0, bhs.length()-2));
}
// gets the minimum using the Arrays function to sort the
// array
public static void getMin()
{
//Find the smallest number of crates set out by any house
Arrays.sort(houses);
int min = houses[0];
System.out.println("Smallest number of crates set out: " + min);
}
} // probably the closing '}' of the class --- added by editor
The program works fine but now I want to take all the output including the users input and put that output into a file.
I've seen ways to do this with BufferedWriter and FileWriter and I understand how those work with the input and output using the reader.
Except in the example programs I have seen, none of those programs have methods.
I can rewrite my program without methods or modify them to return input instead of being void and using System.println. But I was wondering if there is a way to send all the output of my program to a file without having to rewrite my program?
The easy way, you can run your program as:
java -jar app.jar >> log.out
Edit for the correct way:
PrintStream ps = new PrintStream("log.out");
PrintStream orig = System.out;
System.setOut(ps);
And don't forget:
ps.close();
in the end

Counting occurrences of integers in an array program java

I am trying to find the occurrences of all integers submitted by the user into the program and so far here's what I got. It works but I don't think it's a legit way to do it, is there any way I can try to do this without using the list[10]=9999;? Because if I don't do it, it'll show out of boundary error.
import java.util.*;
public class OccurrencesCount
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] list = new int[11];
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<10;i++){
list[i] = scan.nextInt();
list[10] = 9999;
}
//Sort out the array.
Arrays.sort(list);
int count = 1;
for(int i = 1;i<11;i++){
if(list[i-1]==list[i]){
count++;
}
else{
if(count<=1){
System.out.println(list[i-1] + " occurs 1 time.");
}
else{
System.out.println(list[i-1] + " occurrs " + count + " times.");
count = 1;
}
}
}
}
}
Personally, I think this is a perfectly good solution. It means that you can deal with the last group in the same way as all others. The only change I would make is putting the line list[10] = 9999; outside the for loop (there's no reason to do it 10 times).
However, if you want to use an array of length 10, you can change the line
if(list[i-1]==list[i])
to
if(i < 10 && list[i-1]==list[i])
If you do this, you won't get an ArrayIndexOutOfBoundsException from list[i] because the expression after the && is not evaluated when i == 10.
import java.util.*;
class OccurrencesCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] list = new int[101];
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<10;i++) {
int x = scan.nextInt();
list[x]++;
}
for(int i = 1; i <= 100; i++)
if(list[i] != 0)
System.out.println(i + " occurs " + list[i] + " times ");
}
}
To store count of numbers from 1 to 100 you need to use a list of 100 integers each one storing the number of occurrences of itself. Better approach would be to use a Map.
I have made use of ArrayList and Collections package instead of regular arrays as a different flavor if it interests you check it out.
import java.util.*;
public class OccurrencesCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for (int i = 0; i < 10; i++) {
list.add(scan.nextInt());
}
Collections.sort(list);
Integer prevNumber = null;
for (int number : list) {
if (prevNumber == null || prevNumber != number) {
int count = Collections.frequency(list, number);
System.out.println(number + " occurs " + count + (count > 1 ? " times." : " time."));
}
prevNumber = number;
}
}
}
I got it figured out guys, only changed a couple of small things inside the conditions and everything went smoothly! Thanks for the help! Now I just need to find a way to restrict the inputs from going above 100.
import java.util.*;
public class CountOccurrences
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] list = new int[10];
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<=9;i++){
list[i] = scan.nextInt();
}
//Sort out the array.
Arrays.sort(list);
int count = 1;
for(int i = 1;i<=10;i++){
if(i<=9 && list[i-1]==list[i]){
count++;
}
else{
if(count<=1){
System.out.println(list[i-1] + " occurs 1 time.");
}
else{
System.out.println(list[i-1] + " occurrs " + count + " times.");
count = 1;
}
}
}
}
}

Array not Recognized

My program is to enter 10 numbers and add them together then display the result. Then I am to divide the smaller number by the larger number and display the result. Users cannot enter characters or zero.
I am new and have been working on this for DAYS. I do not see my mistake.
Now my problem is the Variable i isn't being recognized.
I introduced an Exception (try..catch) and it wouldn't read. I tried moving things all over (I'm new, I'm guessing and seeing what does what..) I did something wrong and probably something stupidly small. I need some help and fresh eyes.
I also need to end the program when the user enters 9999. Any idea where that would go? 'Cause I'm about to break out into tears.
public static void main(String[] args) throws NumberFormatException {
Scanner in = new Scanner(System.in);
Scanner input = new Scanner(System.in);
double[ ] digit = new double[11];
int sum = 0;
//Declare an array
System.out.print("Please Enter Ten Numbers:");
System.out.println();
try{
for (int i = 1; i < digit.length; i++)
System.out.print("Numbers " + i + ": ");
digit[i] = (double)in.nextInt(); //Array Not recognized here
sum += (int)digit[i];//Or recognized here
// Input the data into array from the user.
if(digit[i]==0.0)//None of these are recognized either, what did I do?
{
System.out.println("You can't enter zero. Try again");
--i; //nope
in.nextLine();//dispose of wrong number
}
}catch (NumberFormatException e){
System.out.println("You Can Only Enter Numbers!");
--i; //nope, not recognizing here either
in.nextLine();//dispose of wrong input
}
System.out.println("Total Values in Array:"+ sum);
// Calculate the sum and print the total
System.out.println();
System.out.println("Would you like to divide the values?");
System.out.println("Yes or No to Exit the Program");
String a = input.next();
if(a.equalsIgnoreCase("yes")){
double [] divisionResult = new double[digit.length / 2];
//Division array declared
for (int i = 1; i < digit.length; i += 2)
//These are all good and recognized. No problem with the division part
{
double result = digit[i];
if (result > digit[i + 1])
result = result / digit[i + 1];
else {
result = digit[i + 1] / result;
}
divisionResult [i / 2] = result;
System.out.println(result);
}
}
else if(a.equalsIgnoreCase("no")){
System.exit(0);
}
}
}
}
You for loop doesn't have braces around it. Only the first line below it is part of the loop.
You need braces around the contents of your for loop.
I have tried to modified the attached code snippet. Hope this might help you.
package com.so.general;
import java.util.Scanner;
public class AddNumbers
{
private static final int SIZE_OF_ARRAY = 10;
public static void main(String[] args)
{
int counter = 0;
double sumOfTenDigits = 0.0;
double[] digit = new double[SIZE_OF_ARRAY];
int listOfElements = digit.length;
System.out.print("Please Enter Ten Numbers:"+"\n");
Scanner readInputFromUser = new Scanner(System.in);
try
{
for (counter=0; counter<listOfElements; counter++)
{
System.out.print("Numbers " + (counter+1) + ": ");
digit[counter] = Double.parseDouble(readInputFromUser.next());
if(digit[counter] == 0.0)
{
System.out.println("Zero is not allowed. Please try again.");
System.out.print("Numbers " + (counter+1) + ": ");
digit[counter] = Double.parseDouble(readInputFromUser.next());
}
sumOfTenDigits += digit[counter];
}
}
catch(NumberFormatException numberFormatExcep)
{
System.err.println(" You have entered other than numbers. Only numbers are allowed. Terminating the program.");
numberFormatExcep.printStackTrace();
System.exit(0);
}
System.out.println("Addition is: "+ sumOfTenDigits);
System.out.println("Would you like to divide the values? Press Y to continue, any other character to terminate the program.");
Scanner continueWithDivide = new Scanner(System.in);
String userInput = continueWithDivide.nextLine();
closeScanner(readInputFromUser);
closeScanner(continueWithDivide);
if(readInputFromUser != null)
{
readInputFromUser.close();
}
// Always use static string literals on the left hand side.
// This prevents Null pointer exception.
if("Y".equalsIgnoreCase(userInput))
{
double[] divisionResult = new double[listOfElements/2];
for(int i=0; i<listOfElements; i+=2)
{
double result = digit[i];
if (result > digit[i+1])
{
result = result/digit[i+1];
}
else
{
result = digit[i+1]/result;
}
divisionResult[i/2] = result;
System.out.println(result);
}
}
else
{
System.out.println("You have entered "+userInput+". Terminating the program.");
System.exit(0);
}
}
/**
* Closed the scanner
* #param scanner
*/
public static void closeScanner(Scanner scanner)
{
if(scanner != null)
{ try
{
scanner.close();
}
catch(IllegalStateException illegatStateExcep)
{
System.err.println("Scanner is already closed.");
illegatStateExcep.printStackTrace();
}
}
}
Please note the below points:
Always use proper indentation.
Always match { }
Even if your if or for is having only one statement, use { }.
For example:
for (int counter=1; i<digit.length; i++)
{
System.out.print("Numbers " + i + ": ");
}
Above three points will save a lot of your time if some thing goes wrong in your program.
Use proper name for the variables and method.
Always close the IO resources after the use.
For example:
if(scanner != null)
{
scanner.close();
}

Finding an average of a loop from a different method?

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;

Why doesn't my program call my methods?

java methods statithing but I can't seem to get my while statement on line 56 to call my methods properly. Is there something that I'm doing wrong? I am very new to Java so any sort of help would be appreciated! Thanks in advance!
Here is my code:
import java.util.*;
import javax.swing.*;
import java.io.*;
public class GradeCalculator {
static String fileInput;
static double totalGrade;
static int scoreCount= 0;
static double classAverage;
static double score;
static double testScore;
static double averageScore;
static int numberOfStudents = 0;
static char letterGrade;
static String fileOutput;
static String nameOfStudent;
static int numberCount;
static int numberCalculatedStudents;
static double average = 0;
public static void main (String[] args) throws FileNotFoundException {
//Welcome
JOptionPane.showMessageDialog(null,"Welcome to the Grade Calculator! This program will\n" +
" calculate the average percentage of 5 test scores that\n"+
" are given in a given file once these scores are\n"+
" averaged it will give the student a letter grade.","Welcome!",JOptionPane.PLAIN_MESSAGE);
fileInput = JOptionPane.showInputDialog(null, "Please enter the name of the input file you wish to use for this program."
,"Input File",JOptionPane.PLAIN_MESSAGE);
fileOutput = JOptionPane.showInputDialog(null, "Please enter the name of the output file you wish to use for this program."
,"Output File",JOptionPane.PLAIN_MESSAGE);
//preparing text files
PrintWriter outFile = new PrintWriter (fileOutput);
File inFile = new File (fileInput);
Scanner reader = new Scanner(new FileReader(fileInput));
outFile.println("Student Name Test1 Test2 Test3 Test4 Test5 Average Grade");
while(reader.hasNextLine()) {
nameOfStudent = reader.next();
outFile.printf("%n%n%s",nameOfStudent);
numberOfStudents++;
score = reader.nextDouble();
calculateAverage(score);
calculateGrade(averageScore);
outFile.printf(" %.2f ", averageScore);
outFile.println(" "+letterGrade);
}
classAverage = classAverage/numberCalculatedStudents;
outFile.print("\n\n\n\n\n\n\n\n\n\n\n\nClass average for "+ numberCalculatedStudents + "of" + numberOfStudents + "is" + classAverage);
JOptionPane.showMessageDialog(null,"The report has successfully been completed and written into the file of " + fileOutput +"."
+" The class average is " + classAverage + ". Please go to the output file for the complete report.");
outFile.close();
}
public static void calculateAverage(double score) throws FileNotFoundException {
Scanner reader = new Scanner(new FileReader(fileInput));
PrintWriter outFile = new PrintWriter (fileOutput);
while (reader.hasNextDouble() && numberCount <= 5 ) {
score = reader.nextDouble();
numberCount++;
if (score >= 0 & score <= 100) {
outFile.printf("%10.2f",score);
scoreCount++;
average = score + average;
}
else
outFile.printf(" **%.2f",score);
}
if (average!=0){
numberCalculatedStudents++;
average = average/scoreCount;
averageScore = average;
classAverage = average + classAverage;
}
average = 0;
}
public static char calculateGrade (double averageScore) {
if (averageScore >= 90 && averageScore <= 100)
letterGrade = 'A';
else if (averageScore < 90 && averageScore >= 80)
letterGrade = 'B';
else if (averageScore < 80 && averageScore >= 70)
letterGrade = 'C';
else if (averageScore < 70 && averageScore >= 60)
letterGrade = 'D';
else if (averageScore < 60 && averageScore >= 0)
letterGrade = 'F';
else
letterGrade =' ';
return letterGrade;
}
}
Without knowing what line the problem is arising on, two issues jump out at me:
At the top of the while loop:
if (score >= 0 & score <= 100)
{ outFile.printf("%10.2f",score);
scoreCount++;
average = score + average;
}
else
outFile.printf(" **%.2f",score);}
You have a close bracket (}) after the else statement, but no open bracket. So that close bracket looks like its exiting the while loop before you want it to.
Second, it looks like you're trying to return something (namely a char) in your CalculateGrade method, but you have specified a return type of void on it, which means that even though you have a return statement, nothing gets returned when you call it. You don't show where you're calling that method, so I can't be sure this is causing a problem, but its certainly suspect. It seems like you want to use:
public static char calculateAverage(double score) throws FileNotFoundException{
instead of public static void calculateAverage(double score)...
Also, is there a reason why all of these methods are static? Do you know what making something static means?
EDIT (based on your comment):
No. making a variable static makes it a "class variable", which means that only one of them exists for all objects of that class. To illustrate:
If you have a class like this:
class test {
static int id;
}
And you run the following code:
test t1 = new test();
test t2 = new test();
t1.id = 4;
t2.id = 8;
System.out.println(t1.id);
it will print 8. This is because, since id is a static variable changing it on any object of the class will cause it to change for every other object of the class.
This is as opposed to an "instance variable" one of which exists for every object of the class. To make id an instance variable, simply remove the static keyword. If you do so and run the same code, it will print 4, because changing an instance variable of t2 has no effect on t1.
Make sense?

Categories