Java Sum of numbers until string is entered - java

i've just started java programming and was wondering on how to approach or solve this problem i'm faced with.
I have to write a program that asks a user for a number and continually sums the numbers inputted and print the result.
This program stops when the user enters "END"
I just can't seem to think of a solution to this problem, any help or guidance throughout this problem would be much appreciated and would really help me understand problems like this. This is the best i could do
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.print("Enter a number: ");
int x = scan.nextInt();
System.out.print("Enter a number: ");
int y = scan.nextInt();
int sum = x + y;
System.out.println("Sum is now: " + sum);
}
}
}
The output is supposed to look like this:
Enter a number: 5
Sum is now: 5
Enter a number: 10
Sum is now: 15
Enter a number: END

One solution would be to not use the Scanner#nextInt() method at all but instead utilize the Scanner#nextLine() method and confirm the entry of the numerical entry with the String#matches() method along with a small Regular Expression (RegEx) of "\d+". This expression checks to see if the entire string contains nothing but numerical digits. If it does then the matches() method returns true otherwise it returns false.
Scanner scan = new Scanner(System.in);
int sum = 0;
String val = "";
while (val.equals("")) {
System.out.print("Enter a number (END to quit): ");
val = scan.nextLine();
// Was the word 'end' in any letter case supplied?
if (val.equalsIgnoreCase("end")) {
// Yes, so break out of loop.
break;
}
// Was a string representation of a
// integer numerical value supplied?
else if (val.matches("\\-?\\+?\\d+")) {
// Yes, convert the string to integer and sum it.
sum += Integer.parseInt(val);
System.out.println("Sum is now: " + sum); // Display Sum
}
// No, inform User of Invalid entry
else {
System.err.println("Invalid number supplied! Try again...");
}
val = ""; // Clear val to continue looping
}
// Broken out of loop with the entry of 'End"
System.out.println("Application ENDED");
EDIT: Based on Comment:
Since since an integer can be signed (ie: -20) or unsigned (ie: 20) and the fact that an Integer can be prefixed with a + (ie: +20) which is the same as unsigned 20, the code snippet above takes this into consideration.

Do it like this:
public static void main(String[] args) throws Exception {
int sum = 0;
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
System.out.print("Enter a number: ");
if (scan.hasNextInt())
sum += scan.nextInt();
else
break;
System.out.println("Sum is now: " + sum);
}
System.out.print("END");
}
This will end if the input is not a number (int).
As pointed out in the comments, if you want the program to stop when the user specifically enters "END", change the else-statement to:
else if (scanner.next().equals("END"))
break;

Related

infinite loop in a while statement

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("\nThe sum of the numbers is: " + getSumOfInput());
}
public static int getSumOfInput () {
int counter = 0;
int sumOfNums = 0;
Scanner userInput = new Scanner(System.in);
while(counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
boolean checkValidity = userInput.hasNextInt();
if(checkValidity) {
int userNum = userInput.nextInt();
userInput.nextLine();
System.out.println("Number " + userNum + " added to the total sum.");
sumOfNums += userNum;
counter++;
} else {
System.out.println("Invalid input. Please, enter a number.");
}
}
userInput.close();
return sumOfNums;
}
}
Hello everybody!
I just started java and I learned about control flow and now I moved on to user input, so I don't know much. The problem is this code. Works just fine if you enter valid input as I tested, nothing to get worried about. The problem is that I want to check for wrong input from user, for example when they enter a string like "asdew". I want to display the error from else statement and to move on back to asking the user for another input, but after such an input the program will enter in an infinite loop displaying "Enter the number X: Invalid input. Please, enter a number.".
Can you tell me what's wrong? Please, mind the fact that I have few notions when it comes to what java can offer, so your range of solutions it's a little bit limited.
Call userInput.nextLine(); just after while:
...
while(counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
userInput.nextLine();
...
The issue is, that once you enter intput, which can not be interpreted as an int, userInput.hasNextInt() will return false (as expected). But this call will not clear the input, so for every loop iteration the condition doesn't change. So you get an infinite loop.
From Scanner#hasNextInt():
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
The fix is to clear the input if you came across invalid input. For example:
} else {
System.out.println("Invalid input. Please, enter a number.");
userInput.nextLine();
}
Another approach you could take, which requires less input reads from the scanner, is to always take the next line regardless and then handle the incorrect input while parsing.
public static int getSumOfInput() {
int counter = 0;
int sumOfNums = 0;
Scanner userInput = new Scanner(System.in);
while (counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
String input = userInput.nextLine();
try {
int convertedInput = Integer.parseInt(input);
System.out.println("Number " + convertedInput + " added to the total sum.");
sumOfNums += convertedInput;
counter++;
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please, enter a number.");
}
}
return sumOfNums;
}

Include plus or minus in sum program

This is a program that asks for user input (number) and prints a sum statement. Which continually works until user enters END. It works fine, however when a negative integer is inputted, an empty print statement is returned. Any help or insight into how to include negative integers in the sum is greatly appreciated thanks for your time!
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum = 0;
String val = "";
while (val.equals(""))
{
System.out.print("Enter a number: ");
val = scan.nextLine();
if (val.equalsIgnoreCase("end")) {
break;
}
else if (val.matches("\\d+")) {
sum += Integer.parseInt(val);
System.out.println("Sum is now: " + sum);
}
else {
System.err.println("");
}
val = "";
}
}
}
This would be because \\d+ picks up one or more numbers. Whereas the - before a negative number is not considered a number so therefore it does not match your regex.
Try using something like:
-?\\d+

How can i input several integer or another types?

I want to enter several numbers for some operations. But i need to add this numbers without stopping. I mean, for example i wanna that program asks me how many integer i want to enter, after for example i yped 5 and click enter, it should give me opportunity to enter my 5 numbers (For example, 12, 34, 54, 23, 9) in the lines. Then i will use this numbers for something in my program.
i am using Scanner class for entering the number. But i wanna to enter several numbers in once input.
package frlr;
import java.util.Scanner;
public class Frlr {
public static void main(String[] args) {
System.out.println("Please enter your numbers: ");
Scanner in = new Scanner(System.in);
int myNumbers = in.nextInt();
System.out.println(myNumbers);
}
}
I need, when program asks me "Please enter your numbers:" if i enter 5 , it should be the count of the numbers which i will enter in the next steps.
You can use for loop, for loop allows you enter the amount of numbers you entered in your first scanner.
For example:
1) you scan the amount of number you want to enter
2) in for loop you use that number as an endpoint
so your for loop is gonna look like this:
for(initialization; condition(your condition is your scan) ; increment/decrement)
{
statement(s);
}
3) you statement is going to be another scan, or as you refer to it as entering several numbers
If you want to use the numbers later you can save them in an Array. First you ask the user how big the array has to be (quantity). Then you initialize an Array with the user input size. You need to watch out that the number is positive. After that you make a for loop, that has the input quantity times of iterations. After each step you save the number in the proper spot. In the end you can output the numbers.
Validation of user inputs can be done with Regular Expressions. Here is a good tutorial on RegEx: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
import java.util.Arrays;
import java.util.Scanner;
public class VariableInputs
{
private Scanner scanner;
private String input;
private boolean isInputBad;
public VariableInputs()
{
this.scanner = new Scanner(System.in);
this.isInputBad = false;
}
public void startInteraction()
{
System.out.println(
"How many Integers would you like to enter? Enter a positive number that is smaller than 100.");
int quantity;
do
{
if (isInputBad) System.out.println("Enter a valid number."); // this gets printed if the user entered a wrong input (f.e. "abc").
input = scanner.next();
isInputBad = true;
}
while (!input.matches("\\d{1,2}")); // this checks if the input contains only number 0-9. The input has to have atleast 1 and max 2 numbers.
isInputBad = false;
quantity = Integer.parseInt(input); // because of the regular expression we know for sure that the input string is a number. So we can parse it.
int[] numbers = new int[quantity]; // init array with input quantity.
System.out.println("Good job my friend. You have entered " + quantity
+ ". Go ahead and enter those numbers.");
for (int i = 0; i < quantity; i++)
{
do
{
if (isInputBad) System.out.println("Enter a valid number.");
input = scanner.next();
isInputBad = true;
}
while (!input.matches("\\d"));
numbers[i] = Integer.parseInt(input);
isInputBad = false;
}
System.out.println("Good job my friend. You have entered " + quantity
+ " numbers.");
System.out.println("The numbers are: " + Arrays.toString(numbers));
scanner.close();
}
public static void main(String[] args)
{
VariableInputs vi = new VariableInputs();
vi.startInteraction();
}
}
You can try this code and see if its useful:
import java.util.Scanner;
import java.util.Arrays;
public class ScannerIn {
public static void main(String[] args) {
System.out.print("Please enter how many numbers (between 1 and 10)? ");
Scanner in = new Scanner(System.in);
int numbersCount = in.nextInt();
System.out.println(numbersCount);
if (numbersCount <= 0 || numbersCount > 10) {
System.out.println("Numbers count must be between 1 and 10. Exit program!");
System.exit(0);
}
int [] myNumbers = new int [numbersCount];
for (int i = 0; i < numbersCount; i++) {
System.out.print("Please enter your number: ");
in = new Scanner(System.in);
myNumbers[i] = in.nextInt();
}
System.out.println("Numbers input: " + Arrays.toString(myNumbers));
}
}

How to input a lot of data until you type in an invalid number in java

User inputs numbers one by one and then once they type in an invalid number (has to be from 1-200) the program calculates the average of the numbers that were inputted.
I'm just wondering what would the code be for this. I know the one for inputting one piece of data. Example would be:
`Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();`
this is just an example, but this time I want the user to input a lot of numbers. I know I'm going to include a loop somewhere in this and I have to stop it once it contains an invalid number (using a try catch block).
* I would also like to add that once the user inputs another number it always goes to the next line.
Just use a while loop to continue taking input until a condition is met. Also keep variables to track the sum, and the total number of inputs.
I would also suggest having numberOfShoes be an int and use the nextInt() method on your Scanner (so you don't have to convert from String to int).
System.out.println("Enter your number of shoes: ");
Scanner in = new Scanner(System.in);
int numberOfShoes = 0;
int sum = 0;
int numberOfInputs = 0;
do {
numberOfShoes = in.nextInt();
if (numberOfShoes >= 1 && numberOfShoes <= 200) { // if valid input
sum += numberOfShoes;
numberOfInputs++;
}
} while (numberOfShoes >= 1 && numberOfShoes <= 200); // continue while valid
double average = (double)sum / numberOfInputs;
System.out.println("Average: " + average);
Sample:
Enter your number of shoes:
5
3
7
2
0
Average: 4.25
It added 5 + 3 + 7 + 2 to get the sum of 17. Then it divided 17 by the numberOfInputs, which is 4 to get 4.25
you are almost there.
Logic is like this,
Define array
Begin Loop
Accept the number
check if its invalid number [it is how u define a invalid number]
if invalid, Exit Loop
else put it in the array
End Loop
Add all numbers in your array
I think you need to do something like this (which #Takendarkk suggested):
import java.util.Scanner;
public class shoes {
public void main(String[] args){
int input = 0;
do{
Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();
input = Integer.parseInt(numberOfShoes);
}while((input>=0) && (input<=200));
}
}
you can use for loop like this
for(::)
{
//do your input and processing here
if(terminating condition satisified)
{
break;
}
}

How many integers, addition of integers

import java.util.Scanner;
public class InputLoop
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer to continue or a non integer to finish");
while (scan.hasNextInt())
{
System.out.println("Enter an integer to continue or a non integer to finish");
int value = scan.nextInt();
System.out.print("user: ");
}
scan.next();
{
System.out.println ("You entered");
System.out.println ();
}
}
}
Where it says 'you entered' I have to have how many Integers have been input, for example '3' and then the total of the integers added together for example '56'. I don't know how to do this, how can I implement this?
Maintain a List<Integer> and add to this list every time the user enters an integer. The number of integers added will therefore simply be list.size(). With what you're doing currently, there is no way to access the user's old inputs.
You can alternatively use variables that store the total and the count (which will work fine in this case), but in my opinion using the List approach will give you much greater flexibility if you ever decide to update/revise this code, which is something you should bear in mind as a programmer.
List<Integer> inputs = new ArrayList<Integer>();
while (scan.hasNextInt()) {
...
inputs.add(scan.nextInt());
}
...
Just keep a variable named count and a variable named sum.
And change your code in the while loop to:
int value = scan.nextInt();
sum += value;
count++;
In the end you can output both after the while loop ends.
By the way you don't need to put those curly braces { } after scan.next();
They're unrelated, and will always be executed independently of scan.next();
So just change it to:
scan.next(); //I presume you want this to clear the rest of the buffer?
System.out.println("You entered " + count + " numbers");
System.out.println("The total is " + sum);
have a count variable, declared at the beginning of main and increment it.
you can also mantain a sum variable in the same way.
while (scan.hasNextInt())
{
System.out.println("Enter an integer to continue or a non integer to finish");
int value = scan.nextInt();
count++;
sum += value;
System.out.print("user: ");
}
scan.next();
{
System.out.println ("You entered");
System.out.println (count);
}
For what you want to output, you don't need to keep a history of the user's input. All you need are a running total and a count. You also don't need the last call to scan.next() or to enclose the last println calls in a separate block.
public class InputLoop
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer to continue or a non integer to finish");
int total = 0;
int count = 0;
while (scan.hasNextInt())
{
System.out.println("Enter an integer to continue or a non integer to finish");
int value = scan.nextInt();
total += value;
++count;
System.out.print("user: ");
}
System.out.println ("You entered " + count + " values with a total of " + total);
}
}

Categories

Resources