How to swap numbers in while loop java - 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.

Related

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);

How to get do-while statement to loop infinitely with nested if statment

I am having a user enter in a multiple of 3 between 3 and 24 inclusive. The output then prints out the number less 3 until it reaches 0. Ex the user picks 15. The output prints out 15,12,9,6,3,0. The problem is if the user picks the number 17 it rounds it down to 15 and proceeds to do the rest of the code. How do I make it repeat the input infinitely if they do not enter in a multiple of 3? My code is as follows.
do{
System.out.print("Enter a multiple of 3: ");
//We use the variable n to hold the multiple of 3, like the heading says to do.
n = input.nextInt();
if (n % 3 !=0 || n >= 25) {
System.out.println("Error: Enter a multiple of 3 between 3 and 24, inclusive.");
n = input.nextInt();
}
/**
* X = n /3, this gives us the base number of the multiple of 3 to use and figure out the
* values of n->0 by 3's.
*/
for(x = n / 3; x <= 8 && x >=0; x--){
int three = 3 * x;
System.out.printf(three + "\t");
}
}while(x >= 0);
As you can see I just put another input section within the if statement, however I do not wish to do this. I am trying to figure out a way for the if statement to keep looping. Is it my parameters I set up on my if statement? Or is there a specific command to make the if statement repeat if the criteria of the statement is not met? Also I am using Java.
You can use a separate loop to initialize n. (I'm not sure what your outer loop is for, so I deleted it.)
int n;
while (true) {
System.out.print("Enter a multiple of 3: ");
n = input.nextInt();
// Validate input.
if (n % 3 == 0 && n < 25 && n > 0) {
// Input is good.
break;
}
// Input is bad. Continue looping.
System.out.println("Error: Enter a multiple of 3 between 3 and 24, inclusive.");
}
for (x = n / 3; x <= 8; x--) {
int three = 3 * x;
System.out.printf(three + "\t");
}
The if--break pattern is necessary because you need to check the looping condition in the middle of the loop, rather than the beginning or end.
If you don't like the while(true) { ... break; ... } then you can use a do { ... } while (flag); loop instead. A do/while loop is common when you want to do something 1 or more times - specifically at least once and you aren't sure how many times.
For example
boolean keepGoing = true;
do {
System.out.println("Enter a multiple of 3 between 3 and 24: ");
n = input.nextInt();
keepGoing = (n < 3 || 24 < n || n % 3 != 0);
} while (keepGoing);
System.out.println("You entered: " + n);
Or this variation
boolean done = true;
do {
System.out.println("Enter a multiple of 3 between 3 and 24: ");
n = input.nextInt();
done = (3 <= n && n <= 24 && n % 3 == 0);
} while (!done);
System.out.println("You entered: " + n);

Run loop an extra time if one of the inputs is bad

I have a for-loop which asks for scores between 0 and 10. It asks a certain amount depending on the number of judges.
Here's the code:
System.out.println("Number of judges: ");
int numOfJudges = IO.readInt();
int sum = 0;
for (int i=0; i<numOfJudges; i++) {
System.out.print("Enter judge's score: ");
int score = IO.readInt();
if (score >= 0 && score <= 10) {
sum += score;
} else {
System.out.println("Incorrect number, must be between 0 and 10.");
}
}
System.out.println(sum);
I want to make is so if a number is entered that's not between 0 and 10, it won't count that as one of the conditions as i < numOfJudges.
For example if I have 3 judges and I enter 2 wrong inputs, it will still only run the loop 3 times (and only take the good input into account) while I really want it to run 5 times to make up for the two incorrect inputs.
Increment numOfJudges in case of ELSE condition so that your FOR loop would run until you have desired number of correct inputs.
This is shortest and cleanest solution.
else {
System.out.println("Incorrect number, must be between 0 and 10.");
numOfJudges++;
}
You can use a while loop inside of the for-loop, instead of adjusting the for-loop:
for (int i=0; i<numOfJudges; i++) {
while(true){
System.out.print("Enter judge's score: ");
int score = IO.readInt();
if (score >= 0 && score <= 10) {
sum += score;
break; //jump out of while-loop
}else {
System.out.println("Incorrect number, must be between 0 and 10.");
}
}
}
System.out.println(sum);

How to correct my prime factorization program?

Here is my program for outputting prime factorization of a given number. I am still just a beginner in java so I know it is not the most efficient code. The problem arises when I input relatively big numbers.
Input: 11 Output: 11
Input: 40 Output: 2 2 2 5
Input: 5427 Output: 3 3 3 3 67
Input: 435843 Output: 3 3 79 613
Input: 23456789 Output: none (there appears to be an infinite loop and the code should return 23456789 since it is a prime number on its own)
What might cause this issue?
import java.util.Scanner;
public class PrimeFactorization {
public static boolean isPrime(long n) {
boolean boo = false;
long counter = 0;
if (n == 1) {
boo = false;
} else if (n == 2) {
boo = true;
} else {
for (long i = 2; i < n; i++) {
if (n % i == 0) {
counter++;
}
}
if (counter == 0) {
boo = true;
}
}
return boo;
}
public static void primeFactorization(long num) {
for (long j = 1; j <= num; j++) {
if (isPrime(j)) {
if (num % j == 0) {
while (num % j == 0) {
System.out.printf(j + " ");
num = num / j;
}
}
}
if (num == 1) {
break;
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter any number:");
long num = scanner.nextLong();
System.out.print("Prime factorization of your number is: ");
primeFactorization(num);
scanner.close();
}
}
There's no actual error - you're just doing things a very inefficient way. Basically, you're checking every number between 1 and 23456789 for primeness, before dividing.
There's absolutely no point in doing this check. As you work your way up from 1 to 23456789, each time you uncover a factor, you know it has to be prime, because you've already divided out all smaller factors. So if you do all of the following, this will still work correctly, and much more quickly.
Remove the isPrime method completely.
Remove the line if (isPrime(j)) {, and the matching }
Change the loop so that j starts at 2, like for(long j = 2 ; j <= num ; j++) {
Remove if (num == 1) { break; } from the end of the loop. It serves no purpose at all.
No matter how efficient the code, factorizing large numbers takes a while - so long it may feel like the computer has hung. Given your code, even modestly large numbers will take a long time.
The main thing you can do to improve your code's efficiency to to note that for any pair of factors of a number, one of them will be no more than the square root of the number. You can use this fact to limit the loop to reduce the order of you algorithm for O(n) to O(log n).
long sqrt = Math.sqrt(number);
for (long i = 2; i < sqrt; i++) {
...
There are many other things you can do, but this change will have the greatest effect.
If number changes value during the loop (as for example in your second factorizing loop), you'll if course need to recalculate the end value:
for (...)
// if number changes
sqrt = Math.sqrt(number);

Better way of calculating sum of even ints

I'm trying to write a programme to prompt the user to input an int which is above or equal 2. From this input the programme must then calculate and print the sum of all the even integers between 2 and the entered int. It must also produce an error message if the inputted int is below 2. I've made a programme for it that works but am just wondering if you guys could find a better way of doing it? I'm sure there is but I can't quite seem to find a way that works!
Here's what I did:
import java.util.Scanner;
public class EvenSum {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer which is above 2.");
int number = scan.nextInt();
int divnum = number / 2;
int divnum2 = divnum + 1;
int sumofeven = divnum * divnum2;
if(number >= 2)
System.out.println("The sum of the even integers between the number is "+
sumofeven);
else
System.out.println("Invalid number entered.");
}
}
Note: do not use this example in a real context, it's not effective. It just shows a more clean way of doing it.
// Check the input.
if (number >= 2)
System.out.println(sum(number));
}
// Will find the sum if the number is greater than 2.
int sum(int n) {
return n == 2 ? n - 2 : n % 2 == 0 ? n + sum(n - 2) : sum(n - 1);
}
Hope this helps. Oh, by the way, the method sum adds the numbers recursively.
Sorry, but I had to edit the answer a bit. There might still be room for improvement.
Why do it with a loop? You can actually calculate it out. Let X be the number they choose. Let N be the largest even number <= X. (N^2+2*N)/4 will be your answer.
Edit: just saw the answer above me. He is right. I gave the function I suppose.
Why use a loop at all? You are computing the sum of:
2 + 4 + ... n, where n is a positive even number.
This is a very simple arithmetic progression.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer which is above 2.");
int number = scan.nextInt();
if (number >= 2) {
int sumofeven = 0;
for (int i = 2; i <= number; i += 2) {
sumofeven += i;
}
System.out.println("The sum of the even integers between the number is " + sumofeven);
} else {
System.out.println("Invalid number entered.");
}
}

Categories

Resources