Which part of my program is in the wrong loop? JAVA - 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 :)

Related

A Java program with a loop that allows the user to enter a series of integers, then displays the smallest and largest numbers + the average

I've got an assignment that requires me to use a loop in a program that asks the user to enter a series of integers, then displays the smallest and largest numbers AND gives an average. I'm able to write the code that allows the user to enter however many integers they like, then displays the smallest and largest number entered. What stumps me is calculating the average based on their input. Can anyone help? I'm sorry if my code is a little janky. This is my first CS course and I'm by no means an expert.
import javax.swing.JOptionPane;
import java.io.*;
public class LargestSmallest
{
public static void main(String[] args)
{
int number, largestNumber, smallestNumber, amountOfNumbers;
double sum, average;
String inputString;
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
largestNumber = number;
smallestNumber = number;
sum = 0;
for (amountOfNumbers = 1; number != -99; amountOfNumbers++)
{
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
if (number == -99)
break;
if (number > largestNumber)
largestNumber = number;
if (number < smallestNumber)
smallestNumber = number;
sum += number;
}
average = sum / amountOfNumbers;
JOptionPane.showMessageDialog(null, "The smallest number is: " + smallestNumber + ".");
JOptionPane.showMessageDialog(null, "The largest number is: " + largestNumber + ".");
JOptionPane.showMessageDialog(null, "The average off all numbers is: " + average + ".");
}
}
The problem is that you do an extra
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
at the beginning. You don't count that in a sum. That's why you get unexpected results.
The fix would be:
replace the declarations line with:
int number = 0, largestNumber, smallestNumber, amountOfNumbers;
Remove
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
That go before the loop
Replace for (amountOfNumbers = 0 with for (amountOfNumbers = 1
This is my first CS course
Then allow me to show you a different way to do your assignment.
Don't use JOptionPane to get input from the user. Use a Scanner instead.
Rather than use a for loop, use a do-while loop.
Usually you declare variables when you need to use them so no need to declare all the variables at the start of the method. However, be aware of variable scope.
(Notes after the code.)
import java.util.Scanner;
public class LargestSmallest {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int largestNumber = Integer.MIN_VALUE;
int smallestNumber = Integer.MAX_VALUE;
int number;
double sum = 0;
int amountOfNumbers = 0;
do {
System.out.print("Enter an integer, or enter -99 to stop: ");
number = stdin.nextInt();
if (number == -99) {
break;
}
if (number > largestNumber) {
largestNumber = number;
}
if (number < smallestNumber) {
smallestNumber = number;
}
sum += number;
amountOfNumbers++;
} while (number != -99);
if (amountOfNumbers > 0) {
double average = sum / amountOfNumbers;
System.out.printf("The smallest number is: %d.%n", smallestNumber);
System.out.printf("The largest number is: %d.%n", largestNumber);
System.out.printf("The average of all numbers is: %.4f.%n", average);
}
}
}
largestNumber is initialized to the smallest possible number so that it will be assigned the first entered number which must be larger than largestNumber.
Similarly, smallestNumber is initialized to the largest possible number.
If the first value entered is -99 then amountOfNumbers is zero and dividing by zero throws ArithmeticException (but maybe you haven't learned about exceptions yet). Hence, after the do-while loop, there is a check to see whether at least one number (that isn't -99) was entered.
You don't need to use printf to display the results. I'm just showing you that option.

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.

Re-running the program in the same run

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

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.

First and second largest amount

The problem is :
Write a program that prompt the user to enter 5 numbers and find the
two largest values among them. If the user enters number more than 100
or less than – 100 the program should exit.
Hint: use break.
My code is :
import java.util.*;
public class q2 {
static Scanner scan = new Scanner (System.in);
public static void main (String[] args ) {
int num;
int max=0;//define Maximum value and save it in variable max = 0;
int secondMax=0;//define the second maximum value and save it in variable secondMax = 0;
System.out.println("Please , Enter 5 numbers between 100 and -100 "); //promet user to enter 5 numbers with the condition
for (int count=0 ; count<5 ; count++) // start loop with (for)
{
num = scan.nextInt();//user will enter number it will be repeated 5 times .
if( num > 100 || num<-100) //iv the user enter a number less than -100 or geater than 100 program will quit from loop
{
System.out.println("The number you have entered is less than -100 or greater than 100 ");//telling the user what he did
break;//End the loop if the condition ( num > 100 || num<-100) is true .
}
if(num>max )//Another condition to find the maximum number
max = num;//if so , num will be saved in (max)
if (num >= secondMax && num < max)// A condition to find the second Maximum number
secondMax = num;//And it will be saved in (secondMax)
}//End loop
System.out.println("The largest value is " + max); //Print the largest number
System.out.println("The second largest value is " + secondMax );//print the second largest number .
}//End main
}//End class
This is what my code outputs:
Please , Enter 5 numbers between 100 and -100
20
30
60
20
-10
The largest value is 60
The second largest value is 20
The second largest number is incorrect - 20, not 30. What did I do wrong?
There can be two cases,
You find new max, in this case, update secondmax and set this num as max
You find new SecondMax, update only secondmax
Try this
if(num>secondMax&&num<max) // case 2
{
secondMax = num
}
else if(num>max) // case 1
{
secondMax = max;
max = num;
}
if(num>max )//Another condition to find the maximum number
secondMax = max;
max = num;//if so , num will be saved in (max)
else if (num >= secondMax)// A condition to find the second Maximum number
secondMax = num;//And it will be saved in (secondMax)
If you replace the highest number by one that is even higher, the former largest one becomes the second largest (becaus it'S still larger than the former second largest). Your code doesn't reflect that.
Everytime you change the largest nubmer, set the second largest to the old largest one.
In the condition where the max number change first save previous max than assign new max otherwise second max should be adjusted if it less than the number.
if(num>max ){//Another condition to find the maximum number
secondmax = max;
max = num;//if so , num will be saved in (max)
} else if (num > secondmax) {
secondmax = num;
}

Categories

Resources