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.
Related
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
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
My code won't allow me to enter in multiple integers to where it can then compute the sum, the count of integers, the minimum, and the sum of positive even integers. I am not sure if I need another method or if im calling for the wrong things.
import java.util.Scanner;
public class Assignment2 {
private static final Scanner input = null;
private static int n;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum=0, minNumber=0, nCount=0, countEvenIntegers=0;
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
//when code reads 0, code terminates
int[] numbers = new int[4];
for(int i=0; i<4; i++){
numbers[i] =sc.nextInt();
}
while(!(n==0)){
sum += n;
n = input.nextInt();
}
class SumOfValues {
public int sum(int...vals){
int sum=0;
for (int val : vals) {
sum+= val;
}
return sum;
}
}
class CountingInts{
public void main(String[] args){
Scanner input=new Scanner(System.in);
int count=0;
System.out.print("Numbers: ");
while (input.hasNextInt()){
input.nextInt();
count++;
}
System.out.print(count);
input.close();
}
}
int sumPositive = 0;
System.out.println("The minimum integer is " + minNumber + "\nThe count of integers is "
+ nCount + "\nThe sum of positive integers is " + sumPositive + "\nThe count of even integers in the sequence is " +
countEvenIntegers );
}
}
It looks like you are an absolute beginner, so I'd recommend not dealing with functions and classes and all that, and just write everything linearly. I'm not sure why you have all those functions, classes and variables, but to help you, this is probably the simplest way to achieve what you are trying to do.
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args) {
int sum = 0, minNumber = 0, nCount = 0, countEvenIntegers = 0;
Scanner sc = new Scanner(System.in);
while (true) {
int input = sc.nextInt();
if (input == 0) {
break;
}
sum += input;
nCount += 1;
}
System.out.println("The minimum integer is " + minNumber);
System.out.println("The count of integers is " + nCount);
System.out.println("The sum of positive integers is " + sum);
System.out.println("The count of even integers in the sequence is " + countEvenIntegers);
}
}
Note that I've not added the minimum interger and count of even intergers for you to complete.
Not quite sure what you are doing in your code since you are not doing any operations on the variables you are outputting, and thus should not expect the output to be any other than 0.
Also, your inner classes are really weird.
Here is an example (based on your code) that does what you want. Plenty of ways of achieving your goal, but I think this is simple enough:
import java.util.Scanner;
import java.util.*;
public class Assignment2{
private static final Scanner input = null;
private static int n;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum=0, minNumber=0, nCount=0, countEvenIntegers=0, sumPositive = 0;
Scanner sc = new Scanner(System.in);
List<Integer> numbers = new ArrayList<Integer>();
while(true) {
int i = sc.nextInt();
if(i == 0) {
break;
}
numbers.add(i);
}
if(numbers.size() > 0) {
minNumber = numbers.get(0);
}
for (int number : numbers) {
sum += number;
if(minNumber > number) {
minNumber = number;
}
if(number % 2 == 0) {
countEvenIntegers++;
}
if(number > 0 ) {
sumPositive += number;
}
}
nCount = numbers.size();
System.out.println("The minimum integer is " + minNumber + "\nThe count of integers is "
+ nCount + "\nThe sum of positive integers is " + sumPositive + "\nThe count of even integers in the sequence is " +
countEvenIntegers + "\nThe total sum is " + sum);
}
}
#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);
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.