why does displayed number goes above the input number in java? - java

Currently, I am doing an assignment on displaying all odd numbers up to a user inputted specific odd number. The requirement is to include the input number, however, I don't understand why does the code always goes to the next Odd number compared to what user inputted. Please help.
import java.util.Scanner;
public class OddNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Pls enter an odd number you want to finish to: ");
int capp_number = input.nextInt();
int startingNumber = 1;
for(int i = 0; i < capp_number; i+= 2){
startingNumber += 2;
System.out.println(startingNumber);
}

This is because i starts at 0 (It is even), and you are checking to see if it is less than capp_number (which should be odd), and then adding two to i. startingNumber starts at 1, so it is odd. So if the user enters 5 it will go like:
Iteration 1:
i (0) < 5 ? Yes:
print startingNumber+2
output: 3
i == 2
Iteration 2:
i (2) < 5 ? Yes:
print startingNumber +2
output: 5
i == 4
Iteration 3:
i (4) < 5 ? Yes:
print startingNumber +2
output: 7
i == 6
Iteration 4
i (6) < 5 No:
end loop
To fix this, start i at one:
for(int i = 1; i < capp_number; i+= 2)

Sorry, but why did you write this ?
while(startingNumber < capp_number);
i agree with a previous answer and think that there is no reason for this line. And also you should correct your loop as it was also mentioned in previous answer:for(int i = 0; i < capp_number; i+= 2)

Try this. You needed to initialise i to 1 within the for-loop. 1 is an odd number so instead of starting with an even number (0), you look for every odd number.
For example, if you start at 1: 1+2=3, 3+2=5, 5+2=7.... and so on.
For example, if you start at 0: 0+2=2, 2+2=4, 4+2=6.... and so on.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Pls enter an odd number you want to finish to: ");
int capp_number = input.nextInt();
int startingNumber = 1;
for(int i = 1; i < capp_number; i += 2){
startingNumber += 2;
System.out.println(startingNumber);
}

Related

Java HW Help. Loops with user input for even number values

I have to write a main program that asks the user for a number between 10 and 20 and its prints the even numbers between that number and 50. If the number is not in the 10 and 20 range, inclusive, the program will keep prompting the user for a valid number.
So far this is what I have
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
Scanner keyboard = new Scanner(System.in);
System.out.println("Please choose a number between 10 and 20! ");
int number = keyboard.nextInt();
int newnumber = number;
while (number <= 10 || number >= 20) {
System.out.print("No, between 10 and 20: ");
System.out.println("Please choose a number between 10 and 20! ");
number = keyboard.nextInt();
}
while (number >= 10 || number <= 20) {
int limit = 50;
for (int i= 10; newnumber <= 50; i++) {
if (i% 2 == 0) {
System.out.println(newnumber);
newnumber=newnumber+2;
}
}
}
}
}
Unrelated to your problem, but your first while loop will prevent the user from putting in 10 or 20 because the while loop keeps checking if the input is equal to those two.
Your second while loop isn't doing much and would make more sense as an if statement - If you hadn't already verified that it was in the range in your first while loop.
Now your actual problem is you start your counter as i but increment newnumber. Even if you were incrementing i, it would still never work for odds because your starting number is odd and you increment by 2. Your two options are to
start i at number, unless number is odd then number+1
increment the loop counter by 1 each iteration
Using the first option
while (number < 10 || number > 20) {
System.out.print("No, between 10 and 20: ");
System.out.println("Please choose a number between 10 and 20! ");
number = keyboard.nextInt();
}
for (int i = (number % 2 == 0 ? number : number+1); i <= 50; i+=2) {
System.out.println(newnumber);
}
Notice that I quit checking if each iteration was even because I made sure to start with an even number and increment by 2.

Print a variable a n number of times in java

My project is to show lines with cardinals, from an initial number and
then varying this number to another number entered.
It starts by asking for a initial number of cardinals (the output must be "###" the number of times asked) and then ask for the final number of cardinals to add. So case, click here 5 initial cardinals and add 3, the program must show a line with 5, another with 6, another with 7 and another with 8 cardinals.
How do I add the cardinals? With if-else?
import java.util.Scanner;
public class P02Cardinais {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the number inicial of cardinals: ");
int numCardinais = keyboard.nextInt();
System.out.println("Enter the number of cardinals to add: ");
int numCardinaisAdd = keyboard.nextInt();
int i;
for (i = 0; i < numCardinais; i++) {
System.out.print("#");
} System.out.print(" - " + numCardinais);
keyboard.close();
}
}
Example of the output
(number inicial - 2 ; number to add - 3)
## - 2
### - 3
#### - 4
##### - 5
You need 2 loops
one for the number of lines from initial to initial+add
one for the number of # which has to be the index of first loop (limo of j is i)
for (int i = numCardinais; i <= numCardinais+numCardinaisAdd; i++) {
for (int j = 0; j<i; j++) {
System.out.print("#");
}
System.out.println(" - " + i); // new line and index
}

a method keeps asking for input when i didnt even ask the user for input

hey i am solving a problem on codingbat called sumDigits where u make a method which sums the digits of a number
for example
123 should return 1 + 2 +3 // 6
here is the code
public int sumDigits(int num ) // num = 123
{
int sumOfDigits = 0;
for(int i = num ; i >= 0 ; i /= 10)
{
int digit = i % 10; // stores the rightmost digit then adds it to sumOfDigits
sumOfDigits += digit;
}
return sumOfDigits;
}
Main Function:-
System.out.println("Problem 4");
Assignment5 solutionA5 = new Assignment5();
System.out.println(solutionA5.sumDigits(123));
the problem is , when i run the program
and the num parameter is = 123 as i wrote in the comment
the program waits for the user to enter another num !
i dont understand why , i didnt even include any scanner in.nextInt or anything like that ?
sorry if its a lame question
the program waits for the user to enter another num
No it doesn't. It enters an infinite loop, because i can never become negative. Your loop should be:
for (int i = num; i > 0; i /= 10)
What 'enter another num' can possibly mean in a program that doesn't accept user input at all is another mystery.
It goes into infinite loop one the value of i=0 . You shall change
for(int i = num ; i >= 0 ; i /= 10)
to
for(int i = num ; i > 0 ; i /= 10)
i didnt even include any scanner in.nextInt
Its not waiting for the user input either. All it does is this:
System.out.println("Problem 4"); // prints 'Problem 4'
Assignment5 solutionA5 = new Assignment5();
System.out.println(solutionA5.sumDigits(123)); // goes into the infinite loop

receive input to find number of multiples

I'm having some trouble getting the correct output format for my homework. Here it is:
Write a program that accepts an integer n and an integer m from user and that prints a
complete line of output reporting the first m multiples of n. For example, if user input is:
m = 5, n = 3;
It should produce this output:
The first 5 multiples of 3 are 3, 6, 9, 12, and 15.
This is what I have so far:
import java.util.*;
public class Assignment2Part3 {
public static void main (String[] args) {
//declaring the two variables being entered
int n = 0;
int m = 0;
//declaring answer variable
int a = 0;
//declaring scanner input
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number you want to find multiples of");
n = input.nextInt();
while(true) {
System.out.println("Please enter the amount of multiples you want to see");
m = input.nextInt();
if (m <= 0) {
System.out.println("Please enter an integer greater than zero");
}
if (m > 0) {
break;
}
}
System.out.println("The first "+n+ " multiples of "+m+" are: ");
for (int i=1; i<=m; i++) {
a =i*n;
System.out.println(a);
}
}
}
This is what the output looks like right now:
Please enter the number you want to find multiples of
3
Please enter the amount of multiples you want to see
5
The first 3 multiples of 5 are:
3
6
9
12
15
How do I get the output to look like "The first 5 multiples of 3 are 3, 6, 9, 12, and 15." ?
NOTE: This assignment is for an introductory course and we have just covered for loops.
Printing them out on one line.
By changing System.out.println to System.out.print you can make multiple prints display on the same line.You also need to print a separator (", ") before every number (except the first), so that the numbers don't just pile up on top of each other.
Before the last number, you want to print "and".
You can do by altering the behaviour when the loop is at the final step (which is when i==m).
This gives something like this:
System.out.println("The first "+m+ " multiples of "+n+" are: ");
for (int i = 1; i <= m; ++i) {
if (i > 1) {
System.out.print(", ");
if (i==m) {
System.out.print("and ");
}
}
System.out.print(i*n);
}
System.out.println(".");

My logical program is not giving the correct output?

Question:
The Utopian tree goes through 2 cycles of growth every year. The first growth cycle occurs during the spring, when it doubles in height. The second growth cycle occurs during the summer, when its height increases by 1 meter.
Now, a new Utopian tree sapling is planted at the onset of the spring. Its height is 1 meter. Can you find the height of the tree after N growth cycles?
Input Format
The first line contains an integer, T, the number of test cases.
T lines follow. Each line contains an integer, N, that denotes the number of cycles for that test case.
Constraints
1 <= T <= 10
0 <= N <= 60
Output Format
For each test case, print the height of the Utopian tree after N cycles.
//FINALLY, HOPE so .. WHAT QUESTION IS SAYING..
INITIALLY VALUE IS 1 .. IF SPRING OCCURS.. IT'S VALUE WILL BE DOUBLED.. THAT MEANS .. IT WILL BE MULTIPLIED BY 2.. BUT IF SUMMER OCCUR IT'S VALUE WILL BE ADDED BY 1...
If i give input:
2 //here 2 is the number of question..
0
1
So, Output must be:
1
2
Another example,
sample of output:
2
3
4
So, Sample of input will be:
6
7
HOPE SO.. YOU UNDERSTAND WHAT QUESTION IS ASKING, HERE NOW WE HAVE TO MAKE A PROGRAM INTO JAVA....
Okay as further i made a program for this..
package com.logical03;
import java.util.Scanner;
public class MainProgram{
public static void main(String[] args){
int num=1;
int[] array=new int[100];
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements=in.nextInt();
System.out.println("Enter the values now: ");
for(int i=1; i<=n_Elements; i++){
array[i]=in.nextInt();
}
for(int i=1; i<=n_Elements; i++){
if(array[i]==0){
System.out.println("\n1");
}
else{
for(int j=1; j<=array[i]; j++){
if(j%2!=0){
num=num*2;
}
else{
num=num+1;
}
}
System.out.println(num);
}
}
}
}
As i run into here .. it adds the second number of question into my output.. Suppose..
If i give input as:
2
3
4
So, output must suppose to be:
6
7
Which is correct!!
But My program gives the output as:
6
27 //which is incorrect..becoz it adds the sum of above number :(
Mistake - int num = 1; should be declared in inside parent loop to refresh it's value.
public static void main(String[] args) {
int[] array = new int[100];
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements = in.nextInt();
System.out.println("Enter the values now: ");
for (int i = 1 ; i <= n_Elements ; i++) {
array[i] = in.nextInt();
}
for (int i = 1 ; i <= n_Elements ; i++) {
int num = 1;
if (array[i] == 0) {
System.out.println("\n1");
} else {
for (int j = 1 ; j <= array[i] ; j++) {
if (j % 2 != 0) {
num = num * 2;
} else {
num = num + 1;
}
}
System.out.println(num);
}
}
}
Output
Enter the number of Questions:
2
Enter the values now:
3
4
6
7
My approach is to take on account that first cycle (2 * height) occurs on odds indexes, and second cicle (1 + height) occurs on even indexes, from 1 to n (inclusive), starting index 0 is always 1.
return IntStream.rangeClosed(1, n)
.reduce(1, (acc, idx) -> idx % 2 != 0 ? acc * 2 : acc + 1);
This is my first contribution, only learning to code and solve algorithms, I had to find a workable solution with simple to follow code credit to http://www.javainterview.net/HackerRank/utopian-tree
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
//receive input
Scanner in = new Scanner(System.in);
//no of test cases
int T=in.nextInt();
//no of cycles
int[] N = new int[T];
for(int i=0;i<T;i++){
N[i]=in.nextInt();
}
int height=1;
for(int i=0;i<N.length;i++){
height=1;
for(int j=1;j<=N[i];j++){
if((j%2) ==1)
height=height*2;
else
height++;
}
System.out.println(height);
}
}
}//this the end of the class

Categories