I've created this code to get unlimited values of integers, store them, and calculate the mean. It also does it in a squared format. My problem is, I created it so that the while loop only stops when the the number 0 is entered. However, I only put it there as a substitute, as it's the only way i could test the rest of the code to ensure it all works.
What I really want to do it have the while loop continue until the user provides input that is not an integer. Ive tried everything, using hasNextint() or nextint and so forth, what can I do?
import java.io.*;
import java.util.*;
public class InputStats {
public static void main(String[] args) {
Scanner TextIO = new Scanner(System.in);
int inputNumber; // One of the integers input by the user.
int sum; // The sum of all the integers.
int count; // The number of integers that have been entered.
double mean; // The mean value of the integers, rounded to 2 decimal places.
int squarein; // Value of squared number.
int sumsquare; // The sum of the squares of all the integers.
double meansquare; // The mean value of the squares of integers, rounded to 2 decimal places.
/* Initialize the summation and counting variables. */
sum = 0;
count = 0;
sumsquare = 0;
meansquare = 0;
/* Read and process the user's input. */
System.out.println("Enter your first positive integer: ");
inputNumber = TextIO.nextInt();
while (inputNumber != 0) {
sum += inputNumber; // Add inputNumber to running sum.
squarein = inputNumber; //
sumsquare = squarein * squarein; //square inputs
count++; // Count the input by adding 1 to count.
System.out.println("Enter your next positive integer, or 0 to end: ");
inputNumber = TextIO.nextInt();
}
/* Display the result. */
if (count == 0) {
System.out.println("You didn't enter any data!");
} else {
mean = ((double)sum) / count;
meansquare = ((double)sumsquare) / count;
TextIO.nextInt();
System.out.println("Numbers entered: " + count + "\n");
System.out.println("Sum: " + sum + "\n");
System.out.println("Mean: " + mean + "\n");
System.out.println("Sum Squares: " + sumsquare + "\n");
System.out.println("Mean Square: " + meansquare + "\n");
}
} // end main()
} // end class InputStats
You should read your values in as a string and then convert them to integers with Integer.parseInt(string);
That way you can use the following function to check if they're integers
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}
Your program would then look like this:
import java.io.*;
import java.util.*;
public class InputStats {
// *** I added this to help your while loop ***
public static boolean isInteger(String s) {
// check if a string is an integer, eg "10" is 10 but "w" is not an int
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
return true;
}
public static void main(String[] args) {
Scanner TextIO = new Scanner(System.in);
// *** I added this to store the input as a string first ***
String input; // The original string inputted by the user
int inputNumber;
int sum;
int count;
double mean;
int squarein;
int sumsquare;
double meansquare;
sum = 0;
count = 0;
sumsquare = 0;
meansquare = 0;
System.out.println("Enter your first positive integer: ");
// *** I changed this to .nextLine(); to get a string ***
input = TextIO.nextLine();
// *** I made this while it's an integer so it stops when it's a string ***
while (isInteger(input)) {
inputNumber = Integer.parseInt(input);
sum += inputNumber;
squarein = inputNumber;
sumsquare = squarein * squarein;
count++;
System.out.println("Enter your next positive integer, or a non integer to end: ");
// *** I changed this to .nextLine(); to get a string ***
input = TextIO.nextLine();
}
if (count == 0) {
System.out.println("You didn't enter any data!");
}
else {
mean = ((double)sum) / count;
meansquare = ((double)sumsquare) / count;
// *** I removed this because it was no longer needed *** TextIO.nextInt();
System.out.println("Numbers entered: " + count + "\n");
System.out.println("Sum: " + sum + "\n");
System.out.println("Mean: " + mean + "\n");
System.out.println("Sum Squares: " + sumsquare + "\n");
System.out.println("Mean Square: " + meansquare + "\n");
}
} // end main()
} // end class InputStats
hasNextInt() should work
while(TextIO.hasNextInt()) {
inputNumber = TextIO.nextInt();
sum += inputNumber;
squarein = inputNumber;
sumsquare = squarein*squarein;
count++;
System.out.println("Enter your next positive integer: ");
}
Another thing, why do you call TextIO.nextInt() before your System.outs? It doesn't seem necessary and could possibly throw an error.
Use a boolean flag. Set it to false initially and when user has inputted set it to true.
boolean userInputted = false;
while (!userInputted) {
.
.
.
// if user has inputted
userInputted = true;
}
You could have the user input one line of text with numbers separated by commas and use .split(",") to separate into an array of strings, then loop through that array by the .length and apply .trim() to each string to remove trailing space, then use Integer.parseInt(strarray[i]) to convert the strings to integers. And obviously put it all in a try...catch in case the user inputs badly formatted data.
What you need is a way to tell if what the user inputs is a number or something else.
Try something like this function.
//Function to parse the input from provided scanner, and return null
//if input is not a number
public static Integer parsedInputFrom(Scanner sc){
String input= sc.next();
Integer inputNumber=null;
try{
inputNumber = Integer.parseInt(input);
} catch (NumberFormatException n){
return null;
}
return inputNumber;
}
Related
I'm working on a project which...
Allows the user to input 4 numbers that are then stored in an array for later use. I also want every time the user decided to continue the program, it creates a new array which can be compared to later to get the highest average, highest, and lowest values.
The code is not done and I know there are some things that still need some work. I just provided the whole code for reference.
I'm just looking for some direction on the arrays part.
*I believe I am supposed to be using a 2-D array but I'm confused on where to start. If I need to explain more please let me know. (I included as many comments in my code just in case.)
I tried converting the inputDigit(); method to accept a 2-D array but can't figure it out.
If this question has been answered before please redirect me to the appropriate link.
Thank you!
package littleproject;
import java.util.InputMismatchException;
import java.util.Scanner;
public class littleProject {
public static void main(String[] args) {
// Scanner designed to take user input
Scanner input = new Scanner(System.in);
// yesOrNo String keeps while loop running
String yesOrNo = "y";
while (yesOrNo.equalsIgnoreCase("y")) {
double[][] arrayStorage = inputDigit(input, "Enter a number: ");
System.out.println();
displayCurrentCycle();
System.out.println();
yesOrNo = askToContinue(input);
System.out.println();
displayAll();
System.out.println();
if (yesOrNo.equalsIgnoreCase("y") || yesOrNo.equalsIgnoreCase("n")) {
System.out.println("You have exited the program."
+ " \nThank you for your time.");
}
}
}
// This method gets doubles and stores then in a 4 spaced array
public static double[][] inputDigit(Scanner input, String prompt) {
// Creates a 4 spaced array
double array[][] = new double[arrayNum][4];
for (int counterWhole = 0; counterWhole < array.length; counterWhole++){
// For loop that stores each input by user
for (int counter = 0; counter < array.length; counter++) {
System.out.print(prompt);
// Try/catch that executes max and min restriction and catches
// a InputMismatchException while returning the array
try {
array[counter] = input.nextDouble();
if (array[counter] <= 1000){
System.out.println("Next...");
} else if (array[counter] >= -100){
System.out.println("Next...");
} else {
System.out.println("Error!\nEnter a number greater or equal to -100 and"
+ "less or equal to 1000.");
}
} catch (InputMismatchException e){
System.out.println("Error! Please enter a digit.");
counter--; // This is designed to backup the counter so the correct variable can be input into the array
input.next();
}
}
}
return array;
}
// This will display the current cycle of numbers and format all the data
// and display it appropriatly
public static void displayCurrentCycle() {
int averageValue = 23; // Filler Variables to make sure code was printing
int highestValue = 23;
int lowestValue = 23;
System.out.println(\n--------------------------------"
+ "\nAverage - " + averageValue
+ "\nHighest - " + highestValue
+ "\nLowest - " + lowestValue);
}
public static void displayAll() {
int fullAverageValue = 12; // Filler Variables to make sure code was printing
int fullHighestValue = 12;
int fullLowestValue = 12;
System.out.println(" RESULTS FOR ALL NUMBER CYCLES"
+ "\n--------------------------------"
+ "\nAverage Value - " + fullAverageValue
+ "\nHighest Value - " + fullHighestValue
+ "\nLowest Value - " + fullLowestValue);
}
// This is a basic askToContinue question for the user to decide
public static String askToContinue(Scanner input) {
boolean loop = true;
String choice;
System.out.print("Continue? (y/n): ");
do {
choice = input.next();
if (choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")) {
System.out.println();
System.out.println("Final results are listed below.");
loop = false;
} else {
System.out.print("Please type 'Y' or 'N': ");
}
} while (loop);
return choice;
}
}
As far as is understood, your program asks the user to input four digits. This process may repeat and you want to have access to all entered numbers. You're just asking how you may store these.
I would store each set of entered numbers as an array of size four.
Each of those arrays is then added to one list of arrays.
A list of arrays in contrast to a two-dimensional array provides the flexibility to dynamically add new arrays.
We store the digits that the user inputs in array of size 4:
public double[] askForFourDigits() {
double[] userInput = new double[4];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = /* ask the user for a digit*/;
}
return userInput;
}
You'll add all each of these arrays to one list of arrays:
public static void main(String[] args) {
// We will add all user inputs (repesented as array of size 4) to this list.
List<double[]> allNumbers = new ArrayList<>();
do {
double[] numbers = askForFourDigits();
allNumbers.add(numbers);
displayCurrentCycle(numbers);
displayAll(allNumbers);
} while(/* hey user, do you want to continue */);
}
You can now use the list to compute statistics for numbers entered during all cycles:
public static void displayAll(List<double[]> allNumbers) {
int maximum = 0;
for (double[] numbers : allNumbers) {
for (double number : numbers) {
maximum = Math.max(maximum, number);
}
}
System.out.println("The greatest ever entered number is " + maximum);
}
So my biggest problem is that I cannot seem to remember how to parse a string into an int so that I can idiot proof my code. My goal here is to find out if the user enters in a word instead of an int and then I can explain to them what an integer is. Can someone please help? I just need a simple list of parsing commands so that I can study them for use in the future, once there is a simple list I think I'll be able to figure all the others out from there.
import java.util.Scanner;
import java.util.*;
public class SelfTestNumberNine
{
public static void main(String[] args)
{
boolean test = false;
int num = 0;
int sum = 0;
int count = 0;
int pos = 0;
int neg = 0;
Scanner in = new Scanner(System.in);
while(!test)
{
num = 0;
System.out.print("Enter in an Integer Value: ");
String letta = in.next();
if(??parsing stuff goes here!!)
{
num = in.nextInt();
count++;
if(num > 0)
{
pos++;
sum = sum + num;
}
else if(num < 0)
{
neg++;
sum = num + sum;
}
else
{
test = true;
}
}
else
{
System.out.println("An Integer is a number that is positive or
negative,\nand does not include a decimal point.");
}
}//end while
System.out.println("Total: " + sum);
double avg = sum / count;
System.out.println("Average: " + avg);
}//end main
}//end class
Basically, the program asks the user to input integers, counts the number of positive and negatives, and prints out the total and average (Ignoring 0). The program ends when the user inputs a 0.
P.S. Thanks for your time!! ]:-)
If you want to ensure that the user has entered an int without throwing an exception if they don't you can use the hasNextInt() method:
System.out.println("Enter an int (0) to quit");
//While the user has not entered a valid int
while (!input.hasNextInt()) {
System.out.println("Please enter an integer: ");
//Consume the bad input
input.nextLine();
}
Which will loop until they enter a valid int. A sample run (- denotes user input):
Enter an int (0 to quit)
-No
Please enter an integer:
-Never!!
Please enter an integer:
-Ok ok fine
Please enter an integer:
-3
You can do this in two ways.
- Integer.parseInt()
- Integer.valueOf()
String myStr = "1";
int parsedInt = Integer.parseInt(myStr);
int valueOf = Integer.valueOf(myStr);
System.out.println("Parse Int: " + parsedInt);
System.out.println("Value Of: " + valueOf);
Note: You might get exception if the input is not parseable. NumberFormatException.
You can use a Boolean method and a try-catch to check if you can parse the string to an Integer.
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
I am a beginner and i wrote a java program that allows you to enter n numbers and it displays the max, min and average only if the number -5 is entered, my program its not displaying correctly and i need some help. I want to use try/catch to catch errors when a string is entered instead integer.
import java.util.Scanner;
public class Average{
public static void main(String[]args){
System.out.print("Enter any integer numbers or -5 to quit:");
Scanner scan =new Scanner(System.in);
double avg = 0.0;
int number = -1;
double avg = 0.0;
double sum = 0;
int count = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
try {
while((scan.nextInt())!= -5)
{
if (count != 0) {
avg = ((double) sum) / count;
count++;
}
if (number > max){
max = number;
}
if(number < min){
min = number;
}
catch (InputMismatchException e) {
System.out.println("please enter only integer numbers");
System.out.println("Average : " + avg);
System.out.println("maximum : " + max);
System.out.println("minimum : " + min);
}
}
}
}
}
To get integer inputs in a loop, respond to an "exit" value, and guard against invalid inputs, I would use something like the template below.
Note that something critical that none of the answers so far has mentioned is that it is not good enough to simply catch InputMismatchException. You must also call your scanner object's nextLine() method to clear the bad input out of its buffer. Otherwise, the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next() instead depending on the circumstance, but know that input like this has spaces will generate multiple exceptions.
Code
package inputTest;
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputTest {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter integers or -5 to quit.");
boolean done = false;
while (!done) {
System.out.print("Enter an integer: ");
try {
int n = reader.nextInt();
if (n == -5) {
done = true;
}
else {
// The input was definitely an integer and was definitely
// not the "quit" value. Do what you need to do with it.
System.out.println("\tThe number entered was: " + n);
}
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input type (must be an integer)");
reader.nextLine(); // Clear invalid input from scanner buffer.
}
}
System.out.println("Exiting...");
reader.close();
}
}
Example
Enter integers or -5 to quit.
Enter an integer: 12
The number entered was: 12
Enter an integer: -56
The number entered was: -56
Enter an integer: 4.2
Invalid input type (must be an integer)
Enter an integer: but i hate integers
Invalid input type (must be an integer)
Enter an integer: 3
The number entered was: 3
Enter an integer: -5
Exiting...
You would probably want
if(number > max) {
max = number;
}
if(number < min) {
min = number;
}
inside the while loop because right now you are only checking the last read value(also, there's no need to up the counter outisde the loop(after you have read -5, btw, why -5?o.O).
Also, you would probably want the min/max values initialised this way, because if your min value is bigger than 0, your code outputs 0. Same goes if your max value is below 0:
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
For the non-integer part: read up on exceptions and use a try-catch block to catch the InputMismatchException.
try {
//while(scan.nextInt) here
} catch (InputMismatchException e) {
//Do something here, like print something in the console
}
As someone else pointed out, if you want the average to not be truncated, cast sum to double: ((double) sum) / count.
Finally, but most important: try debugging it yourself before asking someone else.
Try this:
import java.util.Scanner;
public class Average {
static Scanner scan;
public static void main(String[] args) {
System.out.println("Enter any integer numbers or -5 to quit:");
scan = new Scanner(System.in);
int number = -1, sum = 0, count = 0;
int max = 0;
int min = 0;
while((number = scanNextInt()) != -5) {
count++;
sum = sum + number;
if(number > max) {
max = number;
}
if(number < min) {
min = number;
}
}
if(number == -5) {
try {
System.out.println("Average : " + (sum / count));
System.out.println("Maximum : " + max);
System.out.println("Minimum : " + min);
}catch(Exception e) {
//Error printing, so quit the program. Look below.
}
//Quit
System.exit(0);
}
scan.close();
}
static int scanNextInt() {
try {
return scan.nextInt();
}catch(Exception e) {
//Stop the program if the user inputs letters / symbols
System.out.println("Invalid Number.");
return -5;
}
}
}
Changes I've made:
1. I've created a method called scanNextInt() that returns scan.nextInt() if possible. If it will cause an error, it returns -5 to stop the program.
2. I've included the two if statements in the while loop so they actually work.
3. I've caught all of the possible errors, so you should not see any error messages
Note: This HAS been tested
Firstly - you need to move the closing bracket of the while loop after the min number check to allow the checks to be performed for every number you read. And remove one count++ to avoid double counting.
To ignore illegal input you could use one of the other Scanner methods and read a String instead of int, then try to Integer.parseInt the String and wrap the parsing into a try catch.
//count++;
double avg = 0.0;
if (count != 0) {
avg = ((double) sum) / count;
}
System.out.println("Average : " + avg);
When both sides of the division are int then it is an integer division (result int, remainder of division thrown away).
Hence we cast one side, here sum to floating point:
(double) sum
And then it works.
I am trying to get the sum of even numbers between 2 and a value entered by the user. I managed to get as far as printing out the even numbers but how would I get it to print just a sum of the even numbers? Rather than listing out all of the even numbers?
At the end it should look like this:
Entered value: 20
Sum of even numbers between 2 and 20: 110
import java.util.Scanner;
public class Practice_7_1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
while (true)
{
//Gather data value
System.out.println("Please enter a number: ");
int value = input.nextInt();
String text = "Sum of even numbers between 2 and " + value + " is: ";
//Loop
int i = 2;
while (i <= value)
{
if (i%2 == 0){
text = (text + i);
if (i< value)
text = (text + ", ");
else
text = (text + ". ");
}
i++;
}
//Output
System.out.println(text);
}
}
}
Edit:
Final answer:
import java.util.Scanner;
public class Practice_7_1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
while (true)
{
//Gather data value
System.out.println("Please enter a number: ");
int value = input.nextInt();
String text = "Sum of even numbers between 2 and " + value + " is: ";
//Loop
int sum = 0;
for (int i = 2; i <= value; i +=2){
sum += i;
}
//Output
System.out.print(text);
System.out.println(sum);
}
}
}
Use a for loop. With a for loop, you can customize the "step" of your internal loop variable (i). This also removes the need to check for even-ness.
int sum = 0;
for (int i = 2; i < value; i+=2) {
sum += i;
}
System.out.println(sum);
On a side note, you should probably avoid the use of while(true) because it's going to require the use of an explicit break to exit the program. You should instead use some sort of boolean control variable.
I want my program that to accept user number input and output the sum from 1 up to the input number (using while loop).
Example: If input value is 4, the sum is 10 i.e., 1 + 2 + 3 + 4.
My code compiles but returns a never ending 1 until my jcreator stops responding.
import java.util.Scanner;
import java.io.*;
public class SumLoopWhile {
public static void main(String[] args) {
int number;
int sum = 1;
Scanner in = new Scanner (System.in);
System.out.println("Enter number: ");
number = in.nextInt();
while (sum <= 10) {
System.out.println("Sum is: " + sum);
number++;
}
}
}
You should be comparing the value to the number that was input, and adding to the sum. Finally, display the result after the loop. Something like
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number: ");
int number = in.nextInt();
int sum = 0;
int v = 0;
while (v <= number) {
sum += v;
v++;
}
System.out.println("Sum is: " + sum);
}
Which will print Sum is: 10 when the input is 4 (as requested).
I guess that what you want it's to modify the sum inside your while loop. Do it like this:
while (sum <= 10) {
sum = sum + number;
number++;
}
}
System.out.println("Sum is: " + sum);
You have to put your System.out.println out of the loop because you want to print the total value, not each sum that it's calculated in each iteration.
Also, it should be nice that when you want to initialize some int that will be a "total" variable (like the result of a sum, rest or whatever), initialize it to zero.
int sum = 0;
Your output variable sum is having the same value throughout the program.it is not getting altered.the while loop becomes infinite loop
The Condition
(sum <= 10) never becomes true and the while loop will run for infinite times
import javax.swing.JOptionPane;
public class SumUsingWhileLoop {
public static void main(String[] args) {
String input;
input = JOptionPane.showInputDialog("Input the number:");
int number;
number = Integer.parseInt(input);
int sum = 0;
int i = 1;
while (i <= number) {
sum += i;
i++;
}
JOptionPane.showMessageDialog(null, "Sum = " + sum);
System.exit(0);
}
}
The System.out.println should not be placed inside the while loop, because it will get executed as many times as the loop.If you want to print the sum value only once, then the statement System.out.println must be placed outside the loop block.
Just use another variable for counting the iterations.For example
while(count<=number)
{
sum=sum+count;
count++
}
System.out.println("Sum is: "+ sum);