How many integers, addition of integers - java

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

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

How can I avoid my loop to take the previous answer of the user?

I am making a program that will take a user's input on how many numbers he wants and determine the highest number between the given. After that the user will be prompt with a Yes or no question. If the user decides to say yes, the program will loop again and if not, the program will end. Now my question is why does it take the highest number from the previous run?
import java.util.Scanner;
public class IT_VILLAFLOR_Lab1_Prog2
{
public static void main(String[] Args){
int num=1,num2,Largest=0,max;
char YN;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Max Number = ");
max = sc.nextInt();
for(num=1; num<=max; num++)
{
System.out.print("Enter Number " + num + ": ");
num2 = sc.nextInt();
if(Largest<num2)
{
Largest=num2;
}
else if(num==max)
{
System.out.println("The Biggest number is " + Largest );
System.out.print( "Do you want to try again? Y/N ");
YN = sc.next().charAt(0);
if(YN =='Y'|| YN =='y')
{
num=0;
System.out.print('\f');
System.out.print("Enter the Max Number " );
max = sc.nextInt();
}
else
{
System.exit(0);
}
}
}
}
}
If the user wants to continue, you are resetting num to 0. Along with this, Largest also needs to be reset to 0.
num=0;
Largest=0; //new code
By the way, you need to change the line else if(num==max) to if(num==max) . Try the test case with max of 2 and values as 12 ,23.

Java Sum of numbers until string is entered

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;

Having trouble with in.nextDouble()

I'm trying to use the in.nextDouble() method in the below program designed to compute the average of a few numbers.
import java.util.Scanner;
public class Average
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
double value;
int count = 0;
double sum = 0;
System.out.print("Enter a value, Q to quit: ");
while (in.hasNextDouble())
{
value = in.nextDouble();
sum = sum + value;
count++;
System.out.print("Enter a value, Q to quit: ");
}
double average = sum / count;
System.out.printf("Average: %.2f\n", average);
}
}
This code works although I don't understand why. When I first use while(in.hasNextDouble()) I haven't initialised in to anything so why does the loop work?
When you call in.hasNextXXX() when there is no input, the Scanner waits for input.
So, it waits for you to enter a value in the first case.
It will exit as soon as you enter something other than a double (and press enter).
The doc of Scanner#hasNext()
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
This is true for all hasNextXXX() operations.

Collecting two integers in a loop to take a weighted average (without an array)

I'm working on an assignment where I need to ask the user for console input for how many items they have, then ask them for two integers (earned and max possible) which I can then calculate the weighted average. It needs to be done with a loop, not an array for this assignment. I have figured out how to gather the number of items and one of the integers, but I don't know how to gather multiple integers within a for loop. Here's the method I have so far:
public static void homework() {
Scanner console = new Scanner(System.in);
System.out.print("Number of assignments? ");
int totalAssignments = console.nextInt();
int sum = 0;
for (int i = 1; i <= totalAssignments; i++) {
System.out.print(" #" + i + "? ");
int next = console.nextInt();
sum += next;
}
System.out.println();
System.out.println("sum = " + sum);
}
I am able to tally the sum of earned scores with this method, but not the maximum possible scores so that I can take a weighted average.
Thanks!
You need to read the user input (only) integers in a loop and sum each values(weighted and score). You could return one of the sums with something like the following:
public int returnSum() {
Scanner keyboard = new Scanner(System.in);
boolean isValid = false;
int sum1;
while (*NotAtEndOfInput or Some Condition to Signal End of Input*) {
System.out.print("Please enter score: ");
try {
num = keyboard.nextInt();
sum1+=num;
} catch (InputMismatchException ex) {
//In case user enters anything else than integer, catch
//the exception and let the program move ahead to let the user enter again.
System.out.println("Wrong input. Ony integer input will be processed.");
//discards anything which is not int
keyboard.nextLine();
}finally{
//close input stream to avoid memory leak.
keyboard.close();
}
}
return sum1;
}
You will need to read and sum the other number similarly. Hope this helps.

Categories

Resources