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

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

Related

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

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;
}
}

Java User Input array is only capturing 3 integers instead of five

This code is supposed to capture 5 user integers, print them out, then print them in reverse. It is capturing the first int only, and printing it 3 times, then printing the first integer again 5 more times without reversing. Test ends with "Process finished with exit code 0" which I think is says the program finished without errors -- which of course is not correct. I assume the issue is in how the user input array is stored. I have it assigning as userNum[i] with a limited array of 5, and int i =0 to begin array storage at userNum[0], so I'm not clear on why all the inputs are not captured up to userNum[4].
Thank you for any insight you can provide. I am very new to java and this is prework for my java class.
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final int NUM_VALS = 5; // number on int user able to enter
int[] userNum = new int[NUM_VALS]; // user integers storage
int j = 0;
int i = 0;
System.out.println("Enter integer values: ");
userNum[i] = scnr.nextInt(); // capture user input int
for (j = 0; j < NUM_VALS; j++) {
System.out.print("You entered: ");
System.out.println(userNum[i]);
++j;
}
System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
for (j = NUM_VALS - 1; j >= 0; j--) {
System.out.print(userNum[i] + " ");
}
}
}
You need to work more about on for loops and study how to iterate values in for loop, the problem in your i,j variables.
Here I fix your code.
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final int NUM_VALS = 5; // number on int user able to enter
int[] userNum = new int[NUM_VALS]; // user integers storage
int j = 0;
int i = 0;
//for 5 inputs you need loop
for(;i<NUM_VALS;i++){
System.out.println("Enter integer values: ");
userNum[i] = scnr.nextInt(); // capture user input int
}
for (j = 0; j < NUM_VALS; j++) {
System.out.print("You entered: ");
System.out.println(userNum[j]);
//++j; //no need to increment as you already did in for loop
}
System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
for (j = NUM_VALS - 1; j >= 0; j--) {
System.out.print(userNum[j] + " ");// userNum[0] = your last value which you reverse
}
}
}
Here is a solution using the collections framework:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final List<Integer> numbers = new ArrayList<>();
System.out.println("Enter any number of integers. (whitespace delimited. enter a non-integer to quit.): ");
while (scnr.hasNextBigInteger()) {
final int n = scnr.nextInt();
System.out.println("Parsed: " + n);
numbers.add(n);
}
System.out.println("Done reading user input.");
System.out.println("Your input: " + numbers);
Collections.reverse(numbers);
System.out.println("Your input reversed: " + numbers);
}
}
I have provided you with a solution. This is a clean way of doing it.
nextInt() reads the next integer that the user inputs. Notice that this will throw a InputMismatchExceptionif the user does not input a integer as value.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> input = new ArrayList<Integer>();
//Simple loop that will read 5 user inputs
//and add them to the input list
for(int i = 0; i < 5; i++){
input.add(scanner.nextInt());
}
//print the 5 values
for(Integer val : input){
System.out.println(val);
}
//reverse the 5 values
Collections.reverse(input);
//print the 5 values again, but they are now reversed
for(Integer val : input){
System.out.println(val);
}
}

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.

Loop to validate user input

I am fairly new to Java and I am trying to write a small program that asks a user to enter 3 integers between 1-10, stores them in an array and then adds up the integers and tells the user the answer. I have written this so far and it works:
import java.util.Scanner;
public class Feb11a {
public static void main(String[] args) {
int[] numArr = new int[3];
int sum = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter 3 numbers in the range 1 to 10: ");
for (int i = 0; i < numArr.length; i++) {
numArr[i] = keyboard.nextInt();
}
for (int counter = 0; counter < numArr.length; counter++) {
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
}
My problem is I am also meant to validate the input as in if they enter a double, a string or a number outside the 1-10 range. I have tried a while loop but I just cannot get the program to work, below is what I have so far. If I take out the first while loop the second one works i.e. it checks if it is an integer:
import java.util.Scanner;
public class Feb11a {
public static void main(String[] args) {
int[] numArr = new int[3];
int sum = 0;
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < numArr.length; i++) {
//check if between 1 and 10
while (i > 10 || i < 1) {
System.out.println("Enter a number in the range 1 to 10: ");
//check if integer
while (!keyboard.hasNextInt()) {
System.out.println("Invalid entry, please try again ");
keyboard.next();
}
numArr[i] = keyboard.nextInt();
}
}
for (int counter = 0; counter < numArr.length; counter++) {
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
}
My question is how do I get it to check if it is an integer and if it is the range 1-10?
import java.util.Scanner;
public class NewClass {
public static void main(String[] args)
{
int[] numArr = new int[3];
int sum=0,x;
Scanner keyboard = new Scanner(System.in);
for(int i=0; i<numArr.length; i++)
{
//check if between 1 and 10
System.out.println("Enter a number in the range 1 to 10: ");
//check if integer
while (!keyboard.hasNextInt())
{
System.out.println("Invalid entry, please try again ");
keyboard.next();
}
x = keyboard.nextInt();
if(x>0 && x<=10)
numArr[i]=x;
else{
System.out.println("Retry Enter a number in the range 1 to 10:");
i--;
}
}
for (int counter=0; counter<numArr.length; counter++)
{
sum+=numArr[counter];
}
System.out.println("The sum of these numbers is "+sum);
}
}
To check simple use Integer.parseInt() and catch the NumberFormatException (together with Scanner.next()).
Once format is correct you can do an int comparison (i>0 && i<11).
I suggest you to use NumberUtils under org.apache.commons.lang.math
It has isDigits method to check whether given string contains only digits or not:
if (NumberUtils.isDigits(str) && NumberUtils.toInt(str) < 10) {
// your requirement
}
Note that toInt returns zero for big numbers!
Maybe for just this reason adding a whole library seems unnecessary but for bigger projects you will need such libraries like Apache Commons and Guava
You can wrap the System in into a BufferedReader to read whatever the user has to input, then check if its an 'int' and repeat input from user.
I have modified your code a little bit to make it work.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Feb11a {
public static void main(String[] args) throws NumberFormatException, IOException
// You may want to handle the Exceptions when calling the getInt function
{
Feb11a tester = new Feb11a();
tester.perform();
}
public void perform() throws NumberFormatException, IOException
{
int[] numArr = new int[3];
int sum = 0;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < numArr.length; i++)
{
int anInteger = -1;
do
{
// First get input from user.
System.out.println("Enter a number in the range 1 to 10: ");
anInteger = getInt(in);
} while (anInteger > 10 || anInteger < 1); // then check for repeat condition. Not between 1 and 10.
numArr[i] = anInteger; // set the number into the array.
}
for (int counter = 0; counter < numArr.length; counter++)
{
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
public int getInt(BufferedReader br) throws NumberFormatException, IOException
{
String str = br.readLine();
int toReturn = Integer.parseInt(str);
return toReturn;
}
}

Categories