How to break a loop in Java with 'X'? [duplicate] - java

This question already has answers here:
Breaking out of an infinite loop after a user inputs a character
(4 answers)
Closed 5 months ago.
How do I break the loop in Java with a letter instead of a number? I want it to be "Press X to exit" .This is my code below.
System.out.println("Average Demo using do Loop");
System.out.println();
System.out.println("Calculates an average of all numbers: Enter 'X' when finished");
do {
System.out.print("Enter number ");
input = scnr.nextInt();
sum = sum + input;
count++;
}
while (input != 1);
avg = sum / (count - 1);
System.out.println("The average of all numbers is " + avg);
System.out.println();
System.out.println();
count = 0;
input = 0;
avg = 0;
sum = 0;
System.out.println("Average Demo using a While Loop");
System.out.println();
System.out.println("Calculates an average of all numbers: Enter 'X' when finished");
// end of do...while loop
while (input != 1)
{
System.out.print("Enter number ");
input = scnr.nextInt();
sum = sum + input;
count ++;
}
avg = sum / (count - 1);
System.out.println("The average of all numbers is " + avg);
System.out.println();
//end of while loop
for (int i = 0; i < 10; i++)
{
for (int y = 0; y <= i; y++)
{
System.out.print("*");
}
System.out.println();
//end of for loop
}

You'll have to use scanner.nextLine() to get the input as a string first, as using scanner.nextInt() for character will cause an exception.
do {
System.out.print("Enter number ");
string input = scnr.nextLine();
if(input.equals("x") || input.equals("X") ) {
break;
else {
int num = Integer.parseInt(input);
sum = sum + num;
count++;
}
} while ( ! input.toUpperCase.equals("X") );

Related

Difficulty to repeat an entire loop with string in Java

I am new to programming and I started to practice with Java. In my exercice, im asked to write a program which calculates and prints out the sum of the digits of a number. Then it prints out all the divisors of the sum number.
The problem is that after that, i need to ask the user if they want to try another number and im not able to restart the program when the person answer "yes" . Thank you and sorry for my english !
//Introduction
System.out.println("\nWelcome to our Calculation Program!\n----------------------------------------");
System.out.print("Enter a number with at most 7-digits:");
int input = mykeyboard.nextInt();
int sum = 0;
while (input > 0) {
int add = input % 10;
sum = sum + add;
input = input / 10;
}
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++) {
if (sum % counter == 0)
System.out.print(counter + " ");
}
System.out.println("\n\nDo you want to try another number?");
Scanner mykeyboard2 = new Scanner(System.in);
String choice = mykeyboard2.nextLine();
if (choice.equals("yes")) {
System.out.println("Enter a number with a most 7-digits:");
while (input > 0);
int add = input % 10;
sum = sum + add;
input = input / 10;
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++)
if (sum % counter == 0)
System.out.print(counter + " ");
} if (choice.equals("no")) {
System.out.println("Thanks and Have a Great Day!");
You just have to make it so the loop restarts
System.out.print("Enter a number with at most 7-digits:");
int input = mykeyboard.nextInt();
while(input != -1){
int sum = 0;
int add = input % 10;
sum = sum + add;
input = input / 10;
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++) {
if (sum % counter == 0)
System.out.print(counter + " ");
System.out.print("Do you want another number? If you dont type -1: ");
input = mykeyboard.nextInt();
}
The code will keep going until the user types -1
The easiest way is to implement it is using your choice variable to control a loop condition:
System.out.println("\nWelcome to our Calculation Program!\n----------------------------------------");
String choice = "yes";
while(choice.equals("yes")) {
System.out.print("Enter a number with at most 7-digits:");
int input = mykeyboard.nextInt();
int sum = 0;
while (input > 0) {
int add = input % 10;
sum = sum + add;
input = input / 10;
}
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++) {
if (sum % counter == 0)
System.out.print(counter + " ");
System.out.println("\n\nDo you want to try another number?");
Scanner mykeyboard2 = new Scanner(System.in);
choice = mykeyboard2.nextLine();
}
System.out.println("Thanks and Have a Great Day!");
while (input > 0);
This will go in an infinite loop. I think you put a ; instead of {.
Should be while (input > 0){
EDIT:
System.out.println("\nWelcome to our Calculation Program!\n----------------------------------------");
while(true){
System.out.print("Enter a number with at most 7-digits:");
int input = mykeyboard.nextInt();
int sum = 0;
while (input > 0) {
int add = input % 10;
sum = sum + add;
input = input / 10;
}
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++) {
if (sum % counter == 0)
System.out.print(counter + " ");
}
System.out.println("\n\nDo you want to try another number?");
Scanner mykeyboard2 = new Scanner(System.in);
String choice = mykeyboard2.nextLine();
if (choice.equals("no")) {
break;
}
}

asking the user to input numbers and then counting them and finding the average

I need to write a code that takes the users input of numbers and adds them, displays the amount of positives, negatives, zeroes, and the count of the amount of numbers inputted once the user enters the letter 'e'.
When i enter 'e' though, the program terminates without printing the count or average.
Also, the average doesn't work because it says i cannot divide by zero.
public static void main (String[] args){
Scanner input = new Scanner(System.in);
int negative = 0;
int positive = 0;
int zeroes = 0;
int sum = 0;
int count = 1;
int average = sum / (count - 1);
do{
System.out.print("Enter a float or 'e' to exit");
String entered = input.nextLine();
if("e".equals(entered)){
//print stuff
break;
}else{
int num;
try {
num = Integer.parseInt(entered);
} catch (NumberFormatException e) {
System.out.print(negative + positive +
zeroes + sum + (count - 1) + average);
continue; // re-do the loop
}
if(num < 0){
sum += num;
count++;
negative++;
}else if (num > 0){
sum += num;
count++;
positive++;
}else{//similar to comment above
sum += num;
count++;
zeroes++;
}
}
} while(true);
}
}
You are missing the print in "if" condition. Modify the if condition as follows
if("e".equals(entered)){
//print stuff
System.out.print(negative + positive + zeroes + sum + (count - 1) + average);
break;
}
As others people have commented, you need to consider cases like "divide by zero" and also handle input validation.

While loop even count

my problem is the following. If I input number 2, the code counts it as an odd number.
Remainder for 2 / 2 = 0 so the error doesn't make sense.
Below is the program:
import java.util.Scanner;
public class Ohjelma {
public static void main(String[] args) {
// Tänne voit kirjoittaa ohjelmakoodia. Ohjelmasi voit ajaa
// valitsemalla menusta Run->Run File tai painamalla Shift+F6
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int number = Integer.parseInt(reader.nextLine());
int sum = 0;
int many = 0;
double average = 0;
int even = 0;
int odd = 0;
while (number != -1) {
System.out.println("Type numbers: ");
sum = sum + number;
number = Integer.parseInt(reader.nextLine());
many++;
average = (double)sum / many;
if (number%2 == 0) {
even++;
} else {
odd++;
}
}
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + many);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + even);
System.out.println("Odd numbers: " + odd);
The main problem is that for the critical part of your program it largely ignores the first input, apart from adding it to the running sum. You want to recast it like this:
Scanner reader = new Scanner(System.in);
int sum = 0;
int many = 0;
double average = 0;
int even = 0;
int odd = 0;
do {
System.out.println("Type numbers: ");
number = Integer.parseInt(reader.nextLine());
if (number == -1)
break;
sum = sum + number;
many++;
average = (double)sum / many;
if (number%2 == 0) {
even++;
} else {
odd++;
}
} while (true);
This will certainly processes even and odd numbers correctly.
Your code reads the second line of input into number before it checks whether number is odd ... and -1 is odd.

Count even and odd intergers until 0 is encountered

Here is what I have to do:
"Write a segment of code that reads a sequence of integers from the keyboard until the user enters a negative number. It should then output a count of the number of even integers and the number of odd integers read (not including the final negative value in either count). Remember - 0 is an even number. For example, if the sequence is:
2
7
15
5
88
1243
104
-1
Then the output should be
Number of even integers: 3
Number of odd integers: 4
My code just keeps going even after inputting -1. I have a feeling I am missing a {somewhere or wrote the code wrong. Here is my code:
int oddCount = 0, evenCount = 0;
Scanner in = new Scanner(System.in);
while (oddCount>=0&&evenCount>=0){
System.out.print("Enter an integer: ");
int temp = in.nextInt();
if (temp>0) {
if (temp%2==0)
evenCount = evenCount + 1;
else oddCount = oddCount + 1;
while (temp>0);
System.out.println("Number of even integers: "+evenCount);
System.out.println("Number of odd integers: " +oddCount);
}
}
I think using do While loop will also prevent your isses,
int oddCount = 0;
int evenCount = 0;
Scanner in = new Scanner(System.in);
do {
System.out.print("Enter an integer: ");
int temp = in.nextInt();
if (temp > 0) {
(temp % 2==0)? evenCount++:oddCount++;
}
} while (temp > 0);
Your loop will always continue because while (oddCount>=0&&evenCount>=0) will always be true in your case. Try it like this:
int oddCount = 0, evenCount = 0;
Scanner in = new Scanner(System.in);
boolean continue = true;
while (continue){
System.out.print("Enter an integer: ");
int temp = in.nextInt();
if (temp>0) {
if (temp%2==0)
evenCount++;
else
oddCount++;
}
else {
System.out.println("Number of even integers: "+evenCount);
System.out.println("Number of odd integers: " +oddCount);
continue = false;
}
}
Your code reads just one integer, then stuck at this line: while (temp>0);
The code below solve your problem:
int oddCount = 0, evenCount = 0, temp;
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: ");
while (true) {
temp = in.nextInt();
if (temp < 0) {
break;
} else if (temp % 2 == 0) {
evenCount = evenCount + 1;
} else {
oddCount = oddCount + 1;
}
}
System.out.println("Number of even integers: " + evenCount);
System.out.println("Number of odd integers: " + oddCount);
There are a few problems here.
First, since you never decrease oddCount and evenCount, the condition oddCount>=0&&evenCount>=0 will always be true.
Second, you have an empty loop that loops endlessly, since it's condition is true and it has no body: while (temp>0);
I'd just take out the first loop, which is redundant, and use a do while loop:
int oddCount = 0;
int evenCount = 0;
Scanner in = new Scanner(System.in);
do {
System.out.print("Enter an integer: ");
int temp = in.nextInt();
if (temp > 0) {
if (temp % 2==0) {
evenCount++;
} else {
oddCount++;
}
}
} while (temp > 0);
System.out.println("Number of even integers: " + evenCount);
System.out.println("Number of odd integers: " + oddCount);
Try this..
Scanner s=new Scanner(System.in);
int evenCount=0, oddCount=0;
while(true)
{
System.out.println("Enter a number");
int n=s.nextInt();
if(n<0) break;
if(n%2==0) evenCount+=n;
else oddCount+=n;
}
System.out.println("even count "+evenCount);
System.out.println("odd count "+oddCount);

How to summarize numbers entered by user?

I am doing an assignment and have most of what i think will work down, i have to promt the user for random numbers, then display how many negatives as well as positives then sum and average, can anyone help me as i cannot get my code to display the correct amount of values for negative or positive or get it to sum. Here is what i have so far( i also added the break in the end , otherwise it went to an infinate loop)
//Random number evaluation
package chapter_4;
import java.util.Scanner;
public class Four_One {
public static void main(String[] args) {
int positive = 0;
int negative = 0;
int sum = 0;
int count = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter in a value, if 0 is entered program stops: ");
int data = input.nextInt();
while (data != 0) {
sum += data;
if (data < 0)
negative++;
else if (data > 0)
positive++;
count++;
System.out.println("The number of positives is: " + positive);
System.out.println("The number of negatives is:" + negative);
System.out.println("The total is: " + sum);
System.out.println("The average is: " + sum / data);
break; }
}
}
You are not asking for the nextInt() within the while loop - you do want to ask more than once, correct?
Your average is not an average. I suggest dividing by count instead of data.
at the end of the loop (instead of the break) add data = input.nextInt();
btw for average you should display sum/(double)count (the cast to double is there so you'll see the fraction)
This might help you.
Explanation: Using a do-while loop might be easier because it asks for input and than checks the input. Also put the input statement inside the do-While loop so it asks for multiple inputs.
public static void main(String[] args)
{
int positive = 0;
int negative = 0;
int sum = 0;
int count = 0;
Scanner input = new Scanner(System.in);
int data = 0;
do
{
System.out.print("Enter in a value, if 0 is entered program stops: ");
data = input.nextInt();
sum += data;
count ++;
if(data < 0)
negative ++;
else if(data > 0)
positive ++;
}
//Stops if the value of data is ZERO(0) and continues if it's not
while(data != 0);
System.out.println("Positive Numbers = " + positive);
System.out.println("Negative Numbers = " + negative);
System.out.println("Sum of Numbers = " + sum);
System.out.println("Total Numbers = " + count);
}
import java.util.Scanner;
public class Four_One {
public static void main(String[] args) {
int positive = 0;
int negative = 0;
int sum = 0;
int count = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter in a value, if 0 is entered program stops: ");
int data = input.nextInt();
while (data != 0) {
sum += data;
if (data < 0)
negative++;
else if (data > 0)
positive++;
count++;
data = input.nextInt();
}
System.out.println("The number of positives is: " + positive);
System.out.println("The number of negatives is:" + negative);
System.out.println("The total is: " + sum);
System.out.println("The average is: " + sum / (double)count);
}
}

Categories

Resources