Re-running the program in the same run - java

Write a program that reads integers, finds the largest of them, and counts its occurrences. Assume that the input ends with number 0. Suppose that you entered 3 5 2 5 5 5 0; the program finds that the largest is 5 and the occurrence count for 5 is 4.
Design the program such it allows the user to re-run the
program with a different inputs in the same run.
public void findLargestInteger(){
//create Scanner object
Scanner input = new Scanner(System.in);
int x;
do {
//prompt user input
System.out.print("Enter an integer, the input ends if it is 0:");
//declare variables
int n, countNeg = 0, countPos = 0;
float sum = 0;
//calculate how many positive and negative values, total, and average
while ((n = input.nextInt()) != 0) {
sum = sum + n;
if (n > 0) {
countPos++;
}
else if (n < 0) {
countNeg++;
}
}
//display results
if (countPos + countNeg == 0) {
System.out.println("No numbers are entered except 0");
System.exit(0);
}
System.out.println("The number of positives is " + countPos);
System.out.println("The number of negatives is " + countNeg);
System.out.println("The total is " + sum);
System.out.println("The average is " + (sum / (countPos + countNeg)));
}while ((x = input.nextInt()) != 0);
}
How can I get the prompt to display correctly at the end and keep it
running?
Output:
Enter an integer, the input ends if it is 0:
1 2 3 0
The number of positives is 3
The number of negatives is 0
The total is 6.0
The average is 2.0
1
Enter an integer, the input ends if it is 0:
1 2 3 0
The number of positives is 3
The number of negatives is 0
The total is 6.0
The average is 2.0
1
Enter an integer, the input ends if it is 0:
2 3 4 0
The number of positives is 3
The number of negatives is 0
The total is 9.0 The average is 3.0
1
Enter an integer, the input ends if it is 0:
2 3 4 0
The number of positives is 3
The number of negatives is 0
The total is 9.0
The average is 3.0

You could change while((x = input.nextInt()) != 0); to while(true); if you really want to keep repeating your program.
That IS an infinite loop though which is not really a good way to go.
So instead of looking for the next integer and compare with 0, maybe you should write something like
System.out.print("Do you want to quit? (y/n): ");
at the end of your loop (right before the while((x = input.nextInt()) != 0) line).
And then not check for 0 but for the y. At least then you don't have the program waiting for the user to input something without knowing what's happening.
Edit: Or you can just use a counter if you want to run it like twice or three times before it terminates ;)

Have you tried just calling your function inside a while loop?
public void findLargestInteger() {
// Your code
}
public static void main(String[] args) {
do {
findLargestInteger();
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Would you like to continue? (0/1) ");
int n = reader.nextInt();
} while(n == 1);
}

Related

While loop will not continue to ask the user for an input

I am very new to java and I need help. Basically, I have a program that asks the user to input a number. When the number is input, it takes a sum of all of the odd numbers before that number and adds them up. What I'm trying (and failing) to do is, make another loop whereby, when the user is prompted to ask for a number to sum up the odd numbers, I want to make it so that it will only continue when an odd number is entered, otherwise it will keep repeatedly asking the user until they enter an odd number. I know that using a while loop will solve this issue, but I'm not sure how to get it to work.
Here's my code:
import java.util.Scanner;
public class OddCalculator {
private static Scanner sc;
public static void main(String[] args)
{
int number, i, oddSum = 0;
sc = new Scanner(System.in);
System.out.print(" Please Enter any Number : ");
number = sc.nextInt();
while (number % 2 !=0) //HERE IS WHERE IM HAVING THE ISSUE
{
continue;
}
for(i = 1; i <= number; i++)
{
if(i % 2 != 0)
{
oddSum = oddSum + i;
}
}
System.out.println("\n The Sum of Odd Numbers upto " + number + " = " + oddSum);
}
}
Thanks in advance!
continue; as a statement scans 'upwards and outwards' for the first construct that can be continued. Things that can be continued are currently only for, while and do/while statements, so it finds while (number % 2 != 0) and will continue it.
To continue a while loop means: Jump straight back to the condition number %2 != 0, evaluate it, and then enter the loop again if it is true, or hop to the } if it is false.
So, your code checks if the number is odd. If it is, it will .. continue. So, it will.. check if the number is odd. If it is, it will check if the number is odd. If it is, it will check if the number is odd.... forever.
Presumably your intent is to ask the user again, but then you'd have to wrap the loop around more code: Start with the print, because certainly sc.nextInt() needs to be inside the loop. That does mean you won't have a number value to check, but that's what do/while loops are for: To guarantee you loop at least once (and so that you can use anything calculated in the loop as part of the condition).
You should also use the scanner inside the while loop in case the number is not odd.
while (number % 2 !=0) {
number = sc.nextInt(); // Use here as well to keep asking for a number until is odd
}
Your confusion seems to be coming from misunderstanding that continue means going back to the while loop, and break is what gets you out of the loop. Does this work for you?
System.out.println(" Please Enter any Number : ");
number = sc.nextInt();
// keep asking for a number for as long as it is even (condition is false on odd)
while (number % 2 == 0) {
System.out.println("Please enter another number: ");
number = sc.nextInt();
}
System.out.println(number + " is now odd!");
I hope this output is what you are looking for, the reason why your previous code doesn't work is that number = sc.nextInt(); is the reason why you can prompt the user for an input, so you have to loop it, furthermore, you can give a specific prompt base on what the user has inputted in the if statement, hope this helps!
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// int number, i, oddSum = 0;
int number, i, oddSum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please Enter any Number : ");
do{
number = sc.nextInt();
if(number % 2 == 0){
System.out.print("Please Enter an odd number!: ");
}
}while(number % 2 == 0);
for(i = 1; i <= number; i++)
{
if(i % 2 != 0)
{
oddSum = oddSum + i;
}
}
System.out.println("\nThe Sum of Odd Numbers up to " + number + " = " + oddSum);
}
}
Output:
Please Enter any Number : 2
Please Enter an odd number!: 2
Please Enter an odd number!: 3
The Sum of Odd Numbers up to 3 = 4

Why doesn't the scanner class recognize the other numbers?

public class Hello {
public static void main(String [] args){
int number, count = 0, sum = 0;
int Largest= 0, largestEvenNumber = 0;
Scanner console = new Scanner(System.in);
number = console.nextInt(); // read an integer entered by a user
if (number > Largest) { // Condition for computing the largest number
Largest = number;
}
if (number < 0) { // Condition for computing the number of negative integers in the sequence
count = count + 1;
}
if (number % 2 == 0) { // Condition for computing the largest even integer in the sequence
if (largestEvenNumber < number) {
largestEvenNumber = number;
}
}
if (number % 3 == 0) { // Condition for computing the sum of numbers divisible by 3
sum += number;
}
System.out.println("\nThe largest integer is " + Largest);
System.out.println("The number of negative integers in the sequence is " + count);
System.out.println("The largest even integer in the sequence is " + largestEvenNumber);
System.out.printf("The sum of numbers divisible by 3 is %d", sum);
}
}
I would like to get the expected output given below. But, the Scanner class is reading only the first number. How do I correct this without creating multiple objects?
Output:
2
-1
-5
-3
9
8
0
The largest integer is 2
The number of negative integers in the sequence is 0
The largest even integer in the sequence is 2
The sum of numbers divisible by 3 is 0
Process finished with exit code 0
expected Output:
The largest integer is 9
The number of negative integers in the sequence is 3
The largest even integer in the sequence is 8
The sum of numbers divisible by 3 is 6
Thank you!
You only call console.nextInt() once, so only one number is read. If you want to call you need to loop over calls to console.hasNext(). Since you're using System.in. E.g.:
while (console.hasNextInt()) {
number = console.nextInt();
// calculations
}
You are only reading input once. I don't see a loop in your code, so number = console.nextInt(); only runs once. What you should do is put it inside a loop, exit the loop when you have all the numbers (how you check that can be done in multiple ways), and while you're inside the loop put whatever input you receive into an array or another data structure. After you're done collecting input, do your checks over all the numbers on your data structure.
1- You must first receive the data from the user and then calculate it and generate the output. You can do this using the arrays and after finishing put your data, calculate on them.
for example :
private static final int DATA_SIZE = 5;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> data = new ArrayList<>();
// put data in array
while (data.size() == DATA_SIZE){
data.add(scanner.nextInt());
}
// calculate data from array ...
}
2- When you call a field like nextInt() Scanner class , it is done only once, then you put it in a loop to be repeated several times ...
Of course, I have other suggestions for doing this
For example, you can use the array available in the main method (with knowledge, of course)
OR
First ask the user for the amount of data you have, then take it and then calculate
OR....
If you want to type all number at once ,you should set a terminal number. when you input all you number,you shoud add the terminal number to indicate input is over.
For example:
public static void main(String [] args){
int number, count = 0, sum = 0;
int Largest= 0, largestEvenNumber = 0;
Scanner console = new Scanner(System.in);
int endNumber = -1; //set the terminal number
do {
number = console.nextInt(); // read an integer entered by a user
if (number > Largest) { // Condition for computing the largest number
Largest = number;
}
if (number < 0) { // Condition for computing the number of negative integers in the sequence
count = count + 1;
}
if (number % 2 == 0) { // Condition for computing the largest even integer in the sequence
if (largestEvenNumber < number) {
largestEvenNumber = number;
}
}
if (number % 3 == 0) { // Condition for computing the sum of numbers divisible by 3
sum += number;
}
}while (number!=endNumber);
System.out.println("\nThe largest integer is " + Largest);
System.out.println("The number of negative integers in the sequence is " + count);
System.out.println("The largest even integer in the sequence is " + largestEvenNumber);
System.out.printf("The sum of numbers divisible by 3 is %d", sum);
}
The line if code is only being executed once. Thus, the Scanner is only taking in the first in put. Use a while loop to take in multiple inputs.

Which part of my program is in the wrong loop? JAVA

The project is to create a program that takes input from the user in JOption Pane and checks if a number is prime or not. The program is supposed to loop until the user enters 0, which triggers the program to calculate max, min, sum, count, and average.
Ive completed 99% of the assignment, except the first number that I enter does not get printed out like the others but it still gets included in calculations
import javax.swing.*;
import java.util.*;
public class Assignment4 {
public static void main(String[] args) {
// Main Method
userInput();
}
public static void userInput() {
int number;
int sum;
int count; // declaring variables
int max= 0;
int min= 1;
float average;
String userNumber; // Number typed by user
sum = 0; // start at 0 for sum
count = 0; // start at 0 for counter
// prompt user to enter a positive number
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
// convert to int
number = Integer.parseInt(userNumber);
// if the number entered is positive and not 0, the loop repeats
while ( number != 0 && number > 0) {
sum += number;
// starting count and sum at 0
count++;
// repeating user input prompt unless 0 is entered
// storing values for min and max as we go
if (number > max)max=number;
if (number < min & number != 0)min=number;
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
// checking if number entered is prime or not
int i,m=0,flag=0;
m=number/2;
if(number==0||number==1){
System.out.println(number+" is not a prime number");
}else{
for(i=2;i<=m;i++){
if(number%i==0){
System.out.println(number+" is not a prime number");
flag=1;
break;
}
}
if(flag==0){ System.out.println(number+" is a prime number"); }
}
}
if ( count != 0 ) {
// as long as one number is entered, calculations are done below
// calculate average of all numbers entered
average = (float) sum / count;
// printing out the results
System.out.printf("The average is : %.3f\n", average);
System.out.println("The sum is : "+sum);
System.out.println("The count is : "+count);
System.out.println("The max is : "+max);
System.out.println("The min is : "+min);
}
}
}
i need the first entry to print like the rest, please help me find where to put in the loop
Can you explain more what you need? What input do you give it and what output do you see?
I noticed that you're adding numbers before the call to JOptionPane, is it possible that you have count larger by one than your actual count of numbers? Your indentation is terrible, you should clean it up, I'm having trouble reading the code period.
// 1 START OF LOOP
while ( number != 0 && number > 0) {
// 2 ADD NUMBER TO SUM
sum += number;
// starting count and sum at 0
count++;
// repeating user input prompt unless 0 is entered
// storing values for min and max as we go
if (number > max)max=number;
if (number < min & number != 0)min=number;
// 3 THEN GET INPUT. WHAT???
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
You have several issues in your program. The reason why the first number is never considered is that you have
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
two times in your code (before the while loop and in the while loop).
I would suggest to initialize number with Integer.MAX_VALUE: number = Integer.MAX_VALUE;
Then remove
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
before the while loop.
There is a & missing in if (number < min & number != 0)min=number;
=>
if (number < min && number != 0) {
min=number;
}
The condition in the while loop can be simplified by writing while ( number > 0) { because > 0 means != 0 too.
I would also suggest to write your code a little better for readability. Always use curly braces for conditions (if), even when you only execute one line if the condition is true.
I hope this helps. Let me know if you need more help but you should be able to solve this assignment now on your own :)

Write statements in Java reads two integers and displays even numbers between them

Write statements that can be used in a Java Program two integers and display the number of even integers that lie between them. For example, the number of even integers that lie between 12 and 5 are 4
So far below is what i have.... the program outputs all the numbers between the two integers, and not the actual number of even integers.
Can someone please help / tell me what i am doing wrong ?
import java.util.Scanner;
public class evenNumberPrinter {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the smaller integer");
int numOne = keyboard.nextInt();
System.out.println("Enter the larger integer");
int numTwo = keyboard.nextInt();
for (int i = numOne; i <= numTwo; i++) {
System.out.println(i + " ");
}
}
}
to calculate count of even numbers you don't have to use for loop, here is the formula:
static long evenCount(long a, long b) {
return ((Math.abs(a - b) + 1) >>> 1) + ((~((a & 1) | (b & 1))) & 1);
}
some clarification:
zero (0) is even number
count of even numbers obviously depends on distance between two values, lets pull some data:
0-0 - 1 number, distance 0 (0)
0-1 - 1 number, distance 1
0-2 - 2 numbers, distance 2 (0, 2)
0-3 - 2 numbers, distance 3
0-4 - 3 numbers, distance 4 (0, 2, 4)
0-5 - 3 numbers, distance 5
0-6 - 4 numbers, distance 6 (0, 2, 4, 6)
1-1 - no even, distance 0
1-2 - 1 number, distance 1 (2)
so, count of even numbers is determined by (distance+1)/2 plus one if both numbers are even
so, if we take distance Math.abs(a-b) + 1 divide it by two (>>>1) and then add 1 if and only if both numbers are even (a&1)==0
Another solution is to use pure math:
round the smaller number to the next even number (e.g. 5 to 6)
round the bigger number to the previous even number (e.g. 13 to 12)
subtract from the bigger rounded the smaller, e.g. 12-6 = 6
since even numbers are every second, divide it by 2 plus add one to count the first number of the range as well, that is 3+1=4
That is:
public static void main(final String[] args) {
final int number1=1;
final int number2=6;
int min=Math.min(number1, number2);
int max=Math.max(number1, number2);
min=min+min%2; // round up
max=max-max%2; // round down
final int evens=(max-min)/2+1; // even range plus the first number
System.out.println(evens); // Look ma, no loops
}
Edited to include explanation
Your for loop is doing nothing more than printing each number between numOne and numTwo. What you want to do is check to see if i is even or odd which can be accomplished using the modulus operator if i modulus 2 equals zero, then that number is even, and you should increment a counter variable each time this is true.
Change your for loop to something like this:
int evenCounter = 0;
for (int i = numOne; i < numTwo; i++){
if (i % 2 == 0){
System.out.print(i + " ");
evenCounter++;
}
}
System.out.println("There are " + evenCounter + " even numbers between " +
numOne + " and " + numTwo);
A little more optimal solution (if you want to print the numbers). Testing for parity (odd vs even) can be done only once, before entering the loop. Afterwards, just stay on even numbers by incrementing by 2.
int n = numOne;
int evenCount = 0;
if ((n%2)==1) { n++; }
while (n <= numTwo) {
System.out.println(n);
n += 2;
evenCount ++;
}
System.out.println( "There are " + evenCount + " even numbers between " + numOne + " and " + numTwo );
However, if your goal is only to determine how many there are (not print them), this is not optimal. A mathematical solution will be much faster.
int n = 0; //this is your counter
for (int i = numOne; i < numTwo; i++) { //use < numTwo instead of <= numTwo
//so it doesn't count numTwo as an int between your range
if (i%2 == 0) {n++;} //checks to see if number is even
// if it is, it adds one to the counter and moves on
}
System.out.println("there are " +n+ "even numbers between " +numOne+ " and " +numTwo); //prints out how many even ints were counted.

Find the even sum and even max

I am trying to find the even sum and even max from numbers inputted by the user. For example, if they answered "How many integers?" with 4 and inputted the integers: 2, 9, 18, 4 it should output:
how many integers? 4
next integer? 2
next integer? 9
next integer? 18
next integer? 4
even sum = 24
even max = 18
Here is my code:
public static void evenSum(){
//prompt the user to enter the amount of integers
Scanner console = new Scanner(System.in);
System.out.print("how many integers? ");
int numbers = console.nextInt();
//prompt user to enter the first integer
System.out.print("next integer? ");
int firstNum = console.nextInt();
//set the even max to the firstNum
int evenMax = firstNum;
//set the evenSum to zero
int evenSum = 0;
//for loop for the number of times to ask user to input numbers
for (int i = 2; i <= numbers; i++) {
System.out.print("next integer? ");
int num = console.nextInt();
//check to see if the first number is even
if (firstNum % 2 == 0){
//if it is even then add it to the evenSum
evenSum += firstNum;
}
//check to see if the numbers entered are even
if (num % 2 == 0) {
//if they are even add them to the evenSum
evenSum += num;
}
//check to see if the number entered is bigger than the first number
if (num > firstNum) {
if (num % 2 == 0 ) {
evenMax = num;
}
}
}
System.out.println("even sum = " +evenSum);
System.out.println("even max = " +evenMax);
}
But here is what is my output is:
how many integers? 4
next integer? 2
next integer? 9
next integer? 18
next integer? 4
even sum = 28
even max = 4
Could someone help me figure out what the problem is?
You were doing some really weird stuff where the first time a number was entered it was treated as special. This was causing the first even number entered (2, in this case) to be added multiple times to the total.
Put all of your input in the same loop so you can treat everything equally:
public static void evenSum(){
//prompt the user to enter the amount of integers
Scanner console = new Scanner(System.in);
System.out.print("how many integers? ");
int numbers = console.nextInt();
int evenSum = 0;
int evenMax = 0;
//for loop for the number of times to ask user to input numbers
for (int i = 0; i < numbers; i++) {
//input new number
System.out.print("next integer? ");
int num = console.nextInt();
//check to see if the number is even. if it is not even,
//we don't care about it at all and just go to the next one
if (num % 2 == 0){
//add it to the sum
evenSum += num;
//if it's larger than the maximum, set the new maximum
if (num > evenMax) {
evenMax = num;
}
}
}
System.out.println("even sum = " +evenSum);
System.out.println("even max = " +evenMax);
}
As you can see, this code also only checks to see if a number is even once. There is no need to be continuously checking if num is even every time you use it: its value is not changing during the duration of a single run of the loop.
Move the following code inside the for loop to just before the for loop-
if (firstNum % 2 == 0){
//if it is even then add it to the evenSum
evenSum += firstNum;
}
This will prevent the repeated addition of the first number in the evenSum
You also want
if (num > evenMax) {
if (num % 2 == 0 ) {
evenMax = num;
}
}
or, alternatively
if (num > evenMax && num % 2 == 0) {
evenMax = num;
}
In your scenario, firstNum is 2 so every number after it is technically larger, so you will (theoretically) not get the largest even number entered after the first number.
Either move the first if condition inside the for loop upwards (outside of the for loop)
or store all of the user inputs in a data structure i.e. Array before processing them.
Storing them in Array would make it easier to manipulate the data.
Working code:-
Scanner console = new Scanner(System.in);
int numbers =0, firstNum =0, num =0 ;
System.out.print("how many integers? ");
numbers = console.nextInt();
System.out.print("next integer? ");
firstNum = console.nextInt();
int evenMax = 0;
int evenSum = 0;
if(firstNum%2==0)
{
evenSum = firstNum;
evenMax = firstNum;
}
for (int i = 1; i < numbers; i++) {
System.out.print("next integer? ");
num = console.nextInt();
if (num % 2 == 0) {
//don't add firstNum multiple times to the evenSum, earlier it was added every time you entered an even number
evenSum += num;
//check if the number you entered, i.e. num greater than the already existing greatest number i.e. evenMax and if so update it
evenMax = num > evenMax: num?evenMax;
}
}
System.out.println("even sum = " +evenSum);
System.out.println("even max = " +evenMax);
}
Hope this helps. There are three major problems in your code:-
The firstNum(if it's even) gets added to the sum every time you enter a even number. i.e. if first number is 4 and the loop runs 10 times and encounter 6 even numbers, then along with the even number 4 also gets added six times. If you want to use it as a special number and get it's value separately then you'll have to add it to the sum before the loop.
You should compare every new even number to the previous greatest even number and hence set the value of evenMax. You are comparing them to the firstNum so if the first number is 2 and the last even number is anything greater than two, it would be set as the value of evenMax. Compare every even number to the current maximum even number i.e current value of evenMax.
You don't check if the first number is evenor not and assign it to even max. So if it is 999999 it still get's assigned, but it is not even.
Please check it as correct answer and vote up if you find it useful.

Categories

Resources