简体   繁体   中英

How to loop string in decrement order?

Write a program that takes a string input from the user and then outputs the first character, then the first two, then the first three, etc until it prints the entire word. After going down to one letter, print the opposite back up to the full word.

I've gotten the first part done.

   Scanner word = new Scanner(System.in);
   System.out.println("Enter a word.");
   String thing = word.next();
   String rest = "";
      for(int i=0;i< thing.length();i++){
           String w = thing.substring(i,i+1);
           rest += w;
           System.out.println(rest);
       }   

This is what it should look like.

C
Co
Com 
Comp 
Compu 
Comput 
Compute 
Computer 
Computer
Compute 
Comput 
Compu 
Comp
Com 
Co
C

Strings in Java are indexed starting from 0, so the last character is indexed at length-1 .

To iterate from the last character down to the first, the for loop would be for(int i = thing.length () - 1; i >= 0; i--) .

Alternatively, recursion would be a simpler solution considering you already obtained the strings that should be printed in reverse.

static void f (String str, int n) {
    if (n > str.length ()) return;
    String temp = str.substring (0, n); // obtain the string
    System.out.println (temp); // print
    f (str, n + 1); // go to next substring
    System.out.println (temp); // print after returning from the last obtainable substring
}

The function can now be called via f(thing, n);

You can try to implement two arrays, in the first you must split the String entered from the Scanner and in the second you must store the generated aux variable in each iteration of the first array, To finish you must iterate the second array in reverse.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a word: ");
    String word = sc.next();
    String[] array = word.split("");
    int length = array.length;
    String[] auxArray = new String[length];
    String aux = "";

    for (int i = 0; i < length; i++) {
        aux += array[i];
        auxArray[i] = aux;
        System.out.println(aux);
    }

    for (int i = length - 1; i >= 0; i--) {
        System.out.println(auxArray[i]);
    }

}

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