I need to write a programm that, when inserted a number, it print a sequence of numbers from 1 to that number, in separate lines adding a number each time. Example: if you insert 8, it print
1
1 2
1 2 3
1 2 3 ... 8
import java.util.Scanner;
public class Series {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.print("Insert number ");
int a = sc.nextInt();
int i = 0;
StringBuilder sb = new StringBuilder();
for(i=1; i<=a; i++)
sb.append(i);
System.out.println(sb.toString());
}
}
I'm using this and obviously it print just one line from 1 to the number. I don't know what i can change, or if this is totally wrong
StringBuilder
but printed the result only once after the loop, which outputs the entire sequence in one single line, not step-by-step as you want.Here is the corrected version:
import java.util.Scanner;
public class Series {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Insert number: ");
int a = sc.nextInt();
sc.close();
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= a; i++) {
sb.append(i).append(" ");
System.out.println(sb.toString().strip());
}
}
}
Insert number: 10
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
if
condition and avoided using strip()
(or trim()
) here for efficiency:import java.util.Scanner;
public class Series {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Insert number: ");
int a = sc.nextInt();
sc.close();
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= a; i++) {
if (i > 1) {
sb.append(" ");
}
sb.append(i);
System.out.println(sb.toString());
}
}
}
StringBuilder()
:import java.util.Scanner;
public class Series {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Insert number: ");
int a = sc.nextInt();
sc.close();
if (a < 1) {
System.out.println("");
return;
}
String res = "1";
System.out.println(res);
for (int i = 2; i <= a; i++) {
res += " " + i;
System.out.println(res);
}
}
}
StringBuilder()
. The numbers are printed directly as they are processed, with no intermediate storage required.import java.util.Scanner;
public class Series {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Insert number: ");
int a = sc.nextInt();
sc.close();
for (int i = 1; i <= a; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
I would recommend making a habit of calling one of the String#strip… methods rather than trim. See the post: Java’s String.trim has a strange idea of whitespace. And see more discussion on this Answer of mine. – Comment from Basil Bourque
The
trim()
orif
can be avoided by starting with "1" in theStringBuilder
and looping from 2 on. (actually I would suggest using a plainString
instead of aSringBuilder
) – by user85421