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) + "%");
}
}
}
Related
I have a small piece of code that continuously asks the user to input a number until it receives an input that is divisible by 10 (input % 10) and sums all inputs however it does not add the first input
import java.util.*;
class Scratch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int input, sum = 0;
System.out.print("Enter a number: ");
input = in.nextInt();
while (input % 10 != 0) {
System.out.print("Enter a number: ");
input = in.nextInt();
sum += input;
if (input % 10 == 0) {
System.out.println("The total value is: " + sum);
System.out.println("The last input was divisible by 10");
}
}
}
}
Example run
Enter a number: 15
Enter a number: 27
Enter a number: 45
Enter a number: 50
The total value is: 122
The last input was divisible by 10
The total value is 122 even though it should be 137 because it did not add the first input which is 15
You're tossing the first line away. This seems like a perfect opportunity to use a do-while instead.
Also, you can move the actual printing outside the loop.
import java.util.*;
class Scratch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
int input;
do {
System.out.print("Enter a number: ");
input = in.nextInt();
sum += input;
} while (input % 10 != 0)
System.out.println("The total value is: " + sum);
System.out.println("The last input was divisible by 10");
}
}
Note that this lays on the premise that you still want to add the last value to the sum even if it was divisible by 10.
If that's not what you want, you need to make the addition conditional as well.
import java.util.*;
class Scratch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
int input;
do {
System.out.print("Enter a number: ");
input = in.nextInt();
if (input % 10 != 0)
sum += input;
} while (input % 10 != 0)
System.out.println("The total value is: " + sum);
System.out.println("The last input was divisible by 10");
}
}
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 :)
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();
}
#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);
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);
}
}