How to stop while loop from accounting for negative number? - java

For class I am writing a program that accepts a stream of positive integers. The program will stop accounting for numbers and compute the average once a negative number is entered into the console.
My issue is, I keep writing while loops that account for the negative entered. How do I stop this? I have tried the following
do{
if (number < 0){
break;
} else if ( number >= 0) {
number = input.nextDouble();
DivideBy++;
sum+=number;
}
}while (number >= 0);
When entering 1.1, 1.9, 3, and -1, the program prints 1.25, when the correct answer is 2.
Here is another example of what I have tried:
do {
number = input.nextDouble();
DivideBy++;
sum+=number;
}while (number >= 0);
Any help is appreciated.

Try this:
Scanner input = new Scanner(System.in);
double number = 0;
double sum = 0;
int divideBy = 0;
double avg = 0;
while(number >= 0) {
System.out.println("Enter number: ");
number = input.nextDouble();
if(number < 0){
break;
}
sum+=number;
divideBy++;
avg = sum/divideBy;
}
System.out.println(avg);
Your if statement should come after the number has been read from the keyboard :]

Try this out, it worked for me:
while(number >= 0){
total = number + total;
} //Your average logic here//

What you are doing now is checking whether the number is negative after you incremented DivideBy and added the number to the sum.
You can easily fix this by undoing what you did after a negative number.
// outside the loop:
sum -= number;
DivideBy--;
Then you will get the correct result.
Or, you can do it like this - check negative first, then add it to sum.
Scanner s = new Scanner(System.in);
int num = s.nextInt();
int count = 0;
int sum = 0;
while (num > 0) {
sum += num;
count++;
num = s.nextInt();
}
System.out.println(sum / count);

Read the number before the if condition. Try this.
do {
number = input.nextDouble();
if (number < 0) {
break;
} else if (number >= 0) {
DivideBy++;
sum += number;
}
} while (number >= 0);

Related

Basic Java, Largest and smallest integer

The purpose for the code is to prompt the user for 10 integers and then display the largest and smallest integer. I was able to ask the user for the 10 integers and display the largest number; however, the smallest number isn't shown. I believe the issue is with me setting smallest to 0.
import java.util.Scanner;
public class LargeSmall {
public static void main(String[] args) {
int counter = 1;
int largest = 0;
int smallest = 0;
int number = 0;
Scanner input= new Scanner(System.in);
while (counter <= 10) {
System.out.print("Enter number: ");
number = input.nextInt();
if (number > largest) {
largest = number;
}else if(number < smallest) {
smallest = number;
}else {
System.out.print("Number isn't distinct");
counter = counter + 1;
}
System.out.println("Largest number is: " + largest);
System.out.println("Smallest number is: " + smallest);
}
}
Initialize your values like this so we guarantee that we start with the smallest/largest possible reference for our numbers to compare against to:
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
int number;
int old = Integer.MIN_VALUE;
...and then some tweaks have to be made:
Change the way you check for dupe numbers (use and old variable).
Check if every new number is smaller than smallest number always (so, in the first iteration we assign the first value to smallest and largest)
Like this:
number = input.nextInt();
if (old != number) {
old = number;
if (number > largest) {
largest = number;
}
if(number < smallest) {
smallest = number;
}
/* consider moving next line here (this will guarantee to go to the next
iteration only if the numbers are different, and get in the final messages,
valid values for `smallest` and `largest` */
// counter = counter + 1;
} else {
System.out.print("Number isn't distinct");
}
Just make > into >= and < into `<=
Since 0 < 0 evaluates to false, your code block does not run. Thus the correction.
Variable smallest is always 0 so the program never go into this block else if(number < smallest)
You should add this code before if(number < smallest)
if(smallest == 0) {
smallest = number;
}
Also your code doesn't catch the distinct numbers. To find the distinct number you should define a list List<Integer> numbers = null; at the start of the program.
Then you can check if the input is entered or not in the while loop like this:
if(numbers.contains(number))
System.out.print("Number isn't distinct");
else
numbers.add(number);
Sets the largest and smallert variables with the user's first input and then compare
import java.util.Scanner;
public class LargeSmall {
public static void main(String[] args) {
System.out.print("Enter number: ");
Scanner input= new Scanner(System.in);
int number = input.nextInt();
int counter = 1;
int largest = number;
int smallest = number;
while (counter < 10) {
System.out.print("Enter number: ");
number = input.nextInt();
if (number > largest) {
largest = number;
}else if(number < smallest) {
smallest = number;
}else
System.out.print("Number isn't distinct");
counter = counter + 1;
}
System.out.println("Largest number is: " + largest);
System.out.println("Smallest number is: " + smallest);
}
}

Java loop until user enters a value of 0. The values must be between 1-4 and if over 4, ask user to try inputting again

I need to create a loop where the user can input any amount of numbers between 1-4 and then I calculate the average. Typing 0 will end the program and calculate the average. Any value greater than 4 or less than 0 should not count and ask the user to input the value again. I'm stuck on the last part. I'm not sure if the while loop is the correct loop to use either. Thanks for any help
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
double count = 0;
while(input.hasNextInt()) {
int num = input.nextInt();
if (num == 0)
break;
if (num > 4)
System.out.println("Invalid number");
sum += num;
count += 1;
}
System.out.println("Average: " + sum/count);
}
You will always hit the lines:
sum += num;
count += 1;
Because the code just drops through from the second if statement.
The following would work - note the else if and else blocks will only be executed when the first if drops through:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
double count = 0;
while(input.hasNextInt()) {
int num = input.nextInt();
if (num == 0) {
break;
}
else if (num > 4) {
System.out.println("Invalid number");
}
else {
sum += num;
count += 1;
}
}
System.out.println("Average: " + sum/count);
}

Create a java application that displays the sum of the digits of a number

I am relatively new to Java and I'm currently learning while, do while and for loops. I want to create an application that displays the sum of the digits of a number using these concepts but I have no idea how. I previously created an application that displayed ONLY THE DIGITS of a number. Here it is.
int digit;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a positive integer: ");
digit = input.nextInt();
} while (digit <= 0);
input.close();
String sdigit = digit + "";
for (int i = 0; i < sdigit.length(); i++){
System.out.println(sdigit.charAt(i));
}
I'm trying to think of a possible way to expand on this program, but I have no idea why. Once again, this program is not what I need, what I need is somehow to sum the digits of a number using for or while loops. Thank you!
not much code has to be added for summing the digits :
First solution : using a substract with '0' character
int digit;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a positive integer: ");
digit = input.nextInt();
} while (digit <= 0);
input.close();
String sdigit = digit + "";
int sum=0;
for (int i = 0; i < sdigit.length(); i++){
System.out.println(sdigit.charAt(i));
sum = sum + (sdigit.charAt(i) - '0');
}
System.out.println("Sum is : "+sum);
Second solution : using Integer.parseInt which converts String to int :
int digit;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a positive integer: ");
digit = input.nextInt();
} while (digit <= 0);
input.close();
String sdigit = digit + "";
int sum=0;
for (int i = 0; i < sdigit.length(); i++){
System.out.println(sdigit.charAt(i));
sum = sum + Integer.parseInt(sdigit.subString(i,i+1));
}
System.out.println("Sum is : "+sum);
int digit;
System.out.println("Enter a positive integer: ");
number= Integer.parseInt(System.console().readLine());
int sum=0;
int currDigit = 0;
while( number / 10 > 0) {
currDigit = number % 10; //fetching last digit
System.out.println(currDigit);
sum = sum + currDigit;
number = number / 10;
}

program that sums all odd numbers between 1 and 100

Trying to create a program that sums all the odd numbers between 1 and 100 together, displays it, then shows the average. I can't figure out why the loop cuts off early. Super new to this too, so please go easy :p
int sum = 0;
double average;
double lowerbound = 1;
double upperbound = 100;
double number = lowerbound;
double remainder = 1;
//loop
while(number<= upperbound)
if (remainder == 1){
sum += number;
remainder = number%2;
System.out.println(number);
number++;
}else{
number++;
}
average = sum/upperbound;
System.out.println();
System.out.println ("These are your sums and averages");
System.out.println (sum);
System.out.println (average);
}
The main problem is your remainder part. You should calculate it directly:
while(number <= upperbound){
if (number % 2 == 1){
sum += number;
System.out.println(number);
}
number++;
}
What happens with your code is:
remainder starts of as 1. On the first loop number is also 1. So you enter the if case and you calculate the new remainder which is going to be 1%2 = 1. So in the next run you update remainder to be
remainder = 2%2 = 0`. //number = 2
However, since your remainder variable is now set to 0, you will never enter the if case again and therefore never update your remainder. (So the loop doesn't end any earlier, you just skip everthing inside of it)
Also notice that you don't need the else case, since you are increasing number in both the if and the else
You have to check the remainder for every value that you are calculating.
public static void main(String[] args) {
int sum = 0;
double average;
double lowerbound = 1;
double upperbound = 100;
double number = lowerbound;
//double remainder = 1;
//loop
while(number<= upperbound)
if (number%2==1){
sum += number;
//remainder = number%2;
System.out.println(number);
number++;
}else{
number++;
}
average = sum/upperbound;
System.out.println();
System.out.println ("These are your sums and averages");
System.out.println (sum);
System.out.println (average);
}

Why does my code not run?

I have this code:
import java.util.Scanner;
public class PositiveNegative { public static void main(String[] args) {
int numbers, plus = 0, minus = 0;
int count = 0;
double total = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
while(numbers != 0)
{
total += numbers;
if(numbers > 0)
plus++;
if(numbers < 0)
minus++;
}
System.out.println("The number of positives is: " +plus);
System.out.println("The number of negatives is: " +minus);
System.out.println("The number of total is: " +total);
}
}
The problem with is that I try to run it and type the numbers but it does nothing. I want it so that when you type 0 it stops taking numbers and starts processing the code. What should I do?
Try this:
import java.util.Scanner;
public class PositiveNegative {
public static void main(String[] args) {
int numbers = 0, plus = 0, minus = 0;
double total = 0;
do{
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
numbers = Integer.valueOf(scan.nextLine());
total += numbers;
if (numbers > 0)
plus++;
if (numbers < 0)
minus++;
}
while (numbers != 0);
System.out.println("The number of positives is: " + plus);
System.out.println("The number of negatives is: " + minus);
System.out.println("The number of total is: " + total);
}
}
Put your Scanner in the while loop so that everytime loop start it will ask for User input.
You need to update numbers or your loop will run for ever. And I recommend using braces (and an else). Something like,
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
while (numbers != 0) {
total += numbers;
if (numbers > 0) {
plus++;
} else if (numbers < 0) {
minus++;
}
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
}
Alternatively, you could use a do-while loop. Then you only need one copy of the prompt. Like,
do {
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
total += numbers;
if (numbers > 0) {
plus++;
} else if (numbers < 0) {
minus++;
}
} while (numbers != 0);
You have to modify numbers each time to make it work in your while.
So, in your existing code, just comment out numbers = scan.nextInt(); and use below--
// numbers = scan.nextInt(); //comment out this call
while ((numbers = scan.nextInt()) != 0) {
....
this will give you desired output--
Enter an integer (0 to quit): 9
4
-9
1
0
The number of positives is: 3
The number of negatives is: 1
The number of total is: 5.0

Categories