I am trying to reduce the string array by using a for a loop. This is an example I tried to do
User string input: Calculus User input:5 output: CalcuCalcCalCaC
I have turned the string to a char array but the issue presents itself when trying to print them out multiple times. It only prints once and has the right starting output.
input string: Oregon input number: 4 output: Oreg
I notice my for loop says that it is not looping when I hover over it on the IDE that I downloaded from JetBrains.
I tried different combinations of decrementing and incrementing but could not get that “for statement is not looping”. Other than that I have tried different ways to do something in the for loop but I don’t think anything needs to be done for now if the for loop is not looping then, right?
So my question is, how to reduce a string or char array and print the decrement value over and over again?
Here is my code so far for it. public String wordDown(String userString, int userNum) { String stringModded = userString.substring(0, userNum); char[] charArray = stringModded.toCharArray(); char repeat = ' '; for(int i = 0; i<userNum; ++i) { repeat = (char) (repeat +charArray[i]); charArray[i] = repeat; for(int j = 1; i > charArray.length; ++j) { String modWord = String.valueOf(charArray[i + 1]); return modWord; } } return null; } public static void main(String[] args) { int userNumber; String userString; RandomArrayFunctionalities ranMethod = new RandomArrayFunctionalities(); Scanner in = new Scanner(System.in); System.out.println("nEnter a word:"); userString = in.next(); System.out.println("nEnter a number within the word scope that you just enter:"); userNumber = in.nextInt(); System.out.println(ranMethod.wordDown(userString, userNumber)); }
Advertisement
Answer
You do not need to modify the original array. Use a StringBuilder
to concatenate the successive parts of the word. Use the String.substring(int,int)
method to pull out those parts. The example that follows uses a decrementing index to generate the successively smaller substrings.
public String wordDown(String word, int userNum) { StringBuilder sb = new StringBuilder(); for (int length = userNum ; length > 0 ; --length) { sb.append(word.substring(0, length)); } return sb.toString(); }