This question already has answers here:
Understanding how recursive functions work
(18 answers)
Closed 7 years ago.
For the following method, when mystery(45) is called, the output is "1 0 1 1 0 : 2 5 11 22 45". I understand why "1 0 1 1 0 :" is printed out, but don't understand how "2 5 11 22 45" is printed out after the colon. Can someone explain this to me? I've tried writing it out, but I just could not figure it out.
public static void mystery (int n) {
if (n <= 1) {
System.out.print(": ");}
else {
System.out.print((n % 2) + " ");
mystery (n/2);
System.out.print(n + " ");
}
}
It's recursive, so the calling looks something like this.
System.out.print((45 % 2) + " ");
System.out.print((22 % 2) + " ");
System.out.print((11 % 2) + " ");
System.out.print((5 % 2) + " ");
System.out.print((2 % 2) + " ");
mystery (2 / 2); <-- won't recurse anymore, will just print :
System.out.print(2 + " ");
System.out.print(5 + " ");
System.out.print(11 + " ");
System.out.print(22 + " ");
System.out.print(45 + " ");
Related
This question already has answers here:
How do I concatenate two strings in Java?
(23 answers)
Closed 8 months ago.
New to Java.
Does anyone know how I can print the following output:
The sum of the digits is 3 + 0 + 4 + 5 + 8 = 20
This is my print line:
System.out.print("The sum of the digits is: " + num1 + num2 + num3 + num4 + num5 + sum);
I want to get the + sign to display, but for some reason I get errors.
Any assistance is appreciated.
There is a difference between + and "+". The first is used to combine Strings in this case and the second is a String with the value of a plus sign.
So a simple plus in a String would look like this:
num1 + " + " + num2 + " = " + solution
Java
int x = 5;
System.out.println(" x + 5 is " + x + 5);//correct
System.out.println("x += 5 is " + x += 5);// why wrong?
Even though, these 2 println is including calculation but why second println is error.Thanks
What you are doing causes an error because the + is seen as an operator to seperate parts of the string. Try placing that part between brackets like:
System.out.println("x += 5 is " + (x += 5));
This might fix it as you exclude the + from the string. Hope this helps you a bit, and that I am correct in my statement.
I need to print the factors of a perfect number. Here's the gist of my main class:
ArrayList<Integer> perfNums = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.print("Enter the upperbound: ");
upperbound = in.nextInt();
for (int i = 1; i <= upperbound; i++) {
if (isPerfect(i)) { //boolean to check if number is a perfect number
perfNums.add(i);
}
}
System.out.println("Perfect numbers between 1 and " + upperbound + " are:");
for (int i = 0; i < perfNums.size(); i++) {
System.out.print(perfNums.get(i) + " = ");
printFactor((int)perfNums.get(i));
System.out.println();
}
Here's the printFactor class.
private static void printFactor(int number){
int factor = 1;
while(factor < number){
if (number%factor == 0) System.out.print(factor+ " + ");
//I don't know how to print the + sign otherwise.
factor++;
}
}
And here's a sample output:
Enter the upperbound: 10000
Perfect numbers between 1 and 10000 are:
6 = 1 + 2 + 3 +
28 = 1 + 2 + 4 + 7 + 14 +
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248 +
8128 = 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064 +
I've got the main gist of it but I've struggled with an output issue. Due to the restrictions of my online submission system, my output needs to fit exact specifications.
My question is how do I go about printing all the factors of my perfect number but removing the + sign at the end? (e.g)6 = 1 + 2 + 3
I'm not too sure of many methods to print from a while loop. Would a for-loop be better for my goals? Or are there alternative methods to print the factors of a number?
The least amount of change to address this might be something like this:
private static void printFactor(int number)
System.out.print(1);
int factor = 2;
while (factor<number) {
if (number%factor == 0) System.out.print(" + " + factor);
factor++;
}
}
1 is always a factor, so you can print that before the loop and then prepend + to every subsequent factor.
You should cache the output you want to print into a StringBuilder. Then you are able to remove the last plus sign before you print the whole String. It also has a better performance.
private static void printFactor(int number)
{
StringBuilder output = new StringBuilder();
int factor = 1;
while (factor < number)
{
if (number % factor == 0)
output.append(factor + " + ");
factor++;
}
// remove last plus sign
output.deleteCharAt(output.length() - 1);
// print the whole string
System.out.print(output.toString());
}
Since factor starts from value 1 and number % 1 == 0 will always be true, you might print 1 first and then flip factor and + in System.out.print. Like this:
private static void printFactor(int number) {
if(number > 0) {
System.out.print(1);
}
int factor = 2;
while (factor<number) {
if (number % factor == 0) {
System.out.print(" + " + factor);
}
factor++;
}
}
Not the best solution, but it will do the job.
Try to create a variable String numb and use substring method like this:
String numb ="";
while(factor<number){
if(number%factor == 0)
numb= numb + factor+ " + ";
factor++;
}
System.out.print(numb.substring(0, numb.trim().length()-1));
Just for the sake of using Java 8 :)
private static void printFactor(int number){
System.out.println(IntStream.range(1, number)
.filter(p -> number % p == 0)
.mapToObj(i -> String.valueOf(i))
.collect(Collectors.joining(" + ")));
}
Thanks everyone for the quick response. You all have been a lifesaver, and I managed to pick up some new things to consider when I code in the future.
Anyway, while waiting for a reply I was fiddling with the code and came up with a rather inelegant solution, if anybody's interested. Here's the changes to the main class:
System.out.println("Perfect numbers between 1 and " + upperbound + " are:");
for(int i=0; i<perfNums.size(); i++){
System.out.print(perfNums.get(i) + " = ");
outputString = printFactor2(perfNums.get(i));
if(outStr.endsWith(" + ")) outStr = outStr.substring(0, outStr.length()-3);
//because the submission system would cry foul with even a single extra space
System.out.println(outStr);
}
And here's the changes to the printFactor class:
private static String printFactor2(int number){
String out = "";
int factor = 1;
while(factor<number){
if(number%factor == 0) out += factor + " + ";
factor++;
}
return out;
}
Basically, what I did was append the factors to a string, then removing the trailing + sign using the substring method. On hindsight, I probably should've called the substring method inside the printFactor class instead. Something like return out.substring(0, out.length()-3); perhaps?
Nevertheless, thanks everyone!
I have an assignment to write a code that ask you for 10 seats (some are taken and some are empty) and you need to get a seat, check if it is available and if not find the closest seat that is empty.
Some times my code works, but most of the time it doesn't. Can someone help me?
import java.util.Scanner;
public class Main {
static Scanner reader = new Scanner(System. in );
public static void main(String[] args) {
int mult = 1;
int[] manage = new int[10];
System.out.println(" 0- empty 1-taken ");
for (int i = 0; i < 10; i++) {
System.out.println("enter the " + (i + 1) + " place");
manage[i] = reader.nextInt();
}
int a = 0, check = 0;
System.out.println("What the place you want to seat in?: ");
a = (reader.nextInt()) + 1;
System.out.println("checking...");
while (check != 5) {
if (manage[a] == 0) {
System.out.println(" your seat is in the " + a + " place");
check = 5;
} else if (manage[a - mult] == 0) {
System.out.println(" your seat is in the " + ((a - mult) + 1) + " place");
check = 5;
} else if (manage[a + mult] == 0) {
System.out.println(" your seat is in the " + ((a + mult) + 1) + " place");
check = 5;
} else {
mult++;
}
}
}
}
I think what you want for this line is
a = (reader.nextInt()) - 1;
instead of
a = (reader.nextInt()) + 1;
Since you are always displaying the 'actual index + 1' for all your outputs, i.e.
The user deals with 1 - 10 and not 0 - 9?
Note: manage[a - mult] and manage[a + mult] can throw ArrayIndexOutOfBoundsException if the value is < 0 or the value is >= array length.
Note #2: In the else clause, once mult is >= array length, you can break out of the loop. If you do not add that in, the loop will keep repeating if all the seats are taken right from the start.
So, add a check before accessing that array index, as shown here:
if (manage[a] == 0) {
System.out.println("Your seat is in the " + a + " place");
check = 5;
} else if ( a - mult >= 0 && manage[a - mult] == 0) {
System.out.println("Your seat is in the " + ((a - mult) + 1)
+ " place");
check = 5;
} else if (a + mult < manage.length && manage[a + mult] == 0) {
System.out.println("Your seat is in the " + ((a + mult) + 1)
+ " place");
check = 5;
} else {
mult++;
// Check is necessary here, infinite loop if all seats are taken!
if(mult >= manage.length) {
System.out.println("All seats taken!");
break;
}
}
Input/Output (after making the change):
0 - Empty 1 - Taken
Enter the 1 place: 0
Enter the 2 place: 0
Enter the 3 place: 1
Enter the 4 place: 1
Enter the 5 place: 1
Enter the 6 place: 1
Enter the 7 place: 1
Enter the 8 place: 1
Enter the 9 place: 1
Enter the 10 place: 1
What is the place you want to sit in?: 10
checking...
Your seat is in the 2 place
0 - Empty 1 - Taken
Enter the 1 place: 1
Enter the 2 place: 1
Enter the 3 place: 1
Enter the 4 place: 1
Enter the 5 place: 0
Enter the 6 place: 1
Enter the 7 place: 1
Enter the 8 place: 1
Enter the 9 place: 0
Enter the 10 place: 1
What is the place you want to sit in?: 1
checking...
Your seat is in the 5 place
In the above example, user enters 10, but your program checks for array index 9.Array index 9 is taken, so you check array index 8 (9-1), which is empty, and tells the user that seat #9 is his seat.
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 8 years ago.
Improve this question
What I'm trying to do is print the results in increments of 5 - DONE. Then, print only the last line of the loop. For ex: if z=26, print results of z # 5, 10, 15, 20, 25. Then println with z # 26. I'm stuck and can't figure it out.
for (int i = 1; i <= z; i++) {
b = b + (b * y) + x + w;
if (i % 5 == 0)
//input 1
System.out.println("In " + i + " years, IRA value: " + b);
//input 2 - value of IRA when retirement is reached
System.out.println();
I don't know what initial values b, x, w and y got so I just initialized them somehow ..
But I think you want something like this:
public class HelloWorld{
public static void main(String []args){
int z = 26;
int b = 0;
int x = 1;
int w = 2;
int y = 1;
for (int i = 1;i<=z;i++) {
b = b+(b*y)+x+w;
if (i % 5 == 0)
System.out.println("In " + i + " years, IRA value: " + b);
}
System.out.print(z);
}
}
Output:
In 5 years, IRA value: 93
In 10 years, IRA value: 3069
In 15 years, IRA value: 98301
In 20 years, IRA value: 3145725
In 25 years, IRA value: 100663293
26
Change your condition to
if(i%5==0 || i==z)
Adding an or (|| i==z) in the if will do the work
for (int i = 1;i<=z;i++) {
b = b+(b*y)+x+w;
if (i%5==0 || i==z)
//input 1
System.out.println("In " + i + " years, IRA value: " + b);
//input 2 - value of IRA when retirement is reached
System.out.println();
//end
}