Sending output of a java program with methods to file - java

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

Related

How do i stop program from running until user is finished inputting?

I want the user to be able to input the amount of numbers they specified BEFORE the code keeps running. Currently, the user is only able to input one number before the code continues. How do i keep the code from running until a certain amount of numbers are inputted?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n;
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter the amount of numbers you want the array to store: ");
// reads # of # user wants to enter
n = sc.nextInt();
// creates an array in the memory of length 10
int[] array = new int[10];
System.out.println("Enter "+n+" numbers ");
for (int i = 0; i < n; i++) {
// reading array elements from the user
array[i] = sc.nextInt();
double sum = 0;
double mode = 0;
double variance = 0;
double deviation = 0;
for (i = 0; i < 2; i++)
sum = sum + array[i];
//MEAN
mode = sum / 5;
sum = 0;
for (i = 0; i < 2; i++) {
sum = sum + Math.pow((array[i] - mode), 2);
}
//VARIANCE
variance = sum / 5;
//DEVIATION
deviation = Math.sqrt(variance);
//Standard
System.out.println("Standard Deviation is: " + deviation);
//mode
System.out.println("Mode is:" + mode);
//Variance
System.out.println("Variance is: " + variance);
}
}
}
I tried to let the user decide how many numbers should be in the array, then input that many numbers.
However, when i run the code, it doesn't give them enough time to type in the numbers.
I need a way to stop this from happening.
The first thing I discovered is that at no time are you using the variable "n" to create a constant value array, so it will always be an array of 10 elements.
One recommendation that I give you is that you do not use the "Scanner" class because it can give you problems if you ask the user for different types of data. Instead it uses BufferedReader because it is more direct. Here is an example of your exercise but fixed:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
private static Number getNumber(BufferedReader reader) throws IOException {
// Get input content
String line = reader.readLine();
return Double.parseDouble(line);
}
public static void main(String[] args) throws IOException {
// Auto closeable elements
try (InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader buffered = new BufferedReader(reader)) {
// Print message
System.out.print("The amount of numbers you want: ");
// Program variables here
final int totalSize = getNumber(buffered).intValue();
int[] arrayStore = new int[totalSize];
// Iterate all elementos of the array
for (int i = 0; i < totalSize; ++i) {
// Another message
System.out.print("Insert one number: ");
// Ask for numbers
int nextNumber = getNumber(buffered).intValue();
arrayStore[i] = nextNumber;
}
// TODO: Your logic program here
System.out.println(Arrays.toString(arrayStore));
}
}
}
If you were able to notice, the method that asks for the numbers does not check if the content is really a number, for that change the behavior of the getNumber method to the following:
private static Number getNumber(BufferedReader reader) throws IOException {
Number result = null;
do {
try {
result = Double.parseDouble(reader.readLine());
} catch (NumberFormatException e) {
System.err.println("The inserted content is not a valid number");
}
} while (result == null);
return result;
}
I hope it helps you in some way

How do I display all multiples of the starting value for as many multiples as the 2nd parameter states?

I am having trouble getting the right output. I am trying to get my program to do the following: display all multiples of the starting value for as many multiples as the 2nd parameter states.
I don't understand why I am not getting the correct answers when I compile the program. Can someone explain what I did wrong and how to correct?
import java.util.Scanner;
public class Proj3
{
public static void main(String[] args)
{
int iNumMultiples; //holds input by user
int iStartingValue; //holds input by user
int iVal; //holds the multiples
System.out.print("\nEnter integer for multiples and the number of multiples: ");
iStartingValue = kb.nextInt();
iNumMultiples = kb.nextInt();
System.out.print("\nThe first " + iNumMultiples + " multiples of " + iStartingValue + " are: " + iVal);
}
}
public class MyMath
{
//+displayMultiples(startingValue:int, numMultiples:int):void
public static void displayMultiples(int startingValue, int numMultiples)
{
int Val = 0;
for (int i=0; i<=numMultiples; i++)
{
Val += startingValue;
System.out.print("\n" + Val);
}
}
}
Not sure what kb is, you haven't defined it. You actually have to call your displayMultiples method. Not sure why you are breaking this into multiple classes.
public class MyProj {
public static void main(String[] args)
{
int iNumMultiples; //holds input by user
int iStartingValue; //holds input by user
int iVal; //holds the multiples
//System.out.println("Enter integer for multiples and the number of multiples: ");
iStartingValue = 5;
iNumMultiples = 5;
System.out.println("The first " + iNumMultiples + " multiples of " + iStartingValue);
displayMultiples(iStartingValue, iNumMultiples);
}
//+displayMultiples(startingValue:int, numMultiples:int):void
public static void displayMultiples(int startingValue, int numMultiples)
{
int val = 0;
for (int i=0; i<=numMultiples; i++)
{
val += startingValue;
System.out.println(val);
}
}
}

Text File I/O arraylist error is occuring

import java.io.*;
import java.util.*;
public class TextFile
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
PrintWriter myWriter = new PrintWriter(args[0]);
ArrayList<TextFile> myNums = new ArrayList<TextFile>();
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
double sum = 0;
double average;
for(int i = 1; i < args.length; i++)
{
FileReader myReader = new FileReader(args[i]);
Scanner intScan = new Scanner(myReader);
while (intScan.hasNextLine())
{
String textLine = intScan.nextLine();
myWriter.println(textLine);
}
myReader.close();
}
for(int i = 0; i < args.length; i++)
{
sum = sum + intScan[i];
average = sum / args.length;
if(myNums[i] > max)
{
max = intScan[i];
}
if(myNums[i] < min)
{
min = intScan[i];
}
}
System.out.println("The number of entries in the file is: " + args.length);
System.out.println("The sum is: " + sum);
System.out.println("The average is: " + average);
System.out.println("The largest number is: " + max);
System.out.println("The largest number is: " + min);
myWriter.close();
}
}
}
I am attempting to write a program where I pull grades from a file within the class folder that I am using and create an Array List that will count the number of entries, give the sum of entries, average, max and min numbers. What did I do wrong?
You cannot set up a Scanner intScan
and call it as an array variable intScan[i]
Same thing with your ArrayList myNums
What you are seeing are compile time errors from mistakes in your syntax. You are using ArrayList and Scanner as if they are array objects... which they are not.
Read this:
Scanner,
ArrayList
giving an object type of TextFile to your ArrayList does not make any sense.

How to use ArrayLists to output (.txt file) a report in a specific format that lists scores of athletes?

I'm having a bit of trouble with this project, and would greatly appreciate some help.
Here's a link to it:
http://www.cse.ohio-state.edu/cse1223/currentsem/projects/CSE1223Project11.html
The basic gist is it's "A program that reads in a text file that uses a specific input format and uses it to produce a formatted report for output."
Specifically:
"For this lab you will write a Java program that produces a simple formatted report. The program will prompt the user to enter a file name. This file must contain information in a specific format (detailed below). Each "block" of the file contains information for one player in a competition -- the name of the player followed by a number of different scores that that player achieved. The program should find each player's average score, median score and best and worst scores and display them in a line on the final summary report. The program should also determine which player has the highest average score and which player has the lowest average score."
I get the following errors when I try and compile it:
Enter an input file name: Project11.txt
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException... -1
at java.util.ArrayList.elementData(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at Project11.getMedian(Project11.java:68)
at Project11.main(Project11.java:27)
Sorry for not clarifying.
Line 68 is: return (inList.get(Middle - 1) + inList.get(Middle)) / 2;
Line 27 is: int median = getMedian(List);
Hope that helps.
Here's my code:
import java.io.;
import java.util.;
public class Project11 {
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
System.out.print("Enter an input file name: ");
String input = in.nextLine();
File inputFile = new File(input);
List<Integer> List = readNextSeries(inputFile);
int median = getMedian(List);
int mean = getAverage(List);
int max = getMaximum(List);
int min = getMinimum(List);
System.out.print("Enter an output file name: ");
String out = in.nextLine();
PrintWriter outputFile = new PrintWriter(out);
System.out.println("Median = " + median);
System.out.println("Mean = " + mean);
System.out.println("Max = " + max);
System.out.println("Min = " + min);
outputFile.println(median);
outputFile.println(mean);
outputFile.println(max);
outputFile.println(min);
outputFile.close();
}
// Given a Scanner as input read in a list of integers one at a time until a negative
// value is read from the Scanner. Store these integers in an ArrayList<Integer> and
// return the ArrayList<Integer> to the calling program.
private static List<Integer> readNextSeries(File f) {
ArrayList<Integer> List = new ArrayList<Integer>();
try {
Scanner fileScan = new Scanner(f);
while (fileScan.hasNextInt()) {
int value = Integer.parseInt(fileScan.next());
List.add(value);
}
} catch (FileNotFoundException e) {}
return List;
}
// Given a List<Integer> of integers, compute the median of the list and return it to
// the calling program.
private static int getMedian(List<Integer> inList) {
int Middle = inList.size() / 2;
if (inList.size() % 2 == 1) {
return inList.get(Middle);
}
else {
return (inList.get(Middle - 1) + inList.get(Middle)) / 2;
}
}
// Given a List<Integer> of integers, compute the average of the list and return it to
// the calling program.
private static int getAverage(List<Integer> inList) {
int total = 0;
int average = 0;
for(int element:inList){
total += element;
}
average = total / inList.size();
return average;
}
private static int getMaximum(List<Integer> inList) {
int largest = inList.get(0);
for (int i = 1; i < inList.size(); i++) {
if (inList.get(i) > largest) {
largest = inList.get(i);
}
}
return largest;
}
private static int getMinimum(List<Integer> inList) {
int smallest = inList.get(0);
for (int i = 1; i < inList.size(); i++) {
if (inList.get(i) < smallest) {
smallest = inList.get(i);
}
}
return smallest;
}
}
Thank you very much for any input.
Your getMedian(...) method doesn't handle the empty list case. Say you have an empty list (list of size 0), what do you think will happen? It will hit this line:
return (inList.get(Middle - 1) + inList.get(Middle)) / 2;
This inList.get(Middle - 1) is the same as inList.get(0 - 1) if the size of the list is 0. You want to make sure you methods handle all different cases. I'd recommend adding an if statement for this specific case (throw an Exception or give output so user knows what is wrong).
NOTE: This "all cases handling" applies to all your methods.

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;

Categories