I want my program that to accept user number input and output the sum from 1 up to the input number (using while loop).
Example: If input value is 4, the sum is 10 i.e., 1 + 2 + 3 + 4.
My code compiles but returns a never ending 1 until my jcreator stops responding.
import java.util.Scanner;
import java.io.*;
public class SumLoopWhile {
public static void main(String[] args) {
int number;
int sum = 1;
Scanner in = new Scanner (System.in);
System.out.println("Enter number: ");
number = in.nextInt();
while (sum <= 10) {
System.out.println("Sum is: " + sum);
number++;
}
}
}
You should be comparing the value to the number that was input, and adding to the sum. Finally, display the result after the loop. Something like
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number: ");
int number = in.nextInt();
int sum = 0;
int v = 0;
while (v <= number) {
sum += v;
v++;
}
System.out.println("Sum is: " + sum);
}
Which will print Sum is: 10 when the input is 4 (as requested).
I guess that what you want it's to modify the sum inside your while loop. Do it like this:
while (sum <= 10) {
sum = sum + number;
number++;
}
}
System.out.println("Sum is: " + sum);
You have to put your System.out.println out of the loop because you want to print the total value, not each sum that it's calculated in each iteration.
Also, it should be nice that when you want to initialize some int that will be a "total" variable (like the result of a sum, rest or whatever), initialize it to zero.
int sum = 0;
Your output variable sum is having the same value throughout the program.it is not getting altered.the while loop becomes infinite loop
The Condition
(sum <= 10) never becomes true and the while loop will run for infinite times
import javax.swing.JOptionPane;
public class SumUsingWhileLoop {
public static void main(String[] args) {
String input;
input = JOptionPane.showInputDialog("Input the number:");
int number;
number = Integer.parseInt(input);
int sum = 0;
int i = 1;
while (i <= number) {
sum += i;
i++;
}
JOptionPane.showMessageDialog(null, "Sum = " + sum);
System.exit(0);
}
}
The System.out.println should not be placed inside the while loop, because it will get executed as many times as the loop.If you want to print the sum value only once, then the statement System.out.println must be placed outside the loop block.
Just use another variable for counting the iterations.For example
while(count<=number)
{
sum=sum+count;
count++
}
System.out.println("Sum is: "+ sum);
Related
My concern is only with why the modulo (%) isn't working. Please don't comment on the code on it's entirety. My code is as displayed below.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.println("Enter a number");
int num = scanner.nextInt();
int count = 0;
while(num!=0) {
num = num/10;
count++;
}
System.out.println("Total digits = " + count );
int rem = num % 10;
System.out.println(rem);
}}
The output is
Also quick note: the output for "rem" is 0 only when "num" is passed as an operand. If a number replaces the "num" then the code works just fine
There is a wrong logic used for reversing the number. You can try below code.
public class ReverseNumberExample1
{
public static void main(String[] args)
{
int number = 987654, reverse = 0;
while(number != 0)
{
int remainder = number % 10;
reverse = reverse * 10 + remainder;
number = number/10;
}
System.out.println("The reverse of the given number is: " + reverse);
}
}
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 get the sum of even numbers between 2 and a value entered by the user. I managed to get as far as printing out the even numbers but how would I get it to print just a sum of the even numbers? Rather than listing out all of the even numbers?
At the end it should look like this:
Entered value: 20
Sum of even numbers between 2 and 20: 110
import java.util.Scanner;
public class Practice_7_1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
while (true)
{
//Gather data value
System.out.println("Please enter a number: ");
int value = input.nextInt();
String text = "Sum of even numbers between 2 and " + value + " is: ";
//Loop
int i = 2;
while (i <= value)
{
if (i%2 == 0){
text = (text + i);
if (i< value)
text = (text + ", ");
else
text = (text + ". ");
}
i++;
}
//Output
System.out.println(text);
}
}
}
Edit:
Final answer:
import java.util.Scanner;
public class Practice_7_1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
while (true)
{
//Gather data value
System.out.println("Please enter a number: ");
int value = input.nextInt();
String text = "Sum of even numbers between 2 and " + value + " is: ";
//Loop
int sum = 0;
for (int i = 2; i <= value; i +=2){
sum += i;
}
//Output
System.out.print(text);
System.out.println(sum);
}
}
}
Use a for loop. With a for loop, you can customize the "step" of your internal loop variable (i). This also removes the need to check for even-ness.
int sum = 0;
for (int i = 2; i < value; i+=2) {
sum += i;
}
System.out.println(sum);
On a side note, you should probably avoid the use of while(true) because it's going to require the use of an explicit break to exit the program. You should instead use some sort of boolean control variable.
I have a little averaging program I have made and, I am trying to only allow it to take in numbers. Everything else works but, I can't seem to figure it out. I am still learning so, any advise or pointers would be awesome!
Here is my code.
import java.util.Scanner;
public class THISISATEST {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int sum = 0;
int count = 0;
int i = 1;
while (i <= 10) {
i++;
{
System.out.print("Enter the test score: ");
int tS = keyboard.nextInt();
count++;
sum = (sum + tS);
}
System.out.println(sum);
}
System.out.println("The Average is = " + sum / count);
}
}
Inside your while loop use the following code:
System.out.print("Enter the test score: ");
while (!keyboard.hasNextInt()) {//Will run till an integer input is found
System.out.println("Only number input is allowed!");
System.out.print("Enter the test score: ");
keyboard.next();
}
int tS = keyboard.nextInt();
//If input is a valid int value then the above while loop would not be executed
//but it will be assigned to your variable 'int ts'
count++;
sum = (sum + tS);
I am trying to get the average of user inputted numbers. Every time I input numbers the output is always-
The sum is 6
How many numbers: 4
Average: 2.0
A while loop is required, unfortunately for loops are not allowed. I am pretty new to Java so my formatting is sloppy. Where in my code are my problems?
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
int count = 0;
int sum = 0;
int endingVariable = -1;
int input = 0;
double average;
while (input >= endingVariable) {
System.out.println("Type numbers: ");
input = Integer.parseInt(reader.nextLine());
sum += count;
average = (double)sum / count;
count++;
if (input == endingVariable) {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + count);
System.out.println("Average: " + average);
break;
}
}
}
}
You have several errors here.
The main one that causes your error is sum += count. Instead of adding what the user has entered, you are adding the number that shows how many numbers there are. So it will always add 0+1+2+3 etc.
Another problem is that, once you change the above, you have to check whether the input == endingVariable before you add the input to the sum. So you have to write the if first, and then calculate the average inside it. Otherwise it will treat your -1 as part of the sequence of numbers to calculate.
You only need to add the input to the sum and increment the count if you find out that the input is not yet the same as endingVariable.
So:
Add the input, not the count, to the sum.
Calculate the average only when you have reached the final item.
Add the input to the sum and increment the counter only if your input is not endingVariable.
Try this one...
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
int count = 0;
int sum = 0;
int endingVariable = -1;
int input = 0;
double average;
while (input >= endingVariable) {
System.out.println("Type numbers: ");
input = Integer.parseInt(reader.nextLine());
sum += input; // you were doing mistake here.
average = (double)sum / count;
count++;
if (input == endingVariable) {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + count);
System.out.println("Average: " + average);
break;
}
}
}
}
Two big issues with your code. First, this line:
sum += count;
It's probably just a typo, but it should be obviously:
sum += input;
Second, once you fix that, you will notice you are including the -1 in your sum. You probably want something like this:
System.out.println("Type numbers: ");
input = Integer.parseInt(reader.nextLine());
if (input == endingVariable) {
average = (double) sum / count;
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + count);
System.out.println("Average: " + average);
break;
} else {
sum += input;
count++;
}
Thank you for explaining in detail. It works fine now, all I had to do was what you said is change the input, and move the sum += input and count after the final item in an else. I was having the hardest time trying to figure out why my -1 was being included