How to increment input value by two in Java [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
My program asks the individual to input 2 numbers (ie; 10 and 20).
I would like the output to be:
Even numbers: 10 12 14 16 18 20
My code:
System.out.println("Enter an integer:");
int firstNum = keyboard.nextInt();
System.out.println("Enter another integer larger than the first one:");
int secondNum = keyboard.nextInt();
System.out.println();
int mod = firstNum % 2;
while ((firstNum < secondNum) && mod == 0)
{
firstNum = firstNum + 2;
System.out.print("Even numbers" +firstNum);
}

You are close to the result you are after, just need to rearrange the order of a couple of lines and add one if check.
I have made a complete example that runs as expected and allows for both odd and even numbers. You can replace your code with the following:
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer:");
int firstNum = keyboard.nextInt();
System.out.println("Enter another integer larger than the first one:");
int secondNum = keyboard.nextInt();
System.out.println();
int mod = firstNum % 2;
//If first number is odd, increase by one to make it even.
if (mod != 0)
{
firstNum++;
}
System.out.print("Even Numbers: ");
while (firstNum <= secondNum)
{
System.out.print(firstNum + " ");
firstNum = firstNum + 2;
}
keyboard.close();
}

Related

How to take the sum of squares in java? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
So I am a beginner in java and am just learning the loop concept. One of my assignments is to modify this code below so that it prints out the sum of the squares of the values, rather than just the sum of the values:
Scanner scan = new Scanner(System.in);
System.out.println("Enter two numbers");
System.out.println("Separate with spaces");
System.out.println("Code sums from first to second");
int first = scan.nextInt();
int second = scan.nextInt();
int sum = 0;
for(int i = first; i <= second; i++)
{
sum += (i);
}
System.out.print("Sum from "+ first +" to " + second );
System.out.println(" is " + sum);`
Apparently I only have to modify one line of this code. I tried:
Scanner scan = new Scanner(System.in);
System.out.println("Enter two numbers");
System.out.println("Separate with spaces");
System.out.println("Code sums from first to second");
int first = scan.nextInt();
int second = scan.nextInt();
int sum = 0;
for(int i = first; i <= second; i++)
{
sum += (i^2);
}
where I thought if you just added the i^2 value inside of the parenthesis it would work, but it did not. Any help on how I do this/any help on understanding how a loop works would be greatly appreciated.
As the comments said,
change i^2 to i*i
Scanner scan = new Scanner(System.in);
System.out.println("Enter two numbers");
System.out.println("Separate with spaces");
System.out.println("Code sums from first to second");
int first = scan.nextInt();
int second = scan.nextInt();
int sum = 0;
for(int i = first; i <= second; i++)
{
sum += (i*i);
}
I applied the formula of sum of squares of n terms here and subtracting first one I had used n*(n+1)*(2*n+1)/6 formula here with out no loop performance o(1)
sum = (second*(second+1)*((2*second)+1))/6 - (first*(first+1)*((2*first)+1))/6;
Just change
sum += (i);
to
sum += (i*i);

Java loops and zero divisor

I am creating a program that will calculate two numbers. My issue is 0 will be an illegal input to the program but instead of asking again for two numbers.
The program continues to run without giving an error, or giving any answer when ZERO is imputed, it's suppose to ask the user to input two different numbers again.
I've done all the code and it mostly works and there is no visible error.
import java.util.*;
import java.util.Scanner.*;
public class MinilabLoopLogic
{
public static void main(String[ ] args)
{
int num1, num2, divisor, total;
Scanner kb = new Scanner(System.in); //you do it!
System.out.print("Please enter 2 integers (separated by spaces): ");
num1 = kb.nextInt();
num2 = kb.nextInt();
System.out.println("\n\nThis program will generate numbers BETWEEN "+ num1 + " " + num2);
System.out.println("\nPlease enter the integer your output should be divisible by: ");
divisor = kb.nextInt();
while (divisor == 0)
{
divisor = kb.nextInt();
}
System.out.println("\n\n----------------------------------------");
//Be able to handle 1st number smaller
// OR 2nd number smalle
//Use the modulus operator to check if a number is divisible
if (num1 < num2)
{
for (total = num1+1; total < num2; total++ )
{
if (total % divisor == 0)
{
System.out.println(total);
}
}
}
else
{
for (total = num1 - 1; total > num2; total--)
{
if (total % divisor == 0)
{
System.out.println(total);
}
}
}
}
}//end main()
Your problem lies in your while loop looking for the divisor:
System.out.println("\nPlease enter the integer your output should be divisible by: ");
divisor = kb.nextInt(); // gets your divisor
while (divisor == 0) //if it is illegal, e.g. 0
{
divisor = kb.nextInt(); // waits for more divisor input
}
You should output a string to tell the user what the problem is. say:
divisor = kb.nextInt(); // gets your divisor
while (divisor == 0) //if it is illegal, e.g. 0
{
System.out.println("\nYou can't divide by 0. Try again!: ");
divisor = kb.nextInt(); // waits for more divisor input
}
Also, if you want them to have to re-enter the num1 and num2 then scanner input has to happen in that while loop.
You added the following in an edit:
The program continues to run without giving an error, or giving any answer when ZERO is imputed, it's suppose to ask the user to input two different numbers again.
That is because you just loop back to get another value when a zero is entered, without writing any new prompt text.
It also only gets a new divisor number, not "two different numbers". If you looped back to before "Please enter 2 integers", it'd actually end up prompting for all 3 numbers again.

check a list how many is positive number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Write a program called PositiveNegative that reads an unspecified number of integers, determines how many positive and negative values have been entered, and computes the sum and average of the input values (not counting zeros). The reading of input ends when the user enters 0 (zero). Display the number of positive and negative inputs, the sum and the average. The average should be computed as a floating-point number. Design the program such that it asks the user if they want to continue with new inputs after each set of entries, ending the program only when they do not respond to the question with "yes".
Here is a sample run:
Input a list of integers (end with 0): 1 2 -1 3 0
# of positive inputs: 3
# of negative inputs: 1
The total: 5.0
The average: 1.25
Would you like to continue with new inputs? yes
Input a list of integers (end with 0): 0
No numbers were entered except 0
Would you like to continue with new inputs? no
and here is my codeļ¼š
import java.util.*;
public class PositiveNegative
{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String answer;
int countpositive = 0;
int countnegative = 0;
int total = 0;
int num = 0;
System.out.print("Input a list of integers (end with 0): ");
do{
String list = input.nextLine();
for(int i = 0; ; i=i+2 ){
num = Integer.parseInt(list.substring(i,i+1));
if( num == 0)
break;
else if ( num > 0)
countpositive++;
else if ( num < 0)
countnegative--;
total = total + num;
}
double average = total/(countpositive + countnegative);
System.out.println("# of positive inputs: "+countpositive);
System.out.println("# of negative inputs: "+countnegative);
System.out.println("The total: "+total);
System.out.println("The average"+average);
System.out.println("\n ");
System.out.print("Would you like to continue with new inputs? ");
answer = input.next();
}while(answer.equalsIgnoreCase("Yes"));
}
}
I can compile file, but when i run it, i can't get result like sample run.
You are decrementing (countnegative--;) the count of negative integers instead of incrementing it (countnegative++;) when a negative integer is encountered.

how to use a while loop correctly

Write a program that uses a while loop to perform the following steps:
Comment by labelling each part: //Part A, //Part B, etc...
A.)Prompt the user to input 2 integers: firstNum and secondNum. Use 10 and 20.
B.)Output all odd numbers between firstNum and secondNum.
C.)Output the sum of all even numbers between firstNum and secondNum.
D.)Output the numbers and their square between 1 and 10.
E.)Output the sum of the square of odd numbers between firstNum and secondNum.
F.)Output all uppercase letters.
Again I am new to while loops and I am totally lost. I have tried reading a bunch but I am better at learning if someone shows me how to do something. I am open to all suggestions. I have just completed 8 other programs using if else statements and now trying to get the hang of loops. Thanks!
This is my pathetic attempt so far LOL
import java.util.Scanner;
public class whileLoop
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
//Part A
int firstNum = 10;
int secondNum = 20;
System.out.println("Please enter two integers: ");
int oddNum = keyboard.nextInt();
//Part B
while(firstNum <= secondNum)
{
if(firstNum % 2 != 0)
}
oddNum = firstNum + secondNum;
firstNum++;
}
System.out.println(""+oddNum);
}
}
I would like to show you how to use while loop on
Output all odd numbers between firstNum and secondNum.
Output the sum of all even numbers between firstNum and secondNum.
Output the sum of the square of odd numbers between firstNum and secondNum.
int i=firstnumber;
int sum=0;
int sumofsqr=0;
while(i<=secondnumber){
if(i%2==0){
System.out.println(i);
sum+=i;
}
else{
sumofsqr+=i*i;
}
i++;
}
System.out.println("Sum of odd " + sum + " Sum of sqr of even " + sumofsqr);
I think you meant to do this:
//Part B
int temp = firstNum;
while(temp <= secondNum)
{
if(temp % 2 != 0)
{
System.out.println(""+temp);
}
temp++;
}

How to display the sum of the cubes of the digits? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Code:
import java.util.*;
import java.io.*;
class Cubesum {
public static void main(String args[]){
int input=0;
int num1,num2,num3;
//read the number
System.out.println("Enter a Number");
Scanner console = new Scanner(System.in);
input= Integer.parseInt(console.nextLine());
// now let us print the cube of digits
//i.e if number is 123 we will print 1^3, 2^3 and 3^3
//we will also add 1 and 3 to output the sum of first
//and last digits
int number = input; //number is a temp variable
int counter = 0; //counter is used to count no of digits
while(number>0){
int t= number%10;
System.out.println("Cube of "+t +" is "+(t*t*t));
counter = counter+1;
number = number/10;
}
}
}
Output:
Enter a Number
**223**
Cube of 3 is 27
Cube of 2 is 8
Cube of 2 is 8
How do I add the cubes of these numbers? For example, 27+8+8 would be 43
Maybe you want to do something like this:
int number = input;
int sum = 0;
while (number > 0) {
int digit = number % 10;
sum += digit * digit * digit;
number /= 10;
}
Try this code.
int sum=0;
while(number>0){
int t= number%10;
System.out.println("Cube of "+t +" is "+(t*t*t));
sum=sum+(t*t*t);
counter = counter+1;
number = number/10;
}
System.out.println(sum);
Here a solution:
int sum = 0;
while(number>0){
int t= number%10;
System.out.println("Cube of "+t +" is "+(t*t*t));
sum += t*t*t;
counter = counter+1;
number = number/10;
}
System.out.println(sum);
You seem new to Java, so here is a more simple (and readable) example for you:
import java.util.*;
import java.io.*;
class Cubesum {
public static void main(String args[]){
int num1,num2,num3;
Scanner console = new Scanner(System.in);
//read the numbers
System.out.println("Enter the first number");
num1 = Integer.parseInt(console.nextLine());
System.out.println("Enter the second number");
num2 = Integer.parseInt(console.nextLine());
System.out.println("Enter the third number");
num3 = Integer.parseInt(console.nextLine());
int output = (int1*int1*int1)+(int2*int2*int2)+(int3*int3*int3)
System.out.println("result is: " + output);
}
}
You want to get each number individually then create the result.
Sample input:
2
2
3
Output should be:
43

Categories