public class Exercise_442 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int count=0;
int positive=0;
int negative =0;
int nums=0;
int sum=0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Pleaes enter a positive or negative integer");
nums = keyboard.nextInt();
while(nums!=0){
sum+=nums;
System.out.println("Plese enter a positive or negative integer");
nums = keyboard.nextInt();
if(nums<0)
negative++;
if (nums>0)
positive++;
}
System.out.println("The sum of these numbers is " +sum);
System.out.println("The amount of negative numbers here is " + negative);
System.out.println("The amount of positive numbers here is " + positive);
}
}
I need to count the positive and negative numbers here when I enter them. It displays these when the user inputs 0. It counts the negative numbers ok and gets the sum but I don't know why it falls short of one number when it counts the positive integers?
Your first nums is ignored for +/- when you enter the while loop for the first time.
Let's say you enter 1 as nums. It'll add 1 to the sums and then ask for a new input without evaluating > or <.
Move your if statements above the nums = keyboard.nextInt(); in the while loop.
while(nums!=0){
sum+=nums;
//moved everything up before we pull nextInt
if(nums<0)
negative++;
if (nums>0)
positive++;
System.out.println("Plese enter a positive or negative integer");
nums = keyboard.nextInt();
}
Related
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.
Below is a code I have written to give me the largest and smallest integer while also finding the average of the integers entered. My problem is that it is counting the negative number when finding the average. I need it to not count the negative number. Maybe subtracting one from the count? Or an if else statement?
import java.util.Scanner;
public class LargeSmallAverage {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int smallest, largest, sum, count;
sum = 0;
count = 0;
System.out.println("Please enter a series of positive numbers. Enter a negative number to exit program.");
int positive = in.nextInt();
smallest = largest = positive;
while (positive > 0)
{
if (smallest > positive)
smallest = positive;
if (largest < positive)
largest = positive;
sum = sum + positive;
count++;
positive = in.nextInt();
}
double average = sum / count;
System.out.println("The smallest number entered was " + smallest);
System.out.println("The largest number entered was " + largest);
System.out.println("The average of all positive numbers entered is " + average);
}
}
OUTPUT:
Please enter a series of positive numbers. Enter a negative number to exit program.
2
20
10
5
10
2
-5
The smallest number entered was 2
The largest number entered was 20
The average of all positive numbers entered is 8.0
double average = ((double) sum) / count;
You used integer division 49 / 6 = 8.
I'm new to coding. Assignment is to calculate the average of all the positive numbers input and exit when a zero is input. If no positive numbers are input display a message average not possible.
The following is what I have so far. I am stuck on the part about printing out the message "cannot calculate the average" when only a zero or negative numbers are input.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
int sumOfNumbers = 0;
double averagePositive = 0;
while (true) {
System.out.println("Give a number: ");
int number = Integer.valueOf(scanner.nextLine());
if (number == 0)
break;
if (number > 0)
sumOfNumbers = number + sumOfNumbers;
if (number > 0)
numbers = numbers + 1;
if (number > 0)
averagePositive = (double)sumOfNumbers / (double)numbers;
}
System.out.println(averagePositive);
}
Try it as follows...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Give a number: ");
int num=input.nextInt();
int tot=0; //total
int count=0; // counting the positive numbers
if(num>0){
while(num!=0){
tot+=num;
count++;
System.out.print("Give a number: ");
num=input.nextInt();
if(num<0){
System.out.print("Not possible");
return;
}
}
double avg =(double)tot/n;
System.out.print("Average: "+avg);
}else{
System.out.println("Cannot calculate the average.");
}
}
I'd probably do it like this to keep it simple. Also in general, try not to cramp code together. Most formal project demand a certain degree of styling and usually spaces between operators and braces, etc... is required. In the long run it makes the code more readable and easier to maintain.
In your code there was no need to repeat the same if test for number > 0 multiple times, they could have all been bundled together. If the program was bigger and more complex I may have named the variable names with more qualification but for a short program like this, brief names were sufficient for clarity.
continue and break are important keywords to control loop behavior and can be used to increase brevity and clarity. continue goes back to the top of the loop immediately and break exits the innermost loop immediately. Dividing a double by an int yields a double so I was able to eliminate a cast. And the += operator makes it a little easier to read the line.
Also in Java and C any if() or else clause that contains one line doesn't require braces and unless a program is nested in such a way that adding the braces anyway adds to the clarity, it is often clearer to omit the braces in that case. The if statement illustrates both ways in a single statement.
import java.util.Scanner;
public class avg
{
static int count = 0;
static double sum = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("\nEnter a sequence of positive numbers (0 to calculate average):\n");
while (true) {
System.out.print("Number? ");
int n = scanner.nextInt();
if (n < 0) {
System.out.println("Negative numbers not allowed.");
continue;
} else if (n == 0)
break;
sum += (double)n;
++count;
}
System.out.println("Average of " + count + " numbers = " +
(double)(sum / count) + "\n");
System.exit(1);
}
}
Sample output:
$ java avg
Enter a sequence of positive numbers (0 to calculate average)
Number? 1
Number? 2
Number? 3
Number? 4
Number? 5
Number? -6
Negative numbers not allowed.
Number? 0
Average of 5 numbers = 3.0
Hello I am writing a program that wants me to take in a user input and return the average of the input the user has to enter (0) to stop the program. My issues come in the incriminating the user numbers, I cant seem to get it to add the numbers in the array together.
Here is the code..
public class Week2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args){
// TODO code application logic here
Scanner input = new Scanner(System.in);
int n;
int sum = 0;
System.out.println("Input some postive integers (0) to stop.");
n = input.nextInt();
while (n != 0) { // while loop
System.out.println("Please enter (0) to stop");
sum = sum + n;
n = input.nextInt();
the sum = sum + n; is the variable I want to use to add up the numbers but when I run the program and hit 0 it just says hit (0) to stop for every user imputed number.
I added a close brace and a print statement after your loop,
while (n != 0) { // while loop
System.out.println("Please enter (0) to stop");
sum = sum + n;
n = input.nextInt();
} // <-- here
System.out.printf("The sum is %d%n", sum);
And it works here.
The following code outputs the sum, average, count of positive/negative numbers, count of all numbers correctly when ran first time. Because it loops, hence, the output remains on the console prompting user to enter numbers again. At this time, only sum shows the correct output, other values doubles. Please help me in fixing the loop. Thanks!
public class Test {
public static void main(String[] args) {
long n;
int count=0;
float average;
int positive=0;
int negative =0;
Scanner in = new Scanner(System.in);
do {
System.out.print("Enter a positive or negative integers: ");
n = in.nextLong();
if (n == 0){
System.out.println("Integers you've entered is invalid. Please re-launch the Program.");
}
else
{
int sum=0;
do
{
//Find sum of the integers entered.
sum += n %10;
n /= 10;
//Count number of integers entered.
count++;
//Find average of the numbers
average = sum / count;
//Find a count of positive and negative numbers.
if(n < negative){
negative++;
}
else{
positive++;
}
} while (n != 0);
n = sum;
System.out.println("The Sum of the numbers: " + sum);
System.out.println("The Average of the numbers: " + average);
System.out.println("Positive numbers are: " + positive);
System.out.println("Negative numbers are: " + negative);
System.out.println("The count of all numbers: " +count);
}
} while(n != 0);
}
}
It would make sense that sum is the only one that outputs correctly; It's the only value you initialize every iteration of your outer loop.
the values count, positive, and negative aren't re-initialized each iteration, so when you begin the next iteration of your outer loop, they will start from wherever they printed as.
you might want to initialize them again every time you run the loop.
You never reinitialize your variables before entering in your do while loop for a second time.
So
else
{
int sum=0;
do
{
Should be
else
{
int sum=0;
count=0;
average=0.0f;
positive=0;
negative =0;
do
{