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;
}
}
Related
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") );
For this assignment I need to take in a serious of inputs until 0 is entered which will terminate the code. After the input of each number it needs to output whether that number was prime or not. Then after inputting zero the code should stop and give some description of the numbers entered such as max, min, sum, etc.
My issue is that regardless of what number I put in, it says that every number is prime and I cannot seem to understand why. Any help would be greatly appreciated!
import java.util.Scanner;
public class Assignment4
{
public static void main (String[] args)
{
int input;
int max = 0;
int min = 100000000;
double sum = 0;
int count= 0;
double average = 0;
Scanner scan = new Scanner(System.in);
boolean isPrime;
do
{
System.out.println("Enter a postive integer. Enter 0 to quit");
input = scan.nextInt();
for (int i =2; i<= input/2; i++) //Determine if prime
{
if (input % i == 0)
isPrime = false;
else
isPrime = true;
if (isPrime = true)
System.out.println("The number " + input + " is a prime number");
else
System.out.println("The number " + input + " is not a prime number");
if (input > max)
{
max = input;
}
if (input < min)
{
min = input;
}
sum += input;
count = count + 1;
average = sum/count;
break;
}
}
while (input != 0);
System.out.println("The Max is " + max);
System.out.println("The Min is " + min);
System.out.println("The sum is " + sum);
System.out.println("The total numbers are " + count);
System.out.println("The average is " + average);
}
}
You are setting isPrime to true if i is not a divisor. If the last i you check is not a divisor, isPrime will be false even though there might have been a divisor in a previous iteration.
Solution: Remove the assignment to false and set isPrime to true before starting the for loop:
import java.util.Scanner;
public class Assignment4 {
public static void main (String[] args) {
int input;
int max = 0;
int min = 100000000;
double sum = 0;
int count= 0;
double average = 0;
Scanner scan = new Scanner(System.in);
boolean isPrime;
do
{
System.out.println("Enter a postive integer. Enter 0 to quit");
input = scan.nextInt();
isPrime = true; // I added this line
for (int i =2; i<= input/2; i++) //Determine if prime
{
if (input % i == 0) {
isPrime = false;
break;
}
//else
// isPrime = true;
}
if (isPrime)
System.out.println("The number " + input + " is a prime number");
else
System.out.println("The number " + input + " is not a prime number");
if (input > max)
{
max = input;
}
if (input < min)
{
min = input;
}
sum += input;
count = count + 1;
average = sum/count;
}
while (input != 0);
System.out.println("The Max is " + max);
System.out.println("The Min is " + min);
System.out.println("The sum is " + sum);
System.out.println("The total numbers are " + count);
System.out.println("The average is " + average);
}
}
Code untested, I am on my phone currently
Fun fact:
You just need to loop to Math.sqrt(input) (square root). To illustrate it: If input/2 is a divisor, 2 is a divisor too ;)
I can see a few problems:
1) Change:
if (input % i == 0)
isPrime = false;
else
isPrime = true;
To:
if (input % i == 0)
isPrime = false;
And insert
isPrime=true;
before the for loop.
(Because just because the current value of i is not a divisor does not make it prime).
2) Change:
if (isPrime = true)
To:
if (isPrime==true)
Or:
if (isPrime)
3) Delete break;
4) Check if isPrime is true outside the loop, after all the divisors have been checked, not in it.
5) Check values of i up to and including the square root of input, not half of it. It's quicker.
David Sherret is correct, you have an error in that if statement. It needs to change to if( isPrime ).
Also, you are printing the results of every input % i test. That output should happen after the for loop.
Right now, when testing 15, your code will print out:
The number 15 is a prime number
The number 15 is not a prime number
The number 15 is a prime number
The number 15 is not a prime number
The number 15 is a prime number
The number 15 is a prime number
This is because:
(15 % 2) equals 1
(15 % 3) equals 0
(15 % 4) equals 3
(15 % 5) equals 0
(15 % 6) equals 3
(15 % 7) equals 1
and you are printing the results for each of these tests.
Before the for loop, initialize isPrime with true and then only set it to false inside the loop if the number is not prime. Then, test isPrime after the loop and print the statement. Like this:
isPrime = true;
for (int i =2; i<= input/2; i++) //Determine if prime
{
if (input % i == 0)
isPrime = false;
if (input > max)
{
max = input;
}
if (input < min)
{
min = input;
}
sum += input;
count = count + 1;
average = sum/count;
break;
}
if (isPrime)
System.out.println("The number " + input + " is a prime number");
else
System.out.println("The number " + input + " is not a prime number");
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.
As the title stated, I am trying to find the maximum and minimum values, the amount of evens and odds numbers, and the average of all inputted numbers.
The problem. As I run my code, my odds and evens counter seem to read their opposite, odd would read an even input and even would read an odd input. As for my average, I have no clue what is wrong with it, all I know is that it would only find the average of a proper fraction.
Example of my output will be pasted at the end.
import java.util.Scanner;
public class Homework7APrinter
{
public static void main (String[] args)
{
System.out.println("Enter a sequence of integers. Any non-integer to quit");
Scanner scan = new Scanner (System.in);
int min = Integer.MAX_VALUE;
int max = 0;
int count = 0;
int sum = 0;
int oddsCounter = 0;
int evensCounter = 0;
int getInt = Integer.MIN_VALUE;
double average = 0;
boolean notnull = true;
while(scan.hasNextInt())
{
if(true)
{
if (getInt%2==1)
{
evensCounter++;
System.out.println("even: " + evensCounter);
}
else
{
oddsCounter++;
System.out.println("odd: " + oddsCounter);
}
getInt = scan.nextInt();
if(getInt < min)
{
min = getInt;
}
else if(getInt > max)
{
max = getInt;
}
}
else
{
notnull = false;
}
sum += getInt;
System.out.println("sum " +sum);
count++;
System.out.println("count " +count);
average = sum/(count);
System.out.println("average " +average);
}
System.out.println("smallest: " + min);
System.out.println("largest: " + max);
System.out.println("even: " + oddsCounter);
System.out.println("odd: " + evensCounter);
System.out.println("average: " + average);
}
}
Result:
Enter a sequence of integers. Any non-integer to quit
1 //first input
odd: 1
sum 1
count 1
average 1.0
2 //second input
even: 1
sum 3
count 2
average 1.0
3 //third input
odd: 2
sum 6
count 3
average 2.0
4 //fourth input
even: 2
sum 10
count 4
average 2.0
q //quit the scan
smallest: 1
largest: 4
even: 2
odd: 2
average: 2.0 //average of 1, 2, 3, 4 = sum/n = 10/4 = 2.5 not 2.0
Any help would be appreciated. Thank you!
(getInt%2==1) is actually a check for odd number, it should be getInt%2==0 for even check
Few things-
Move getInt = scan.nextInt(); immediately after if(true) condition
For average make it - average = (double) sum / (count);
For even/odd issue make this change - if (getInt % 2 == 0)
So here's YOUR code with some clean up-
System.out.println("Enter a sequence of integers. Any non-integer to quit");
Scanner scan = new Scanner(System.in);
int min = Integer.MAX_VALUE;
int max = 0;
int count = 0;
int sum = 0;
int oddsCounter = 0;
int evensCounter = 0;
int getInt;
double average = 0;
while (scan.hasNextInt()) {
getInt = scan.nextInt();
if (getInt % 2 == 0) {
evensCounter++;
System.out.println("even: " + evensCounter);
} else {
oddsCounter++;
System.out.println("odd: " + oddsCounter);
}
if (getInt < min) {
min = getInt;
} else if (getInt > max) {
max = getInt;
}
sum += getInt;
System.out.println("sum " + sum);
count++;
System.out.println("count " + count);
average = (double) sum / (count);
System.out.println("average " + average);
}
System.out.println("smallest: " + min);
System.out.println("largest: " + max);
System.out.println("even: " + oddsCounter);
System.out.println("odd: " + evensCounter);
System.out.println("average: " + average);
This is what youre looking for
while(scan.hasNextInt())
{
getInt = scan.nextInt();
// if(true)
// {
if (getInt%2==0)
{
evensCounter++;
System.out.println("even: " + evensCounter);
}
else
{
oddsCounter++;
System.out.println("odd: " + oddsCounter);
}
//getInt = scan.nextInt();
if(getInt < min)
{
min = getInt;
}
else if(getInt > max)
{
max = getInt;
}
// }
// else
// {
// notnull = false;
// }
sum += getInt;
System.out.println("sum " +sum);
count++;
System.out.println("count " +count);
average = (double)sum/(count);
System.out.println("average " +average);
}
There were five mistakes in your program
You were printing incorrectly ( System.out.println("even: " + oddsCounter)). Even should be printed as evencounter
You have to make the sum also a double or float, to get the average in decimal format.
You have to read the getINT before you do the odd even test.
Even/odd calculation was wrong. it should be getInt%2==0
You should not have the if/else while calculating min and max. it should be two separate if's
Full working program below.
package com.stackoverflow.test;
import java.util.Scanner;
public class Homework7APrinter {
public static void main(String[] args) {
System.out
.println("Enter a sequence of integers. Any non-integer to quit");
Scanner scan = new Scanner(System.in);
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int count = 0;
double sum = 0;
int oddsCounter = 0;
int evensCounter = 0;
int getInt = 0;
double average = 0;
while (scan.hasNextInt()) {
getInt = scan.nextInt();
if (getInt % 2 == 0) {
evensCounter++;
// System.out.println("even: " + evensCounter);
} else {
oddsCounter++;
// System.out.println("odd: " + oddsCounter);
}
if (getInt < min)
{
min = getInt;
}
if (getInt > max)
{
max = getInt;
}
sum += getInt;
// System.out.println("sum " +sum);
count++;
// System.out.println("count " +count);
average = sum / (count);
// System.out.println("average " +average);
}
System.out.println("*****************");
System.out.println("smallest: " + min);
System.out.println("largest: " + max);
System.out.println("even: " + evensCounter);
System.out.println("odd: " + oddsCounter);
System.out.println("average: " + average);
System.out.println("sum: " + sum);
System.out.println("count: " + count);
}
}
I'm new to Java and I'm trying to make a program that allows the user to input 100 numbers and if the user writes '0', then the program is suppose to print the smallest, largest, sum and all the numbers. I got all that to work but not to exit and print it all. My teacher said something about using a while loop, but how is that possible when you have a for loop?
Regards
public static void main(String[] args) {
int[] list = new int[100];
int min = 0;
int max = 0;
int sum = 0;
boolean first = true;
Scanner scan = new Scanner(System.in);
while(list[i] != 0) {
for (int i = 0; i < list.length; i++) {
System.out.print("Enter number (0 to exit) " + (1 + i) + ":");
list[i] = scan.nextInt();
}
for (int i = 0; i < list.length; i++) {
if (first == true) {
min = list[i];
first = false;
}
if (list[i] < min) {
min = list[i];
}
else if (list[i] > max) {
max = list[i];
}
sum = list[i] + sum;
}
if (list[i] == 0) {
System.out.print("Numbers are: " + list[0] + ", ");
for (int i = 1; i < list.length; i++)
System.out.print(list[i] + ", ");
System.out.println();
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + min);
System.out.println("Sum is: " + sum);
}
}
}
}
You only need one while loop to do this and additionally a for loop just to print the array if you want:
Scanner scan = new Scanner(System.in);
int i = 0;
int sum = 0;
int maxValue = Integer.MIN_VALUE;
int[] history = new int[100];
System.out.println("INPUT:");
int option = scan.nextInt();
while (option != 0 && i <= 100)
{
if (option > maxValue)
maxValue=option;
sum += option;
history[i] = option;
option = scan.nextInt();
i++;
}
System.out.println("OUTPUT: \n" + "SUM: " + sum + "\n MAX VALUE: " + maxValue);
for (int x : history)
System.out.print(x + "");
Here's the body of the method which will do what you've been asked. I have not used a while loop (but in fact, a for-loop is a kind of a while-loop internally).
int size = 100; // Set the number of numbers to input.
int[] list = new int[size]; // Create an array with 'size' elements.
int min = Integer.MAX_VALUE; // Set the highest possible integer as start value.
int max = 0; // Set the minimum to zero, assuming that the user won't input negative numbers.
int sum = 0; // Initialize the sum of the numbers in the list.
Scanner scan = new Scanner(System.in);
for (int i = 0; i < size; i++) { // Run 'size' times the process of inputting a number.
System.out.print("Enter number (0 to exit) " + (i + 1) + ": ");
int number = scan.nextInt();
if (number == 0) { // Quit program if input equals '0'
System.out.println("Exiting...");
break;
}
list[i] = number; // Add the current number to the list
sum += number; // Add the number to the total
if (number < min) { // If the number is smaller than the previous one, set this number as the smallest
min = number;
}
if (number > max) { // If the number is greater than the previous smallest number, set this number as the greatest
max = number;
}
}
// Output all numbers in the list
for (int i = 0; i < list.length; i++) {
if (list[i] != 0) {
System.out.print((i == 0 ? "" : ", ") + list[i]);
}
}
// You see the snippet (i == 0 ? "" : ", ")
// That is a shorthand if-else statement:
// If i equals 0, then "" (empty string), else ", " (comma and space).
// The statement
// System.out.print((i == 0 ? "" : ", ") + list[i])
// is the same as
// if (i == 0) {
// System.out.println("") + list[i];
// }
// else {
// System.out.println(", ") + list[i];
// }
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + max);
System.out.println("Sum is: " + sum);
You have muddled code. Better to use a pattern like this:
while (true) {
// read next
if (input == 0)
break;
}