Can't enter loop with int but only using final int - java

I've created this class in a separate file and the program runs. The questions I have is the for a loop. Currently, I'm using a final int. I wanted to input a variable for
ol < MAX_R
} // End input loop
// Added feature that is not part of grading
System.out.print("Press enter to see results: ");
try {
System.in.read();
} catch (Exception e) {
e.printStackTrace();
}

Well, I think that author wants to read round scores for input stream and calculate an average. This is pretty simple, I think. First, you have to split your method into required logical parts: read data from stream, data processing, output data (to make your code simple and clear).
Java is not a C++. Here you can define array size wherever you like, as well as using user's input at runtime (Java does not require to know size of array at compile time).
public class Foo {
public static void main(String... args) {
double[] scores = readRoundScores();
double avg = calcAverageScore(scores);
System.out.println("\nAverage score: " + avg);
}
private static double[] readRoundScores() {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Enter total rounds: ");
double[] scores = new double[scan.nextInt()];
for (int i = 0; i < scores.length; i++) {
System.out.printf("Enter your round %d score: ", i + 1);
scores[i] = scan.nextDouble();
}
return scores;
}
}
private static double calcAverageScore(double... scores) {
double sum = 0;
for (double score : scores)
sum += score;
return sum / scores.length;
}
}

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

Better way of making program that calculates sum and average in java

I made a java command line program for calculating sum and average of an arbitary series of numbers, but I am wondering is there any better way for making it shorter and maybe without an array?
public class Main {
public static void main(String[] args) {
System.out.println("------------------");
System.out.println("Program for calculating sum and average of an arbitary series of numbers");
System.out.println("------------------");
Scanner input = new Scanner(System.in);
System.out.print("How many numbers do you want to calculate? ");
int nums = input.nextInt();
int array[] = new int[nums];
int sum = 0;
for (int i=0; i<nums; i++){
System.out.print("Enter " + (i+1) + ". number: ");
array[i] = input.nextInt();
}
for (int i=0; i<array.length; i++){
sum= sum + array[i];
}
System.out.println("Sum is: " + sum);
System.out.print("Average is: " + (sum/nums));
}
}
You have two for loops in your code. The first one writes values to an array, and the second one reads them to get their sum. You don't really need both of those loops (or the array). You can sum the values as you read them in, then calculate the average based on the sum.
Note, though, that if you want to extend your code later to calculate other stats on the entered data (e.g., standard deviation) it will be easier to work with the data stored in an array.
You don't need to store these numbers to an array.
Usage of BufferedReader is inexpensive over Scanner in this case. Refer reasons to consider using BufferedReader.
public static void main(String[] args) throws IOException {
System.out.println("------\nProgram for calculating sum and average of integers\n------");
System.out.print("Enter space separated integer values: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] split = reader.readLine().split("\\s");//splits string on whitespaces
double sum=0, average;
for (String numberString : split)
sum += Integer.parseInt(numberString);
average = sum / split.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
}
A simple solution, where the user does not have to enter the number of the numbers first.
public static void main(String[] args) {
System.out.println("------------------");
System.out.println("Program for calculating sum and average of an arbitary series of numbers");
System.out.println("------------------");
Scanner input = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
System.out.print("Input numbers. Input something else (e.g. enter) if you're finisehd:\n");
while (true) {
try {
values.add(Integer.parseInt(input.nextLine()));
} catch (Exception e) {
break;
}
}
System.out.println("Sum is : " + values.stream().mapToInt(Integer::intValue).sum());
System.out.println("Average is: " + values.stream().mapToInt(Integer::intValue).average().getAsDouble());
}

Insight with ending a loop by pressing the enter key in Java

I am in a low level java programming class, and I am having trouble figuring something my professor assigned to us. We originally made a program that added integers that were placed in an arraylist. She then asked us to make it as user friendly as possible, without having a specific amount of integers the user inputs. So I came up with this:
public class CalculatorREDONE
{
public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter any numbers you would like to add. ");
Scanner input = new Scanner(System.in);
do
{
numbers.add((int) input.nextInt()); //inserting input into the arraylist
System.out.println("The sum is " + sum(numbers)); //test output
}while(input.hasNextInt()); // I believe this needs to change but I am unsure what it should be
System.out.println(sum(numbers));
//My Problem here is that the loop doesn't end, therefore cannot print this output
input.close();
}
public static int sum(ArrayList<Integer> list)
{
int total = 0;
for (int i = 0; i < list.size(); i++)
{
total += list.get(i);
}
return total;
}
}
Sorry for the clutter of comments, I'm trying to show any of you my mindset behind what I did. Thank you so much in advance for anyone that has any suggestions!
See if this helps where in you take an input from user to terminate the program.
public class CalculatorREDONE {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter any numbers you would like to add or -1 to exit");
Scanner input = new Scanner(System.in);
// boolean nextAvailable = true;
while(true)
{
String nextVal = input.nextLine();
if(nextVal.isEmpty()) {
break;
}
numbers.add(Integer.parseInt(nextVal)); //inserting input into the arraylist
// System.out.println("The sum is " + sum(numbers)); //test output
} //while (!input.next().); // I believe this needs to change but I am unsure what it should be
System.out.println(sum(numbers));
//My Problem here is that the loop doesn't end, therefore cannot print this output
input.close();
}
public static int sum(List<Integer> list) {
int total = 0;
for (int i = 0; i < list.size(); i++) {
total += list.get(i);
}
return total;
}
}
Try this -- it takes the input as a string, checks the length. If the user just hits enter the length will not be greater than zero. This catches the number exception from the parseInt by confirming the user has ended their list.
Note that I didn't include your sum portion since it wasn't relevant to the question of breaking the loop. You'll need to re-add
import java.util.Scanner;
import java.util.ArrayList;
public class CalculatorREDONE
{
public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter any numbers you would like to add. ");
Scanner input = new Scanner(System.in);
String userinput = "xx";
int nextnum = 0;
while (userinput.length() > 0) {
try {
userinput = input.nextLine();
nextnum = Integer.parseInt(userinput);
numbers.add(nextnum);
System.out.println("Taken");
} catch (NumberFormatException e) {
System.out.println("Inputs complete");
}
}
System.out.println(numbers);
input.close();
}
}

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.

using scanner class to average numbers in java

I am using a scanner class to average numbers together. I am using a method to do the averaging. I do not want the program to run if there are more than 20 args. I cant seem to get this to work. I am very new at java and trying to learn.
I appreciate any help I can get. Thanks!
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double x = 0.00d;
if (args != null) {
System.out.println ("Enter your numbers to be averaged. Remember no more than 20!:");
x = scan.nextInt();
if (x <= 21) {
System.out.println("Please do not add more than 20 numbers");
}
} else {
}
}
public double average(double [] values) {
double average = 0.0;
if ((values != null) && (values.length > 0)) {
for (double value : values) {
average += value;
}
average /= values.length;
}
return average;
}
}
Just run a while loop that breaks when 20 "args" is met or until a break like -1 is entered. Then if you are taking double values, you should use x = scan.nextDouble(). You also do not have a place where you are inserting the values into your array. At the end of your while loop you could put x into an array of doubles.
private double x;
private double Foo[] = new Foo[20];
private int this = 0; //Your counter
while(this < 20 && x != -1)
{
x = scan.nextDouble();
Foo[this++] = x;
}
Then carry out your public double Average by adding up the values in the array and dividing by (double)this
Here is a solution (cleaning up a lot of your code as well) that gets all the numbers on one line after the start of the program:
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double values[] = new double[20];
int count = 0;
System.out.println ("Enter your numbers to be averaged. Remember no more than 20!:");
String inputs = scan.nextLine();
scan = new Scanner(inputs); // create a new scanner out of our single line of input
while(scan.hasNextDouble())
{
if(count == 20)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
values[count] = scan.nextDouble();
count += 1;
}
System.out.println("Your average is: " + average(values, count));
}
public static double average(double [] values, int count) {
double average = 0.0;
for (double value : values) {
average += value;
}
average /= count;
return average;
}
}
I got thinking you might want to use the args that are passed to main, since you use a null check, so you want to run your program like this:
java programTwo num1 num2 num3 num4 num5
etc. If that's the case, we have another solution:
class programTwo {
public static void main (String[] args) {
if(args.length > 20)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
double values[] = new double[args.length];
for(int i=0; i< args.length; ++i)
values[i] = Double.valueOf(args[i]);
System.out.println("Your average is: " + average(values));
}
public static double average(double [] values) {
double average = 0.0;
for (double value : values) {
average += value;
}
average /= values.length;
return average;
}
}
The args != null check is unnecessary. One way to accomplish what you want is to accept numbers while the scanner has a next number (scanner.hasNext() perhaps) and break if the number of inputs thus far is less than 20. Since the number of double numbers is unknown, you're better off using an ArrayList.
List<Double> doubles = new ArrayList<Double>();
and calling the add method on doubles
doubles.add(x);
Then pass this to a method that averages the values in the arraylist.

Categories