I need to figure out how to get this result:
I got this but how to put result from 2nd loop in new line?
public class Main04 {
public static void main(String[] args) {
int w = 1;
while (w <= 10) {
System.out.print( w " ");
w ;
}
for ( int f = 1; f<=10; f )
System.out.print( f " ");
}
}
CodePudding user response:
Simply call System.out.println
to print a delimiting newline after the first loop:
public class Main04 {
public static void main(String[] args) {
int w = 1;
while (w <= 10) {
System.out.print( w " ");
w ;
}
System.out.println(); // print delimiting newline
for ( int f = 1; f<=10; f )
System.out.print( f " ");
}
}
Note: Currently your code will add a trailing space after the last number.
CodePudding user response:
As a slightly different approach: rather than printing each term separately, collect them in an array, and then just print each array on its own line using the Arrays.toString(...) method from java.utils.Arrays
:
import java.util.Arrays;
public class Main04 {
public static void main(String[] args) {
// we know the length of this array
int[] values = new int[10];
// fill the array using a while loop
int w = 1;
while (w <= 10) {
values[w-1] = w;
w ;
}
System.out.println(Arrays.toString(values));
// fill the array using a for loop. We know
// we're going to fully cover the old array,
// but just in case: throw away the old one.
values = new int[10];
for (int f = 1; f<=10; f ) {
values[f-1] = f;
}
System.out.println(Arrays.toString(values));
}
}
Yielding:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
CodePudding user response:
You must use System.out.println();
instead of System.out.print();
Alternatively, you may append "\n"
to the end of the String printed by the first loop to add a newline character.
In that case, you would want to ALSO add a "\n"
to the end of the second loop's print statement and ideally, only if it is not the last iteration of the loop
public class Main04 {
public static void main(String[] args) {
int w = 1;
final StringBuilder sbLoopOne = new StringBuilder();
final StringBuilder sbLoopTwo = new StringBuilder();
while (w <= 10) {
sbLoopOne.append(Integer.toString(w));
//Only print space if needed
if(w != 10) { sbLoopOne.append(" ");}
w ;
}
for ( int f = 1; f<=10; f ){
sbLoopTwo.append(Integer.toString(f));
//Only print space if needed
if(f != 10) { sbLoopTwo.append(" ");}
}
System.out.println(sbLoopOne.toString());
System.out.println(sbLoopTwo.toString());
}
}
In the above example, we use StringBuilder in an effort to demonstrate knowledge of the Java compiler's inability to optimize String concatenation using the " " operator within an iterative context.
The idea is that we collect all of the characters we would like to print in StringBuilder objects and then print them afterward.