how to allow predefined amount of entries to java program - java

My program allows the user to enter 20 entries. each entry is entered as one entry then presses enter from command line. I would like to add the ability for the program to say
"you have 20 entries left"
then
"you have 19 entries left"
and so on... as the user enters more data in to the program.
I would appreciate if someone could show me the simplest way to add this to my current code.
import java.util.ArrayList;
import java.util.Scanner;
class project02Diaz
{
private static Double calculate_average( ArrayList<Double> myArr )
{
Double sum = 0.0;
for (Double number: myArr)
{
sum += number;
}
return sum/myArr.size();
}
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
int count = 0;
System.out.println("Enter one number at a time be averaged, you have 20 entries remaining:");
for (String inputs = scan.nextLine() ; !inputs.matches("[qQ]") ; inputs = scan.nextLine())
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
try{
myArr.add(Double.valueOf(inputs));
count++;
System.out.println("Please enter another number or press Q for your average");
}
catch (NumberFormatException e) {
System.out.println("Try again you tard! You entered more than one number, or not a valid number at all.");
continue;
}
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}
}

You again! Allright, going to do that one, too. There isn't too much that you have to change: simply count your counter down from twenty and output it's stauts every time. Also, stop if you reach 0.
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
int entriesLeft = 20; // changed counter that counts upwards to one counting down.
System.out.println("Enter one number at a time be averaged, you have 20 entries remaining:");
// added additional condition to be checked: we now also stop if maximum number of entries ie reached.
for (String inputs = scan.nextLine() ; entriesLeft > 0 && !inputs.matches("[qQ]") ; inputs = scan.nextLine())
{
try{
myArr.add(Double.valueOf(inputs));
entriesLeft--; //counting one down
System.out.println("Please enter another number or press Q for your average");
// telling user how much numbers are left
System.out.println("You have " + entriesLeft + "numbers left.");
}
catch (NumberFormatException e) {
System.out.println("Try again you tard! You entered more than one number, or not a valid number at all.");
continue;
}
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}
Note that appending the integer entriesLeft to the string isn't super efficient, the nicer way is to call Integer.toString(entriesLeft).

import java.util.ArrayList;
import java.util.Scanner;
class project02Diaz
{
private static Double calculate_average( ArrayList<Double> myArr )
{
Double sum = 0.0;
for (Double number: myArr)
{
sum += number;
}
return sum/myArr.size();
}
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
int count = 0;
System.out.println("Enter one number at a time be averaged, you have 20 entries remaining:");
for (String inputs = scan.nextLine() ; !inputs.matches("[qQ]") ; inputs = scan.nextLine())
{
System.out.println("You have "+ String.valueOf(20 - count -1) +" number of enteries left");
if (count == 19)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
try{
myArr.add(Double.valueOf(inputs));
count++;
System.out.println("Please enter another number or press Q for your average");
}
catch (NumberFormatException e) {
System.out.println("Try again you tard! You entered more than one number, or not a valid number at all.");
continue;
}
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}
}

Related

Problem with java program taking user inputs

I'm writing a java program to take a bunch of doubles the user inputs into the command line, add them together, and average them. The user can enter any amount of numbers. When they enter a negative number, the program does the adding/averaging. When i enter a number into cmd line it only lets me enter one. Can anyone help me improve this?
import java.util.Scanner;
public class Average
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Statistics Program, assignment one, program
Two. Sean Kerr");
System.out.println("\nPlease enter a series of numbers. To stop,
enter a negative number.");
//initialize two doubles and an int for our variables: the total numbers,
//the total added together, and the doubles the user enters into cmd line.
int amount = 0;
double totaladded = 0;
double userinput = 0;
userinput = keyboard.nextDouble();
while (userinput >= 0);
{
if(userinput > 0 )
{
totaladded = totaladded+userinput;
amount++;
}
}
System.out.println("Numbers entered: " + amount);
System.out.println("The average is: " + totaladded/amount);
}
}
use a do while loop instead,
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
int amount = 0;
double totaladded = 0;
double userinput = 0;
do {
System.out.println("Statistics Program, assignment one, program Two. Sean Kerr");
System.out.println("\nPlease enter a series of numbers. To stop, enter a negative number.");
//initialize two doubles and an int for our variables: the total numbers,
//the total added together, and the doubles the user enters into cmd line.
userinput = keyboard.nextDouble();
if(userinput > 0 ) {
totaladded += userinput;
amount++;
}
} while (userinput >= 0);
System.out.println("Numbers entered: " + amount);
System.out.println("The average is: " + totaladded/amount);
}

User Input Java to a list and comprehension

How do I prompt user to input numbers? I want to calculate percentage, so I want user to keep inputing integer. if the user press enter without entering anything then thats where the calculation starts
this is the example output
Input Integer:
2
17
1
3
The numbers and percentage:
2 8.7%
17 73.9%
1 4.3%
3 13.0%
23 100.0%
After the user finish inputting the numbers, I want to sum them and calculate the proportion of each number compared to the sum.
This is what I have done
package basic.functions;
import java.util.*;
import java.text.DecimalFormat;
public class Percent {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
reader.useDelimiter(System.getProperty("line.separator"));
List<Integer> list = new ArrayList<>();
System.out.println("Enter Integer: ");
do {
try {
int n = reader.nextInt();
list.add(Integer.valueOf(n));
} catch (InputMismatchException exception) {
System.out.println("Not an integer, please try again");
}
}
//When user press enter empty
while (reader.hasNextInt());
reader.close();
//SUM all the integer elements in the list
int sum = 0;
for (int x : list)
sum += x;
//calculate the percentage of each integer that was entered as proportion of the sum
//for all elements in the list, divide by the SUM then time 100 to get the percentage
System.out.println("The numbers and percentage:");
if (sum == 0) {
System.out.println("Division by 0 not possible");
}
else {
for (int x : list) {
System.out.println(x + " " + ((x * 100 / sum) + "%"));
}
System.out.println(sum + " " + ((sum * 100) / sum) + "%");
}
}
}
Assuming you already have methods for the statistic part:
you need a scanner, a list of integers, and set the delimiter of the scanner to a platform independent line.separator
List<Integer> list = new ArrayList<>();
Scanner myScanner = new Scanner(System.in);
myScanner.useDelimiter(System.getProperty("line.separator"));
System.out.println("give some int...");
while (myScanner.hasNextInt()) {
list.add(myScanner.nextInt());
}
myScanner.close();
System.out.println("now calculating");
doMath(list);
System.out.println("done");
You need to include reader.useDelimiter(System.getProperty("line.separator")); to your Scanner object as suggested in the other answer too.
In addition note that you have to close the Scanner using reader.close();
You also need List<Integer> list = new ArrayList<Integer>(); to store the integers for later processing.
Lastly, DecimalFormat df = new DecimalFormat("#.0"); is to round the output to one decimal place.
Edit:
Now that you need to catch incorrect inputs too, you no longer need reader.useDelimiter(System.getProperty("line.separator")); so I have removed this line.
Basically, you need to read the input as a String and then check to see if the user pressed enter (giving an isEmpty() String) or entered invalid input (caught by NumberFormatException).
Here is the code that does this:
package basic.functions;
import java.util.*;
import java.io.IOException;
import java.text.DecimalFormat;
public class Percent {
public static void main(String[] args) throws IOException {
Scanner reader = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
System.out.println("Enter Integer: ");
while(reader.hasNextLine())
{
String input = reader.nextLine();
if(input.isEmpty())
{
//When user press enter empty
break;
}
else
{
try
{
list.add(Integer.valueOf(input));
}
catch (NumberFormatException exception)
{
System.out.println("Not an integer, please try again");
}
}
}
reader.close();
//SUM all the integer elements in the list
int sum = 0;
for (int x : list)
sum += x;
//calculate the percentage of each integer that was entered as proportion of the sum
//for all elements in the list, divide by the SUM then time 100 to get the percentage
System.out.println("The numbers and percentage:");
if (sum == 0) {
System.out.println("Division by 0 not possible");
}
else {
for (int x : list) {
System.out.println(x + " " + ((x * 100 / sum) + "%"));
}
System.out.println(sum + " " + ((sum * 100) / sum) + "%");
}
}
}

Java program will not recognize sentinel value

My program accept input data from a user (up to 20 values) and calculate the average/find the distance from the average. If the user enters "9999" when no numbers have been added yet it will display an error message and tell the user to re-enter a value. Otherwise entering "9999" will collect what the user has entered and do its calculations. My program will have to collect all 20 inputs from the user and also ignore when the value "9999" is entered completely but, it will do the other calculations correctly. I'm not sure why its not recognizing my sentinel value whatsoever.
package labpack;
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers = new double[20];
double sum = 0;
int sentValue = 9999;
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the numbers you want up to 20");
do {
for (i = 0; i < numbers.length; i++) {
if (numbers[0] == sentValue){
System.out.println("Error: Please enter a number");
break;
}
else {
numbers[i] = input.nextDouble();
sum += numbers[i];
}
}
while (i<numbers.length && numbers[i]!=sentValue); //part of do-while loop
//calculate average and distance from average
double average = (sum / i);
System.out.println("This is your average:" + average);
for (i = 0; i < numbers.length; i++) { //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}
}
}
You can do this without doing the do-while and doing while instead.
if (numbers[0]== sentValue){
System.out.println("Error: Please enter a number");
break;
Here you are trying to compare the value without initializing the array with the user input.
This can be done in a much simple way :
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers =new double[10];
double sum =0;
double sentValue=9999;
int count = 0;
System.out.println(numbers.length);
System.out.print("Enter the numbers you want up to 20");
Scanner input = new Scanner(System.in);
while (i<numbers.length){
double temp = input.nextDouble();
if (temp >= sentValue){
if(i==0){
System.out.println("Error Message Here");
} else {
break;
}
}//if
else {
numbers[i] = temp;
sum += numbers[i];
i++;
count++;
}
} //part of while loop*/
//calculate average and distance from average
double average=(sum/i);
System.out.println("This is your average:" + average);
for (i=0;i < count;i++){ //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}//for loop
}//main bracket
}//class lab4 bracket
You need to store the value of the input.nextDouble() into a variable because when the compiler reads input.nextDouble(), each time it will ask the user for an input.
PS. You dont need to re-initialize this part :
java.util.Scanner input = new java.util.Scanner(System.in);
The above line can simply be written as :
Scanner input = new Scanner(System.in);
because you already imported Scanner.
import java.util.Scanner;
Hope this helps :)

How to fix user input error when a non number is entered in .nextDouble?

So I am taking Java as part of math degree requirements and have stumbled on a problem with this code. Essentially the code is supposed to take in numbers from the user until they type a zero. It works fine as long as only numbers are entered. However if the user enters a letter or symbol the program gets an exception. Is there a simple way I can validate user input as a number without getting an exception?
import java.util.Scanner;
public class SamsAdder
{
public static void main(String[] args)
{
double userInput = 1;
double sum = 0;
Scanner in = new Scanner (System.in);
while(userInput != 0)
{
System.out.println("Enter a number. (0 to quit):");
userInput = in.nextDouble();
sum = sum + userInput;
}
System.out.println("The sum of the numbers is " + sum + ".");
}
}
So I've tried the try/catch as you showed it. I'm still getting an exception with non numbers though. Entered the code as follows:
while(userInput != 0)
{
System.out.println("Enter a number. (0 to quit):");
try{
userInput = in.nextDouble();
}
catch(NumberFormatException nfe){
System.out.println("Invalid Number");
}
sum = sum + userInput;
}
import java.util.InputMismatchException;
import java.util.Scanner;
public class SamsAdder {
public static void main(String[] args) {
double userInput = 1;
double sum = 0;
Scanner in = new Scanner(System.in);
while (userInput != 0) {
try {
System.out.println("Enter a number. (0 to quit):");
userInput = in.nextDouble();
sum = sum + userInput;
} catch (InputMismatchException nfe) {
System.out.println("Invalid Number");
in.next();
}
}
in.close();
System.out.println("The sum of the numbers is " + sum + ".");
}
}

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

Categories