Loop pyramid

The expected result is as follows:

1 12 123 1234 12345 123456 1234567 12345678 123456789 1234567890 12345678901 123456789012 

Below is the startup code that I would use:

 import java.util.Scanner; public class Pyramid { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Type in an integer value"); Scanner in = new Scanner(System.in); int input = in.nextInt(); String str = ""; for(int i=1;i<=input;i++){ str += i; System.out.println(str); } } } 

The following is my conclusion.

 Type in an integer value 15 1 12 123 1234 12345 123456 1234567 12345678 123456789 12345678910 1234567891011 123456789101112 12345678910111213 1234567891011121314 123456789101112131415 

I was thinking about how to solve this problem; if I write the operator If if(i > 9){ i = 0; } if(i > 9){ i = 0; } . But will it reset my counter?

How can I complete this task? What am I missing?

+4
source share
4 answers

You can use the modulo operator to loop i back to 0 as soon as it reaches 10:

 str += i % 10; 
+5
source

Everything you need to use with the % operator module, and everything will work until any number.

 public static void main(String[] args) throws IOException { System.out.println("Type in an integer value"); Scanner in = new Scanner(System.in); int input = in.nextInt(); String str = ""; for (int i = 1; i <= input; i++) { str += i % 10; System.out.println(str); } } 
+2
source

solution:

 IntStream.rangeClosed(1, MAX) .forEach(i -> IntStream.rangeClosed(1, i) .mapToObj(j -> j == i ? j % 10 + "\n" : j % 10 + " ") .forEach(System.out::print) ); 
0
source
 public class counter1 { public static void main(String[] args) {// TODO Auto-generated method stub while(true) //keep repeating code { System.out.println("Enter Number..."); Scanner number = new Scanner(System.in); int repeat = number.nextInt(); //input number int c = 1; //start counting at 1 while (c<=repeat) //count vertically if this if true { int a = 1; //always start each count from 1 do { System.out.print(a + " "); //print number and a space horizontally a++; //increment horizontal numbers by 1 } while (a<=c); //check if the final number on horizontal line is less max, if max-exit loop c++; System.out.println(); //line break } } } } 
-1
source

Source: https://habr.com/ru/post/1480821/


All Articles