How to close a while loop - java

I thought my code was correct but when I ran it, my output statements at the bottom wouldnt produce. I'm asking the keyboard to enter any number and then to end by entering -1. My while loop includes adding numbers, creating a sum, as well as giving the amount of even numbers. When I test my code I've been entering just 1,2,3,4 hoping to produce 4 total numbers. 2 even, and a sum of 10. Why isnt' my code getting to the print statements?
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter a number. Enter -1 to stop program.");
int num = sc.nextInt();
int counter = 0;
int even = 0;
int sum = 0;
while (num != -1)
{
counter += 1;
sum += num;
if (num%2 == 0)
{
even +=1;
}
}
System.out.println("You have entered "+ counter + "number(s)");
System.out.println("You have entered "+ even + "even numbers");
System.out.println("The sum for the numbers you entered is "+ sum);
}

You never get the input again so the loop runs infinitely. You need to get the value again.
while (num != -1)
{
...
num = sc.nextInt();
}

num gets set before you enter the loop.
So, when does the num change inside the while loop? It doesn't. That's why your code won't exit the loop.
I suggest moving the
num = sc.nextInt();
inside the loop.

Related

Arithmetic mean in java

Problem statement
Need to find the Arithmetic mean of numbers entered by user.
Constraints
We cannot ask user to define/share the number of "NUMBERS" user has planned to enter i.e. we cannot ask user to tell how many numbers he is going to enter.
If -1 is entered by user, the input should stop and Arithmetic mean should be displayed.
We are supposed to ask user only to enter the numbers for which Arithmetic mean is to be calculated. Like : User enters
2
4
7
10
-1
so we need to calculate arithmetic mean for 2,4,7,10 and display the result.
Code
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
do {
System.out.println("Value is :" + n);
count++;
sum = sum + n;
}while ( n != -1);
}
It goes to infinite loop and I've also tried using if/else but i didn't work. Please assist.
For the input of :
3
9
4
-7
0
2
-1
The arithmetic mean should be calculated for 3,9,4,7,0,2,29 i.e. 1.8
Try this:
Scanner sc = new Scanner(System.in);
int sum = 0;
int count = 0;
int n = 0;
do {
System.out.println("Enter next number(-1 to exit): ");
n = sc.nextInt();
System.out.println("Value is :" + n);
if(n != -1)
{
count++;
sum = sum + n;
}
}while ( n != -1);
sc.close();
System.out.println("Mean is: " + (double) sum/count);
}
You needed to move your sc.nextInt(); into the loop so that you can keep entering in values. I also added an if statement so the -1 does not get used in the mean value.
You're reading "n" as input out of the while, then n has always the first value and the loop is infinite.
You just need to keep passing ints, otherwise n is forever the first value entered.
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
do {
System.out.println("Value is :" + n);
count++;
sum = sum + n;
n = sc.nextInt();
}while ( n != -1);

What is the proper way to prevent a program from exiting after a user enters wrong input in Java?

The Task
Design and implement an application that reads an integer value and prints out the sum of all EVEN integers between 2 and its input value, inclusive. Print an error message if the input value is less than 2. Prompt accordingly.
Note: the lesson was on while loops, not other loops such as for loop etc
The Issue
I have everything working, however something about how I have written this feels wrong. I currently have a while loop while(programOn) to keep the program running. without this while loop, if the user enters a number < 2, the user is asked to try again, however if the user tries again, the program exits instead of running the new input into the program. So, I created the while loop to force the program open until the user types an acceptable input.
- something about this feels hacky and incorrect i would really appreciate some validation on my method.
public static void main(String[] args){
int inputNumber;
int sum = 0;
boolean programOn = true;
Scanner scan = new Scanner(System.in);
System.out.println("Please Type a number no smaller than 2");
inputNumber = scan.nextInt();
//include the original input to sum
sum = inputNumber;
while(programOn){
if(inputNumber < 2){
System.out.println("you need a number greater than or equal to 2, try again");
inputNumber = scan.nextInt();
sum = inputNumber;
}else{
//from the number chosen divide until you reach 0
while(inputNumber != 0){
//subtract one from the number
inputNumber = (inputNumber - 1);
if((inputNumber % 2 == 0) && (inputNumber != 0)){
System.out.println(inputNumber);
//add the input to the sum
sum += inputNumber;
}
}
System.out.println("The sum is " + sum);
programOn = false;
}
}
}
That's because the validation is done by an if condition. What you need here is a while loop that keeps asking for inputs as long as user's input is less than 2, below is the code snippet that does this:
Scanner scan = new Scanner(System.in);
System.out.println("Please Type a number no smaller than 2");
int inputNumber = scan.nextInt();
while(inputNumber < 2){
System.out.println("you need a number greater than or equal to 2, try again");
inputNumber = scan.nextInt();
}
System.out.println(inputNumber);

Printing the two highest values from user input

I have an assignment where I have to write a code which lets the user decide an amount of int values to be written in, and then decides what these values should be. There has to be atleast 2 inputs from the user. The program will then compare the values from the input and then print out the two highest values. So far I managed to print out the highest value, but I'm not sure whats wrong with the way I've done it since the output just becomes 0 if I choose to print out 2 numbers and the highest one is entered in first. And I'm also not sure how to keep track of the second highest number either. Would appreciate some help.
import java.util.Scanner;
public class ToStoersteTall{
public static void main(String[] args){
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if (reader.hasNextInt()) {
int numbers = reader.nextInt();
if (numbers >= 2) {
System.out.println("Enter value #1");
if (reader.hasNextInt()) {
int num1 = reader.nextInt();
System.out.println("Enter value #2");
if (reader.hasNextInt()) {
int num2 = reader.nextInt();
int biggest = 0;
for (int i = 3; i <= tall; i++) {
System.out.println("Enter value #" + i);
int num3 = reader.nextInt();
biggest = num1;
if(biggest < num3){
biggest = num3;
}
}
System.out.println(biggest);
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer equal or higher than 2.");
}
} else {
System.out.print("Vennligst oppgi et heltall større eller lik 2.");
}
}
}
I have an assignment where I have to write a code which lets the user decide an amount of int values to be written in, and then decides what these values should be. There has to be atleast 2 inputs from the user. The program will then compare the values from the input and then print out the two highest values. So far I managed to print out the highest value, but I'm not sure whats wrong with the way I've done it since the output just becomes 0 if I choose to print out 2 numbers and the highest one is entered in first. And I'm also not sure how to keep track of the second highest number either. Would appreciate some help.
A couple things:
good practice to close scanner (and IO-related resources in general)
reduced if-statement blocks bloat for easier readability
you specify 2 guaranteed numbers, so attempt to parse those before looping
can remove system.exit calls or replace system.exit and move bulk of code back into the larger if-else blocks as originally state in OP (but I refer back to the sake of readability)
added check for the first and second numbers input to make sure high1 is highest value, and high2 is second highest value.
keep order while looping and checking values (note: does not use array), if the number is a new high, replace high1 and move high1's value down to high2, or if the number is a second (new) high, replace high2. If values are equal, this logic is excluded and you may want to specify based on your own constraints
import java.io.IOException;
import java.util.Scanner;
public class ToStoersteTall {
public static void main(String[] args) throws IOException {
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
int n = 0;
if (reader.hasNextInt()) {
n = reader.nextInt();
} else {
System.out.println("Vennligst oppgi et heltall større eller lik 2.");
System.exit(-1); // quits execution
}
if (n < 2) {
System.out.println("Please enter an integer equal or higher than 2.");
System.exit(-2);
}
// Since guaranteed 2 numbers, parse and assign now
int high1 = 0, high2 = 0;
System.out.println("Enter value # 1");
if (reader.hasNextInt())
high1 = reader.nextInt();
System.out.println("Enter value # 2");
if (reader.hasNextInt())
high2 = reader.nextInt();
// check to see if a switch to keep correct highest order, swap values if so
if (high1 < high2) {
int t = high2;
high2 = high1;
high1 = t;
}
// loop won't execute if only 2 numbers input, but will if 3 or more specified at start
for (int i = 2; i < n; ++i) {
System.out.println("Enter value #" + (i + 1));
if (reader.hasNextInt()) {
int t = reader.nextInt();
if (t > high1) {
high2 = high1; // throw away high2 value and replace with high1
high1 = t; // replace high1 value with new highest value
} else if (t > high2) {
high2 = t;
}
} else {
System.out.println("Please enter an interger");
}
}
reader.close();
System.out.println("The two highest numbers are: " + high1 + ", " + high2);
}
}
You're already keeping track of the biggest, so why not keep track of the second biggest? Another easy way of solving this problem is to keep all the numbers in a list, sort the list by number size, and grab the two highest entries.
I tried your code and used an array to solve the problem.
import java.util.Scanner;
public class Main {
static int secondHighest(int... nums) {
int high1 = Integer.MIN_VALUE;
int high2 = Integer.MIN_VALUE;
for (int num : nums) {
if (num > high1) {
high2 = high1;
high1 = num;
} else if (num > high2) {
high2 = num;
}
}
return high2;
}
public static void main(String[] args) {
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if (reader.hasNextInt()) {
int numbers = reader.nextInt();
int[] array = new int[numbers];
if (numbers >= 2) {
System.out.println("Enter value #1");
if (reader.hasNextInt()) {
int num1 = reader.nextInt();
array[0] = num1;
System.out.println("Enter value #2");
if (reader.hasNextInt()) {
int num2 = reader.nextInt();
array[1] = num2;
int biggest = 0;
for (int i = 3; i <= numbers; i++) {
System.out.println("Enter value #" + i);
int num3 = reader.nextInt();
array[i-1] = num3;
}
System.out.println("second largest number is" + secondHighest(array));
int largest = 0;
for(int i =0;i<array.length;i++) {
if(array[i] > largest) {
largest = array[i];
}
}
System.out.println("Largest number in array is : " +largest);
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer equal or higher than 2.");
}
} else {
System.out.print("Vennligst oppgi et heltall større eller lik 2.");
}
}
}
Test
How many numbers? (minimum 2)?:
6
Enter value #1
3
Enter value #2
4
Enter value #3
5
Enter value #4
6
Enter value #5
7
Enter value #6
8
second largest number is7
Largest number in array is : 8
There is a logic error in your program. If numbers is 2, then the for loop never gets executed, and the value of biggest remains zero because it is never updated. Change your declaration of biggest to reflect the current maximum value found so far.
int biggest = num1 > num2 ? num1 : num2;
That way if the for loop never executes then biggest will be the maximum value of the first two numbers.
As for keeping track of the second highest value, you could introduce another variable secondBiggest, initialised in a similar manner to biggest, and then write logic to update this value in your for loop. However, in my opinion, it would be much easier to change your strategy to hold the entered values into an array, then when all inputs have been entered, calculate whichever values you desire from the array. This would lead to a much cleaner solution IMO.
(I have assumed that tall in the for loop is actually meant to be numbers...)
import java.util.Scanner;
public class Foo{
public static void main(String[] args){
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if(reader.hasNextInt()){
int numbers = reader.nextInt();
if(numbers >= 2){
int[] list = new int[numbers];
for(int i = 0; i < numbers; i++){
System.out.println("Enter value #" + (i + 1));
if(reader.hasNextInt())
list[i] = reader.nextInt();
}//for
int biggest = 0;
int secondBiggest = 0;
// find the values you want
for(int i = 0; i < numbers; i++){
if(list[i] > biggest){
secondBiggest = biggest;
biggest = list[i];
}//if
else if(list[i] > secondBiggest)
secondBiggest = list[i];
}//for
// print your results
System.out.println("The biggest integer is: " + biggest);
System.out.println("The second biggest integer is: " + secondBiggest);
}//if
}//if
}//main
}//class

Sequence of Integers that Returns Average at the End

Hey guys I need help with this assignment. When I run what I have it just loops forever, help would be much appreciated. Here's what my assignment is:
Write a program segment on the following page which reads a sequence of integers from the keyboard until 0 (zero) is entered. As it is entered print each integer (except for the 0 that stops the program) and at the average of the integers entered.
Each non-zero integer is printed on a separate line.
this continues until a zero is read, at which point the segment stops.
Here's what I have so far:
import java.util.Scanner;
public class List {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int boom = 0;
int sum = 0;
double average = 0;
int count = 0;
System.out.println("Enter a nonzero integer, please!");
boom = keyboard.nextInt();
while (boom != 0) {
sum += boom;
count++;
average = ((double) sum) / count;
System.out.println("The average is " + average);
}
}
}
You read the keyboard input only once. That's what you should do:
while (boom=keyboard.nextInt() != 0) {
sum += boom;
count++;
average = ((double)sum) / count;
System.out.println ("The average is " + average);
}
It will loop forever if you enter a non-zero integer at the boom=keyboard.nextInt() stage. The reason why is that boom never changes in your while block and the condition for stopping is that boom does not equal zero.
You'll need to set boom to a non-zero value outside of the loop and move your assignment to boom of the int from the keyboard inside the loop.

Java While loop skipping lines, doing them every 2 cycles instead

I'm writing a program for homework that is supposed to read in an unspecified number of 0-100 scores (maximum of 100 scores) and stop after -1 or any negative number is entered.
I've put this into a Do While loop that is set to terminate when -1 is pulled in through Scanner. The loop has a counter that keeps track of how many times the loop has been gone through, an adder that adds all the input lines together to later compute an average, and a means to send the input value to an array after it has checked to see if the number is -1.
Instead of doing this, the loop only increments the counter every 2 loops and -1 will only terminate the loop on an even cycle number, other wise it will wait until the next cycle to terminate. This completely baffles me, I have no idea why it's doing this. Could someone point out the error? Thanks in advance! This is all I have so far.
import java.util.Scanner;
public class main {
//Assignment 2, Problem 2
//Reads in an unspecified number of scores, stopping at -1. Calculates the average and
//prints out number of scores below the average.
public static void main(String[] args) {
//Declaration
int Counter = 0; //Counts how many scores are
int Total = 0; //Adds all the input together
int[] Scores = new int[100]; //Scores go here after being checked
int CurrentInput = 0; //Scanner goes here, checked for negative, then added to Scores
Scanner In = new Scanner(System.in);
do {
System.out.println("Please input test scores: ");
System.out.println("Counter = " + Counter);
CurrentInput = In.nextInt();
Scores[Counter] = CurrentInput;
Total += In.nextInt();
Counter++;
} while ( CurrentInput > 0);
for(int i = 0; i < Counter; i++) {
System.out.println(Scores[i]);
}
System.out.println("Total = " + Total);
In.close();
}
}
CurrentInput = In.nextInt();
Scores[Counter] = CurrentInput;
Total += In.nextInt();
You are calling twice In.nextInt(), i.e., you are reading two lines in each loop iteration.
CurrentInput = In.nextInt();
Scores[Counter] = CurrentInput;
Total += CurrentInput;
Use this instead.

Categories