好的,首先,我想说我是Java Development的新手...... 考虑到这一点,我现在试图使tryWord的值包含空格而不是破折号,如果是s中的空格。谁能帮我?
String tryWord = "";
for (int i = 0; i < s.length(); i++) {
tryWord += "-";
}
System.out.println(s + tryWord);
Value for s
------------
private static String randomOutput() {
String array[] = new String[10];
array[0] = "Hamlet";
array[1] = "Mysts of Avalon";
array[2] = "The Iliad";
array[3] = "Tales from Edger Allan Poe";
array[4] = "The Children of Hurin";
array[5] = "The Red Badge of Courage";
array[6] = "Of Mice and Men";
array[7] = "Utopia";
array[8] = "Chariots of the Gods";
array[9] = "a Brief History of Time";
ArrayList<String> list = new ArrayList<String>(Arrays.asList(array));
Collections.shuffle(list);
String s = list.get(0);
return s;
}
答案 0 :(得分:2)
您可以在java中使用replace
或replaceAll
,它将解决问题
tryWord = s.replaceAll("\\s", "-");
答案 1 :(得分:0)
使用此:
tryWord.replace(oldChar, newChar);
答案 2 :(得分:0)
tryWord += s.charAt(i) == ' ' ? " " : "-";
这称为三元表达式... ? ... : ...
,一种带有字符的if是空格,然后是其他空格。
答案 3 :(得分:0)
试试这个:
if (s.charAt(i) == ' ') {
tryWord += ' ';
} else {
tryWord += '-';
}