对于下面运行我的程序,它会提示用户输入要输入到userStringInput中的字符串数。我无法解决的问题是当它进入for循环并要求用户填充数组中的项目时,它会自动将数组的第一项设置为空字符串,并自动将用户输入的第一个字符串设置为被分配给数组中的[1]而不是[0]。下面,我包括了程序中的代码以及正在运行的代码示例。您能帮我解决此数组分配错误吗?
import java.util.Scanner;
import java.util.Random;
/**
Create a string array to store user input
Assign values to the String array
Create a random number generator
Store random numbers generated
Create randomString Method to manipulate the initial array
Store manipulated Strings into a new array
Main method:
create an instance of the class
call get user input method
store return array as an userDataArray in the main
call randomString Method with userDataArray as an argument
store modifiedArray in main method
prints array
*/
public class StringManipulator {
public String[] getUserData(){
System.out.println("How many Strings will you enter?");
Scanner keyboard = new Scanner(System.in);
int totalNumberInArray = keyboard.nextInt();
String[] userStringInput = new String[totalNumberInArray];
for (int elementx = 0; elementx<userStringInput.length; ++elementx){
System.out.println("Enter String Number " + (elementx+1) + ":");
String userInput = keyboard.nextLine();
userStringInput[elementx]= userInput;
}
return userStringInput;
}
public void randomString(String[] tempStringArray) {
Random generator = new Random();
for (int elementy = 0; elementy<tempStringArray.length; ++elementy){
int number = generator.nextInt(4);
String[] modifiedArray = new String[tempStringArray.length];
if(number == 0){
//intact
System.out.println(tempStringArray[elementy]+" (intact)");
}else if(number == 1){
//reversed
StringBuffer s = new StringBuffer(tempStringArray[elementy]);
System.out.println(s.reverse() + " (reversed)");
}else if(number == 2){
//lowercase
System.out.println(tempStringArray[elementy].toLowerCase() + " (lowercase)");
}else if (number == 3){
//uppercase
System.out.println(tempStringArray[elementy].toUpperCase() + " (uppercase)");
}
}
}
public static void main(String[] args){
StringManipulator instance = new StringManipulator();
String[] tempStringArray = instance.getUserData();
instance.randomString(tempStringArray);
}
}
样本输出:
How many Strings will you enter?
10
Enter String Number 1:
Enter String Number 2:
dog
Enter String Number 3:
cat
Enter String Number 4:
goose
Enter String Number 5:
moose
Enter String Number 6:
goose
Enter String Number 7:
cow
Enter String Number 8:
horse
Enter String Number 9:
goat
Enter String Number 10:
mule
(uppercase)
DOG (uppercase)
tac (reversed)
goose (lowercase)
esoom (reversed)
esoog (reversed)
COW (uppercase)
esroh (reversed)
goat (intact)
MULE (uppercase)