Here is my while loop. The program sums up integers until a negative number is input. At that point the loop should break and it should print "Goodbye". However it is adding the negative number each time before it says goodbye. Im not sure what is going wrong here. Please help?!
import java.util.Scanner;
public class While {
public static void main(String[] args)
{
int input = 5;
int sum = 0;
while(input >= 0)
{
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
sum = sum + input;
System.out.println("Running total: " + sum );
}
System.out.println("Goodbye!" );
}
Test:
Please enter a positive integer:
5
Running total: 5
Please enter a positive integer:
10
Running total: 15
Please enter a positive integer:
-1
Running total: 14
Goodbye!
I do not want to get the return value of 14, it should simply say Goodbye!
You need to use the break keyword. Your loop will always finish so the check on the while only happens after you've added the negative number. You could change to this:
while(true)
{
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
if(input <0){
break;
}
sum = sum + input;
System.out.println("Running total: " + sum );
}
Or this:
while(input >= 0)
{
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
if(input <0){
break;
sum = sum + input;
System.out.println("Running total: " + sum );
}
}
Or to avoid if statements entirely if needed (though that isn't the point of loops):
while(input >= 0)
{
sum = sum + input;
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
System.out.println("Running total: " + sum );
}
Here was my solution:
while(input >= 0)
{
sum = sum + input;
System.out.println("Running total: " + sum );
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
}
System.out.println("Goodbye!" );
}
by calculating the sum at initialization and before the first integer is entered. It appears to work the way I want now. Thanks for your help.
Related
Im confused as to how I allow only numbers 1-4? Im not sure if there is a term for this, i think its parameter
THE CODE IM QUESTIONING IS THE 3RD TO LAST LINE
private void validatePositiveNumber() {
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Please enter a positive number: ");
while (!scanner.hasNextInt()) {
String input = scanner.next();
System.out.printf("\"%s\" is not a valid number.\n", input);
}
number = scanner.nextInt();
} while (number < 4);
System.out.printf("You have entered a positive number %d.\n", number);
}
Use while (number > 4 || number < 1); This disallows anything outside of the range.
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Please enter a positive number: ");
while (!scanner.hasNextInt()) {
String input = scanner.next();
System.out.printf("\"%s\" is not a valid number.\n", input);
}
number = scanner.nextInt();
} while (number > 4 || number < 1);
System.out.printf("You have entered a positive number %d.\n", number);
I am a beginner to java and don't know to write a program using loops that prompt the user to enter a number till user does does not enter 0.
When user enter 0 then system should display MAX number among user input
QUE 2
Write a program to ask the user to enter a sequence of numbers (double type). The numbers are separated by the return key (and give a prompt for each enter). The user ends the sequence by entering a 0. Then output the maximum number of all the entered numbers. Here is an example (the part in italic is the user’s input): Please enter a sequence of numbers, separated by return, and then end this sequence with a 0 at last: 25
Next number: 35.6
Next number: 112.112
Next number: 0
The maximum among your enters is 112.112
import java.util.Scanner;
public class Q3
{
public static void main(String[] args[])
{
double n;
// double i;
double MAX=0;
System.out.println("Please Enter the number: ");
Scanner Kb = new Scanner(System.in);
n = Kb.nextDouble();
if(n>0){
System.out.println("Please Enter the number: ");
n = Kb.nextDouble();
return;
}
else if(n==0) {
if (MAX>0){
MAX=n;
return ;
}
}
return;
}
}
Keep track of the max and each time a user inputs a number check if it is greater than that max
import java.util.Scanner;
public class Q3 {
public static void main(String... args) {
double max = 0;
System.out.println("Please enter the number: ");
Scanner kb = new Scanner(System.in);
double number = kb.nextDouble();
while (number != 0) {
if (max < number) {
max = number;
}
number = kb.nextDouble();
}
System.out.print("The max is " + max);
}
}
Since zero is the terminal character then negative input can be essentially ignored and the initial value of max as zero is acceptable.
Note that nextDouble can throw an InputMismatchException if the user decides to give you input that can not be parsed to a double.
using Collections.max ,
List<Double> doubleList = new ArrayList<>();
System.out.println("enter a number :");
Scanner kb = new Scanner(System.in);
while (kb.hasNext() ) {
double input = kb.nextDouble();
if(input == 0){
break;
}
doubleList.add(input);
}
System.out.println("Max Value Entered : " + Collections.max(doubleList));
Scanner sc = new Scanner(System.in);
double max = 0;
while(true){
double number = sc.nextDouble();
if(max<number){
max = number;
}
else if(number==0){
break;
}
}
System.out.print(max);
I have to write a program that asks the user to enter an integer value. After each value, the user has to respond with a "y" or a "n" if he/she wants to continue with the program, and each number the user enters is stated as either odd or even.
I have done this so far with a do-while loop, but I am confused on how to get the averages of the values the user enters. How would you get the average for all the numbers entered?
Here is my code so far:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
do {
int num, count = 0;
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next();
count++;
} while (answer.equals("y"));
}
}
From the Question looks like following things need to handled,
haven't add mechanism for addition into single variable.
put all variable to out from do...while loop body...
created additional variable according to requirement.
see all this things covered by me with following code snippet.
do something likewise,
String answer = "";
double sum = 0; // use for storing addition to all entered values..
int num, count = 0;
Scanner scan = new Scanner(System.in);
do {
System.out.print("Enter any number : ");
num = scan.nextInt(); // getting input from user through console
sum = sum + num; // add every input number into sum-variable
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next(); // ask for still want to repeat..
count++;
} while (answer.equals("y"));
System.out.println("Average is : " + sum + "/" + count + " = "+ (sum /count));
In order to calculate Average, you need 2 things: Sum of all numbers and Count of all numbers involved in the Average calculation.
Your sum and count which involved in the Average calculation needs to be out of the do..while scope in order for them to be known at the calculation stage.
I also took the liberty of fixing your code a little bit
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System. in );
int count = 0;
int sum = 0;
String answer = "";
do {
System.out.print("Enter any number : ");
int num = scan.nextInt();
boolean isEven = (num % 2 == 0);
System.out.println(num + " is an " + (isEven ? "even" : "odd") + " number.");
sum += num;
System.out.println("do you want to continue?");
answer = scan.next();
count++;
} while (answer.toLowerCase().equals("y"));
System.out.println("Average: " + (sum/count));
}
}
Change your code like this:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
int avr =0;
int num, count = 0;
do {
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
avr += num;
answer = scan.next();
count++;
} while (answer.equals("y"));
avr = avr /count;
System.out.println("The avreage of value is:" + avr );
}
}
avr is average. that means when you input an integer. we add num and avr . and when finish looping. we divideto count. like this:
1-5-9-11
avr = 1+5+9+11;
count = 4;
avr = avr/4;
I am trying to write a method that will subtract multiple numbers instead of using just 2 input numbers.
So far I have...
public void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double value = in.nextDouble();
double difference = 0;
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
double valueTwo = in.nextInt();
difference = value - valueTwo;
}
System.out.println("Difference: " + difference);
}
this currently only works with 2 inputs, but my end goal is to be able to continue subtracting multiple numbers.
Instead of continually subtracting from value, instead subtract from difference
Change difference = value - valueTwo; to difference -= valueTwo
This will be equivalent to doing ((A - B) - C) - ..., A being the first input, B the second input, C the third input...
public void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double difference = in.nextDouble();
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
difference -= in.nextDouble();
}
System.out.println("Difference: " + difference);
}
This should work fine
#include <stdio.h>
int main()
{
int result=0, n,number,i;
printf("How many numbers you want to use?\n");
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d", &number);
if(i ==0 ){
result=number;
}
else{
result -= number;
}
}
printf("Answer is= %d ", result);
return 0;
}
Output:
How many numbers you want to use?
4
55
34
1
3
Answer is= 17
This solution doesn't hang after the first input. It is more user friendly.
public static void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the next number: ");
double difference = 0.0;
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
difference -= in.nextDouble();
}
System.out.println("Difference: " + difference);
}
Why have two variables? Anyway, the following is simpler and prompts correctly:
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double value = in.nextDouble();
while (true) {
in.nextLine(); // Silently discard rest of line
System.out.print("Please enter the next number, or . to stop: ");
if (! in.hasNextDouble())
break;
value -= in.nextDouble();
}
System.out.println("Difference: " + value);
Test
Please enter the number: 10
Please enter the next number, or . to stop: 1
Please enter the next number, or . to stop: 2
Please enter the next number, or . to stop: 3
Please enter the next number, or . to stop: .
Difference: 4.0
I have a situation in java;
I would like to ask the user to put in some numbers & have a total of those numbers. However if the user enter a negative number it will end the loop;
currently I have a while loop as below;
double sum = 0;
double Input = 0;
System.out.println("Please enter the numbers (negative to end)")
System.out.println("Enter a number");
Scanner kdb = new Scanner(System.in);
Input = kdb.nextDouble();
while (Input > 0)
{
System.out.println("Enter an income");
Input = kdb.nextDouble();
sum = Input;
}
However it does not do the job. If the user put in 40,60,50, and -1 the correct result should be 150; my loop result in 109.
Please help!
Many thanks!
Jackie
double sum = 0;
double Input = 0;
System.out.println("Please enter the numbers (negative to end)")
System.out.println("Enter a number");
Scanner kdb = new Scanner(System.in);
Input = kdb.nextDouble();
while (Input > 0)
{
sum += Input;
System.out.println("Enter an income");
Input = kdb.nextDouble();
}
I recommend variable names not to start with upper case letters.
You should check for Input > 0 before doing sum += Input.
This should work!
double sum = 0;
double Input = 0;
boolean Adding= true;
System.out.println("Please enter the numbers (negative to end)");
Scanner kdb = new Scanner(System.in);
while(Adding == true)
{
System.out.print("Enter a number: ");
Input = kdb.nextDouble();
if(Input > 0)
{
sum+= Input;
}
else
Adding = false;
}
System.out.println("Your sum is: " + sum);
The first input value was overwritten by the second one since the the sum was done only at the end of the loop.
**double sum = 0;
double Input = 0;
System.out.println("Please enter the numbers (negative to end)");
System.out.println("Enter a number");
Scanner kdb = new Scanner(System.in);
Input = kdb.nextDouble();
while (Input>0)
{
sum+= Input;
System.out.println("Enter an income");
Input = kdb.nextDouble();
}
System.out.println(sum);
}**
The output is:
Please enter the numbers (negative to end)
Enter a number
40
Enter an income
50
Enter an income
60
Enter an income
-1
150.0