简体   繁体   中英

How do I make this output happen in java?

I'm a beginner and I want to output the following using a for loop and subscript and I'm not sure.

output:

Jamaica

 amaica

  maica

   aica

    ica

     ca

      a

What can I do, in order to achieve this output?

First: You need to loop for generating n line which is the length of array.

Second: You need to print the spaces with is same value as row - 1 number of times.

Second: You need to print character start from row - 1 number to the length of the string.

And the final solution will be:

public class MyClass {
    public static void printStr(String str) {
        int i,j;
        for (i = 0; i < str.length();i++) {
            for(j = 0; j < i; j++) {
                System.out.print(" ");
            }
            for(j = i; j < str.length();j++) {
                System.out.print(str.charAt(j));
            }
          System.out.println("");
        }
    }
    public static void main(String args[]) {
        MyClass.printStr("Jamaica");

    }
}

I would use two regular expressions , the first to terminate the loop when the String is filled with white space. The second to replace the first non-white space character with a white space in the loop body (after printing the current String value). And, if it's possible the String might be empty you should guard against that. Like,

String s = "Jamaica"; 
if (!s.isEmpty()) {
    while (!s.matches("\\s+")) {
        System.out.println(s);
        s = s.replaceFirst("\\S", " ");
    }
}

Outputs (as requested)

Jamaica
 amaica
  maica
   aica
    ica
     ca
      a
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String s = scan.next(); //input through scanner class
    int len = s.length();
    for(int i=0;i<len;i++){
        for(int j=0;j<i;j++){
            System.out.print(" ");
        }
        for(int j=i;j<len;j++){
            System.out.print(s.charAt(j));
        }
        System.out.println("");
    }
}

Hopefully that helps

Try following code:

StringBuilder country = new StringBuilder("Jamaica"); 
        for(int i=0; i< country.length();i++){
            if(i > 0)
            {
                for(int j=0;j<i;j++){
                    country.setCharAt(j,' ');                    
                }                
            }
            System.out.println(country);            
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM