I wrote a program that prompts the user to enter 10 grades, and it calculates the sum of the grades, the average of grades, the highest grade, smallest grade and the range between highest and smallest. And then it prints all these things using system.out.print.
My problem is that everything works EXCEPT for the highest value. Here is my code.
int x = 10;
int i = 1;
int sum = 0;
int guess = 100;
int max = 100;
while (i <= 10) {
x = Integer.parseInt(JOptionPane.showInputDialog("Enter one grade at a time."));
i++;
sum+=x;
if(x<guess){
guess = x;
}
if(x>max){
max = x;
}
}
System.out.println("The sum of your grades is " + sum);
System.out.println("The average of your grades is " + (sum/10));
System.out.println("The smallest grade is " +guess);
System.out.println("The highest grade is " +max);
System.out.println("The range of your grades is " + (max-guess));
Lets say the 10 numbers entered are 10,20,30,40,50,60,70,80,90,99 it will print saying "The highest grade is 100" but 100 wasn't entered. It always says 100. How can I fix this? Thank you!!
Set max to be 0 instead of 100:
int max = 0;
You're initially setting max to 100. Which means that at the end of the last iteration (where x is equal to 99), this condition
if(x > max)
would be false.
(Notice how 100 is greater than any of the numbers that you use in your test sample. If there was a number greater than 100 included, this wouldn't have been the case, & your code would seem to work.)
It looks like you initialized max with 100, so it will always be greater than x and not changed. Change the declaration of max to be zero and it should work.
Because in initial variable int max = 100; you put the default value as 100(maximum), so compiler checks if the value entered is less than 100, which is as default. It is no. so max variable keeps value 100 as always, unless higher input is in
Related
I am brand new to java and I have this problem that I always get 0 random numbers greater than the user value, and I should be getting a different amount of random numbers greater than the value every time I run the program
package chapterfinal;
import java.util.Scanner;
public class finalf {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
int greaterOrequal = 0;
int count = 0;
final int finalcount = 100;
System.out.println("Enter a value between 30 and 70: ");
int value = input.nextInt();
while (value > 70 || value < 30) {
System.out.println("Please try to enter a value between 30 and 70: ");
value = input.nextInt();
}
for (count = 0; count < finalcount; count++) {
int random = (int) Math.random() * 100;
if (random >= value)
greaterOrequal++;
}
System.out.println("There are " + greaterOrequal + " random numbers greater than " + value);
} }
the "while" code is to prompt the user to reenter a value between 30-70 in case the user enters something out of that range.
the "for" code is to generate 100 random numbers and analyze how many are greater than the value that the user entered.
And finally just print the result of how many randoms were greater than the value and print the value that the user entered
I know is a really simple code, I can't find what is wrong with it!
This is the result that I get:
Enter a value between 30 and 70:
80
Please try to enter a value between 30 and 70:
50
There are 0 random numbers greater than 50
And it should be something like:
Enter a value between 30 and 70:
25
Please try to enter a value between 30 and 70:
50
There are 51 random numbers greater than 50
I should get a different amount of random numbers greater than the user value every time I run the program.
I hope any of you guys can help me
Please any help is appreciated!!
int random = (int) Math.random() * 100;
That doesn't parse the way you think it does.
That will:
[A] generate a number between 0 and 1.
[B] Cast that number to an int, so, now it is always 0.
[C] then multiply that by a 100. Still 0.
In other words, that parses as ((int) Math.random()) * 100.
The simplistic fix is (int)(Math.random() * 100), but note that this is NOT the right way to get a random number between 0 and 99.
The pigeon hole principle applies: Computers aren't magical; there are X unique numbers between 0 and 1 that your program can actually produce. X is high, but not infinite. (It's somewhere around 2^53).
If X cannot be divided fully by 100 (spoiler: It can't), then there will be numbers between 0 and 100 that are picked more often than others: It is not uniform.
You're somewhat unlikely to notice (the effect will be small), but that explains why the formula, fundamentally, is broken.
The proper way to do it, is as follows:
Random r = new Random(); // do this only once.
int x = r.nextInt(100); // x can be 0, 99, or anything in between.
It's also cleaner code, in that, without formulas, it's much harder to mess up your parentheses.
I am creating a program that prints the sum of the even numbers from a range of 0 to the number that the user entered. For example, if the user entered the number 20, the program would calculate the sum of all of the even numbers between 0 and 20.
When I tested the program out with the number 10, it worked. But I tried using a different number, 35, and it was just stuck in an infinite loop. I would appreciate any and all help. The code will be posted below:
(Edit) Thanks for the feedback everyone! After talking with a friend, we realized that the solution is actually pretty simple. We were just making it complicated. Still, thanks for all of the suggestions.
//**************************************************************
// Prints the sum of the even numbers within a range of 0
// and the integer that the user enters.
//
// #me
// #version_1.0_11.7.17
//**************************************************************
import java.util.Scanner;
public class EvenNumbersSum
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int user_num = 2; // variable that stores the user's number
int sum; // stores the sum of the needed values
System.out.print("Enter an integer greater than or equal to, 2: "); // prompt user for input
user_num = input.nextInt();
// checks to see if the value entered is valid or not.
while (user_num < 2)
{
System.out.println("Invalid entry. Must enter an integer greater than or equal to, 2.\n");
System.out.print("Enter an integer greater than or equal to, 2: ");
user_num = input.nextInt();
}
// starts adding the values
for (sum = 0; sum <= user_num;)
{
if (user_num % 2 == 0) // checks if the number is even
sum+=user_num; // add the number to sum
else
continue; // I thought that I might need this, but ended up changing nothing.
}
System.out.println(); // extra line for cleanliness
System.out.printf("The sum of the even numbers between 0 and %d is %d.", user_num, sum); // prints the result
}
}
Why are you writing loop for this, there are efficient way to do it.
Sum of numbers between 1-N = (N(N+1))/2
Sum of even numbers between 1-N = (N(N+2))/4
where N = user given input number till which you would like to add even numbers
NOTE: you can add validation on input number that it’s even by (n%2 == 0) and return error if it’s not
The variable you have used in condition (i.e. sum & user_num) no one changes in case of odd number and your code stuck in never-ending loop.
You should use counter variable ( e.g. i from 1 to user_num) and use that number in the condition. Example:
// starts adding the values
sum = 0;
for (int i = 0; i <= user_num; i++)
{
if (i % 2 == 0) // checks if the number is even
sum+=i; // add the number to sum
}
Your for loop should be like this.
int total_sum = 0;
for (int sum = 0; sum <= user_num; sum++)
{
if (sum % 2 == 0) // checks if the number is even
total_sum+=sum; // add the number to total sum
else
continue; // I thought that I might need this, but ended up changing nothing.
}
// note print total sum
System.out.println(totalsum);
your initial program just kept on checking entered number is even or odd.
And the entered number to sum.
So sum was always double of the entered number is even.
If entered number is odd it would go to infinite loop as entered_num(odd) % 2 == 0 always false and execute else statement.
I've searched for answers to this specific question, but haven't been able to find anything. I need to find the maximum and minimum of the input numbers but the values I need are inside the for loop and I can't figure out how to use them outside of it.
System.out.print("How many numbers do you want to input?");
int totalNumbers = console.nextInt();
int minMax = 0;
for(int i = 1; i <= totalNumbers; i++){
System.out.print("Number " + i + ": ");
int inputNumbers = console.nextInt();
}
System.out.println();
int smallest = Math.min(minMax);
System.out.println("Smallest = " + smallest);
int largest = Math.max(minMax);
System.out.println("Largest = " + largest);
I don't need changed code just something that will get me on the right track.Thank you!
Can you notice the problem with the following loop?
for(int i = 1; i <= totalNumbers; i++){
System.out.print("Number " + i + ": ");
int inputNumbers = console.nextInt();
}
You are running the loop totalNumbers times and every time you create a new int with name inputNumbers and store the value received from console. Also where are you changing the value of minMax? Also Math.min(or max) does not take single paramtere and wont even compile.
Now you have few options:
Either store all the numbers in an array and then traverse that for min and max elements using some utility method.
Set some min and max value and run a loop to get all items and also keep track of min and max in loop.
I am not writing any solution as I want you to try it yourself.
The Math.min() and Math.max() methods, according to the oracle documentation, can only compare two values. Importing the values into an array, and then performing operations on the array, should allow you to find minimums and maximums, as well as any other data operation quite easily.
int[] numbers = new int[totalNumbers];
for (int i = 0; i < totalNumbers; i++) {
numbers[i] = console.nextInt();
}
//Other Operations
Unless I'm misreading what you want, can't you just maintain a variable on the outside of the for loop and check them?
int minMax = 0;
int smallest = 0;
int largest = 0;
for(int i = 1; i <= totalNumbers; i++){
System.out.print("Number " + i + ": ");
int inputNumbers = console.nextInt();
if(inputNumbers > largest){
largest = inputNumbers;
} else if (inputNumbers < smallest){
smallest = inputNumbers;
}
}
System.out.println();
System.out.println("Smallest = " + smallest);
System.out.println("Largest = " + largest);
This is the most direct and logical way of checking the input values and deciding whether they're the smallest or largest currently known (Edit: Unless you require the use of Math.minMax)
Pseudocode:
smallest := +∞
largest := -∞
for each number read, n:
if n > largest:
largest := n
if n < smallest:
smallest := n
print the results
Hint:
Java ints can't represent ±∞. Use Integer.MIN_VALUE and Integer.MAX_VALUE instead.
You can do it by just put if else condition inside for loop... like
take 2 variable at outside loop one for max value and other for min value store.
inside loop assign input number to min and max first time.
after that comare next number with this and reassign values.
at end of loop you will find both min and max.
I need to write a program that finds an average of all values in the array and then returns ones larger than the average.
import java.util.*;
public class AboveAverage {
public static void main(String args[]) throws Exception {
Scanner kbd = new Scanner(System.in);
int count=0, num;
int nums[] = new int[1000];
double sum = 0;
double average = 0;
System.out.println("Input +ve integers, to stop type 0");
num = kbd.nextInt();
while( num > 0 ) {
nums[count] = num;
count = count + 1;
num = kbd.nextInt();
}
int d = 0;
while ( d < 1000 ) {
sum += nums[d];
d++;
average = sum / nums[d];
}
for(int i=0; i < count ; i=i+1) {
System.out.print(nums[i] + " ");
}
System.out.println(average);
}
}
In my opinion problem is in this line
I tried the one below which gives an exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1000
at AboveAvarage.main(AboveAvarage.java:23)
average = sum / nums[d];
I also tried
average = sum / nums.length;
Which gave me the sum instead of the average.
Remember that array indices in Java go from zero? This means the allowed indices in your nums array are 0 through 999.
Now look at this loop:
int d = 0;
while ( d < 1000 ) {
sum += nums[d];
d++;
average = sum / nums[d];
}
First, it adds the current number to the sum. This is correct.
Then, it increments the number.
Then it uses the incremented number to access nums[d] to calculate the average.
Now, imagine that you are at the last round. d is 999.
First, it adds the current number to the sum.
Then it increments d. Now it is 1000.
Then it uses the incremented number to access nums[d]. But this means nums[1000]. And that's an illegal index.
So this explains why you have an ArrayIndexOutOfBoundsException. You should never use the index again after you incremented it, because the while only guaranteed that its previous value was less than 1000. If you change the value, you need to test again. This is why normally the increment step is the last in the loop.
As for your logic:
To calculate an average, you first need to know the sum. After you know the sum, you can divide by the number of items you are averaging. So you need to divide the sum by the number of items you read.
So:
You should not do a loop up to 1000. If you entered 0 after 5 numbers when you inputted the data, then there will be no values in the rest of the array (or rather, there will be zeros there).
You can calculate the sum, as another answer told you, in the first loop. No need to do that in the second loop.
You don't calculate the sum and the average in the same step. You first have to complete calculating the sum (finish the loop, be it the first or the second), and only then you can divide by the number of items (which you saved in count).
Then you have to go through another loop, that prints the numbers that are larger than the average. Your print loop prints all the numbers. You should check each number, see if it is greater than the average you calculated, and only if it is, print it.
Hint: there should really only be two loops: One that reads the numbers and calculates the count and the sum. Then you calculate the average, but that's not a repeating action, so it should not be in a loop. The second loop is for printing the numbers that are above average.
In the while loop that is gathering values, you are using count to track how many values are provided.
In the subsequent loop to calculate the average, you should only look at count items of the array:
int d = 0;
while(d<count) {
sum += nums[d];
}
average = sum/count;
Note you don't need to calculate average within the loop - do it once you've summed the values.
You don't need the other while loop, add up sum upon input. When done, just divide by count
while( num > 0 ) {
nums[count] = num;
count = count + 1;
sum += num;
num = kbd.nextInt();
}
average = sum / count;
This question already has answers here:
How do I get this code to stop input when the sum exceeds 100 and still preform the sum and average?
(2 answers)
Closed 9 years ago.
Yes, I know there are a lot of methods here. It's part of the assignment. In this code everything works as intended except that when numbers are entered that equal sum<=100, the "average" output is wrong. For example: if I put in 8,10,19 and zero to exit the output is count 3 sum 37 average 9.25.... the average should be 12.3333. Now, if i enter in 8, 10, 99 the output is count 3 sum 117 and average 39 which is correct. Why is it working for sum>100 but not sum<=100??? I don't get it. What am I missing?
public static void main(String[] args) {
//Use Main Method for gathering input
float input = 1;
// Declare variable for sum
float theSum = 0;
// Declare variable for average
float average = 0;
// Declare variable for counting the number of user inputs
int counter = 0;
/* Initialize the while loop using an input of 0 as a sentinel value
* to exit the loop*/
while (input != 0) {
if (input!=0){
counter++;
}
input = Float.parseFloat(
JOptionPane.showInputDialog(
null, "Please enter a number. Enter 0 to quit: "));
// Invoke sum method and pass input and summation to sum method
theSum = (sum(input, theSum));
if (theSum > 100)
{
JOptionPane.showMessageDialog(null, "The sum of your numbers "
+ "are greater than 100!");
break;
}
}
// Invoke display method and pass summation, average, and counter variables to it
average = (avg(theSum, counter));
display(theSum, average, counter);
}
public static float sum(float num1, float sum) {
//Add the user's input number to the sum variable
sum += num1;
//Return value of sum variable as new summation variable
return sum;
}
public static float avg(float num1, float num2) {
//Declare and initialize variable for average
//Calculate average
float average = num1 / num2;
//Return value of average variable
return average;
}
public static void display(float sum, float average, int counter) {
/* I am subtracting 1 from variable counter so as not to include the sentinel value
* of 0 that the user had to enter to exit the input loop in the overall count*/
// Display the count, sum, and average to the user
if (sum > 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter) + ", Sum = " + sum + ", Average = " + average);
}
if (sum <= 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter - 1) + ", Sum = " + sum + ", Average = " + average);
}
}
}
The reason is that you're exiting the while loop in different ways depending on the total sum. If the sum is less than 100, even when you enter the number 0 to "exit", you're still going through the loop an extra time. To be honest, the entire loop needs to be completely restructured; a do...while loop would be much easier to read and debug.
The issue is because of the way you exit the while loop as mentioned by #chrylis. So in case where the sum is <= 100 the counter is 1 larger. But when you print it you get correct result because you update the counter value here:
if (sum <= 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter - 1) + ", Sum = " + sum + ", Average = " + average);
}
As you see in your example:
"if I put in 8,10,19 and zero to exit the output is count 3 sum 37 average 9.25"
it is because the counter value is 4 (so the avg will be 37/4 = 9.25), but while displaying the result you subtract counter by 1, therefore you get the count as 3.
The do-while loop will solve the issue as the condition would be checked at the last thus the loop will exit in same manner for both <=100 and '>100`.
The do-while loop would be like this:
do{
//here goes your code
}while (input != 0);
Your counter is 1 larger than necessary. Dividing by (counter - 1) would fix it.