Divide by two while loop in java - java

what I'm trying to do is use a while loop to check userNum % 2 > 1 once it hits one i want it to stop and print out all the values of the division so for example
if 20 is user num it would generate. 20 / 2 and 10/ 2 and 5/2 and then 2/2 resulting in 1 and then stopping
(integer division)
import java.util.Scanner;
public class DivideByTwoLoop {
public static void main (String [] args) {
int userNum = 0;
userNum = 20;
while ( (userNum % 2) > 1){
userNum = userNum / 2;
System.out.println(userNum );
}
System.out.println("");
return;
}
}
thats what I have so far.
any help is greatly appreciated.

userNum % 2 is always either 1 or 0, so the condition of the while-loop is never true. The condition should be userNum > 1 instead of (userNum % 2) > 1.

Related

How to break the execution of the code based on a user input

So I am doing a digit counter thing basically
I want it to display 123 and which number is what place value for example 123
------------------------------------
Enter any number: 123
Ones: 3
Tens: 2
Hundreds: 1
------------------------------------
this is my code
import java.util.Scanner;
public class digits {
public static void main(String[] args)
{
Scanner scann = new Scanner(System.in);
System.out.print("Enter any number: ");
int number = scann.nextInt();
int num1 = number % 10;
int num2 = number / 10 % 10;
int num3 = number / 100 % 10;
int num4 = number / 1000 % 10;
int num5 = number / 10000 % 10;
int num6 = number / 100000 % 10;
int num7 = number / 1000000 % 10;
int num8 = number / 10000000 % 10;
scann.close();
System.out.println("Ones: "+num1);
System.out.println("Tens: "+num2);
System.out.println("Hundreds: "+num3);
System.out.println("Thousands: "+num4);
System.out.println("Ten-Thousands: "+num5);
System.out.println("Hundred-Thousands: "+num6);
System.out.println("Millions: "+num7);
System.out.println("Ten-Millions: "+num8);
}
}
How do I stop it from printing the rest if I only type 123?
Output I got
--------------------------
Enter any number: 123
Ones: 3
Tens: 2
Hundreds: 1
Thousands: 0
Ten-Thousands: 0
Hundred-Thousands: 0
Millions: 0
Ten-Millions: 0
------------------------
Output I want
--------------------------
Enter any number: 123
Ones: 3
Tens: 2
Hundreds: 1
------------------------
You need to introduce a condition (or conditions) in your code.
You can achieve that with a chain of if statements. But the better way to do it is by utilizing a loop. Because that will allow you to get rid of the intermediate variables (num1, num2, etc) and to avoid duplicating the line of code that prints the remainder on the consol. That will make the code more readable and concise.
In order to be able to apply the loop for this problem, you need to create an array of strings that will store all quantifiers ("Ones: ", "Tens: ", etc).
It can be done like that:
public static final String[] quantifiers =
{"Ones: ", "Tens: ", "Hundreds: ", "Thousands: ",
"Ten-Thousands: ", "Hundred-Thousands: ", "Millions: ", "Ten-Millions: "};
public static void main(String[] args) {
Scanner scann = new Scanner(System.in);
int number = scann.nextInt();
for (int i = 0; i < quantifiers.length && number > 0; i++) {
System.out.println(quantifiers[i] + number % 10);
number /= 10; // does the same as number = number / 10;
}
}
output for input 123
Ones: 3
Tens: 2
Hundreds: 1
It might help your question. Because of hardcoded terms such as 'tens' or 'hundreds', it is not generic enough.
public static void main(String[] args) {
Scanner scann = new Scanner(System.in);
System.out.print("Enter any number: ");
int number = scann.nextInt();
int length = String.valueOf(number).length();
for(int i=0; i< length; i++){
if(i == 0){
System.out.println("Ones: "+ number % 10);
}else if(i == 1)
System.out.println("Tens: " + number / 10 % 10);
else if(i == 2)
System.out.println("Hundreds: "+ number / 100 % 10);
else if(i == 3)
System.out.println("Thousands: "+ number / 1000 % 10);
else if(i == 4)
System.out.println("Ten-Thousands: "+ number / 10000 % 10);
else if(i == 5)
System.out.println("Hundred-Thousands: "+ number / 100000 % 10);
else if(i == 6)
System.out.println("Millions: "+ number / 1000000 % 10);
else if(i == 7)
System.out.println("Ten-Millions: " + number / 10000000 % 10);
}
scann.close();
}
Your code is printing all the numbers because that's what you wrote:
System.out.println("Ones: "+num1);
...and so on.
If you never want to print e.g. thousands, just remove the println for thousands. If you only want to print them if someone actually enters thousands, add an if statement:
if (num4 > 0) {
System.out.println("Thousands: "+num4);
}
Repeat for the others.

How can I make it so my while-loop only prints even numbers? Java Eclipse IDE

Beginner here. For my coding class, we have an assignment that requires us to print numbers 1-20, but configure it so that it only outputs even numbers. Here is what I have so far but I'm quite stuck. He says to put an if statement and use the "%" operator but I've no idea where to put them.
int counter = 1;
System.out.println("Part 2 - Even Numbers");
while (counter <= 20)
{
//if (counter
System.out.printf("%d ", counter);
counter++;
} // end while loop
Instructions for assignment
My Output
CORRECT Output
if(counter % 2 == 0){
System.out.printf("%d ", counter);
}
counter++;
% operator is mod operator, if counter % 2 == 0 , then counter is an even number
% is an arithmetic operator, it is called MODULO.
Modulo operator returns the remainder of 2 numbers. In this case, we use a modulo to find out whether a number is even or odd.
odd%2 returns 1
even%2 returns 0
The while loop loops through the first 20 elements. So we put an if statement before printing the element. If the counter is an even number i.e (counter%2 == 0) we print that.
This is the code that prints even numbers:
int counter = 0;
System.out.println("Part 2 - Even Numbers");
while (counter <= 20)
{
if (counter%2 == 0){
System.out.printf("%d ", counter);
}
counter++;
} // end while loop
This can also be done without using MODULO operator:
int counter = 0;
System.out.println("Part 2 - Even Numbers");
while (counter <= 20)
{
System.out.printf("%d ", counter);
counter+=2;
} // end while loop
use fori
public static void main(String[] args) {
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
}
% is the remainder operation

How to swap numbers in while loop java

import java.util.Scanner;
public class Swap {
// if the number is less than 10, swap the last two numbers and print them.
public static void main(String[] args) {
// User to enter a number between 1 and 10, but not zero.
Scanner number = new Scanner(System. in );
System.out.println("Enter a Integer(whole number) between 1 and 10. : ");
int userNum = number.nextInt();
while (userNum > 10 || userNum < 0) {
System.out.println("Try again: ");
userNum = number.nextInt();
}
System.out.println("Your number loop");
while (userNum <= 10) {
System.out.println(userNum);
userNum++;
}
System.out.println("Guess the two swap numbers:");
}
}
How do I swap the last two numbers? I am a beginner learning java and OOP. I have created this program where the user has to enter a number between 1 and 10. If the user enters a number below 1 and above 10, the user gets prompted to try again. Then it prints the list of numbers based off the users input. e.g. if the user enters 8, its prints the loop 8,9 and 10. I have having trouble, I understand how to swap two variable, not inside a loop. Thank you and much appreciated for your help.
Let's assume that the maximum number is a parameter N, so that you could swap any last two numbers and place N before N - 1
private static final int N = 10;
There are several ways to do this using different Java operators:
if, to update delta parameter
while (userNum <= N) {
int delta = 0;
if (userNum >= N - 1) {
delta = userNum == N - 1 ? 1 : -1;
}
System.out.println(userNum + delta);
userNum++;
}
or simply skip N - 1 and print it after the loop:
while (userNum <= N) {
if (userNum != N - 1) {
System.out.println(userNum);
}
userNum++;
}
System.out.println(N - 1);
switch
while (userNum <= N) {
int printNum = userNum++;
switch(printNum) {
case N:
printNum--; break;
case N - 1:
printNum++; break;
default:
break;
}
System.out.println(printNum);
}
two consequent loops (the second going backwards):
while (userNum < N - 1) {
System.out.println(userNum++);
}
userNum++;
while (userNum >= N - 1) {
System.out.println(userNum--);
}
another way this can be solved is by creating a loop(for or while) and taking the two numbers you can use the math functions- Math.max(a,b) || Math.min(a,b) to find the biggest and smallest numbers. Afterwards you can create more variables- c&d to save the two numbers.
goodluck
a=max
b=min
then
c=a
d=b;
then a=d and b=c.

How can I make a while loop print userNum = 1 with whitespace after it?

My assignment (an intro to Java course from Zybooks) says to: "Write a while loop that prints userNum divided by 2 (integer division) until reaching 1. Follow each number by a space. Example output for userNum = 20:
20 10 5 2 1
Note: This activity will perform four tests, with userNum = 20, then with userNum = 1, then with userNum = 0, then with userNum = -1."
I can get it to print "20 10 5 2 1 ", but when I successfully add a whitespace to the end of the above sequence of numbers, it doesn't add white space to 1 when userNum = 1. Example: "1" instead of "1 " for userNum = 1. I am just focusing on 1 for now and 0 and -1 later. Also the commented out while loop below just runs an infinite loop but I thought it would be useful to add it in anyways, sorry for the confusion. Here is my code so far, thank you very much in advance:
import java.util.Scanner;
public class DivideByTwo {
public static void main (String [] args) {
int userNum = 0;
userNum = 20;
System.out.print(userNum);
while (userNum > 1) {
System.out.print(" " + (userNum/2));
userNum = userNum/2;
if (userNum == 1) {
System.out.print(" ");
}
}
/* while (userNum <= 1) {
System.out.print(" ");
userNum = userNum + 1;
}*/
System.out.println("");
return;
}
}
You can move this block of yours out of the while loop -
} // end of the while loop
if (userNum == 1) {
System.out.print(" ");
}
Alternatively, you don't need the if there, while (userNum > 1) ensures that check is taken care of.
To make use of your existing code, change as --
while (userNum > 1) {
System.out.print(" " + (userNum/2));
userNum = userNum/2;
}
System.out.println(" ");
After working on this beginner program for 5 days, I finally found the solution. It first checks if userNum is greater than or equal to 1 (so if it's -1 or 0 (-1/2, 0/2, nothing gets printed), then prints out the original userNum value (20, 1, etc..). It then adds this value to a space, the process repeats and it then prints the new userNum value (userNum/2). The while loop makes this process repeat until the value is no longer >= 1. It finally ends and prints a newline. Much simpler than my original thought:
while (userNum >= 1) {
System.out.print(userNum + " ");
userNum = userNum / 2;
}
System.out.println("");
return;
public class DivideByTwo {
public static void main (String [] args) {
int userNum = 20;
while (userNum >= 1) {
System.out.print(userNum+" ");
userNum = userNum/2;
}
return;
}
}
If you hard set the userNum to 20, there's no need to declare it and then assign a value, you can just do it in the same line.
So the change:
If you change the while loop to check (userNum >= 1) the loop will include the number 1 in it's operations (If I'm not mistaken Java will round down integer devisions).
So what will happen is that it will see that userNum is larger or equal to 1, then print userNum and a space until the value is less than 1.
This should output the string you're after.
If however it does continually output a string of 1 1 1 1 1 1 1 1 at the end you can make use of the floor() function to make sure it rounds down.
This while loop should do the trick and it's pretty simple.
while(true){
System.out.print(number + " ");
number = number / 2;
if(number==1){
break;
}
}
You're using the wrong kind of loop; a for loop is more sppropriate than a while loop. Your code can just be:
System.out.print(userNum)
for (;userNum > 1; userNum /= 2)
System.out.print(" " + usernum);

Java not reading "&&" statements properly?

I'm having a problem with my Java code. Specifically, one of my if statements containing an && is not returning True for certain inputs like I expect it to.
The snippet in question:
if (num%2==1 && num < 0) { //why is not reading this statement?
negodd ++;
}
Sample inputs and outputs vs expected outputs:
Enter any number to continue. Enter 0 to stop :
1
2
-2
-1
0 // not counted as a number since it is a stop function.
Output of my code. What it should be.
You Entered 4 numbers : You Entered 4 numbers :
1 negative even 1 negative even
1 positive even 1 positive even
0 negative odd 1 negative odd <--should read the 1
1 positive odd 1 positive odd
The full code in case that helps:
import java.util.Scanner;
public class stupid {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
int num = 0;
int negodd = 0, count = 0, posseven = 0;
int possodd = 0; int negeven=0;
System.out.println("Enter any number to continue. Enter 0 to stop : ");
num = x.nextInt();
if(num==0){
System.out.print("You immediately stop");
System.exit(0);
}
while (num != 0) {
count ++;
if (num%2==1 && num > 0) {
possodd ++;
}
if (num%2==1 && num < 0) { //why is not reading this statement?
negodd ++;
}
if (num%2==0 && num > 0) {
posseven ++;
}
if (num%2==0 && num < 0) {
negeven++;
}
num = x.nextInt();
}
System.out.printf("You Entered %d numbers\n",count);
System.out.printf("%d negative even \n",negeven);
System.out.printf("%d positive even\n",posseven);
System.out.printf("%d negative odd\n",negodd);
System.out.printf("%d positive odd\n",possodd);
}
}
Thanks in advance!
Using the modulo operator with negative numbers gives you a different result than you might think.
1 % 2 == 1
2 % 2 == 0
-2 % 2 == 0
-1 % 2 == -1
To get the result you want, you can replace your modulo tests with num % 2 == 0 and num % 2 != 0.
1 % 2 == 1
2 % 2 == 0
-2 % 2 == 0
-1 % 2 == -1
Here, -1%2 does not results in 1. Hence, it will not increment value of negodd variable.
In JAVA, negative number modulo will give same result as positive number modulo but with a negative sign. 0 is neutral thus it will not have any sign.
-1 % 2 is going to return -1, not 1, where -2 % 2 will give a result of 0.

Categories

Resources