Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如果是空格,则包含空格而不是破折号_Java - Fatal编程技术网

Java 如果是空格,则包含空格而不是破折号

Java 如果是空格,则包含空格而不是破折号,java,Java,好的,首先我想说我是Java开发新手。。。 考虑到这一点,我目前正试图使tryWord的值在s中包含空格而不是破折号。有人能帮我吗 String tryWord = ""; for (int i = 0; i < s.length(); i++) { tryWord += "-"; } System.out.println(s + tryWord); Value for s ------------ private static Strin

好的,首先我想说我是Java开发新手。。。 考虑到这一点,我目前正试图使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;
}
String tryWord=”“;
对于(int i=0;i
您可以在java中使用
replace
replaceAll
,这将解决问题

tryWord = s.replaceAll("\\s", "-");
使用以下命令:

 tryWord.replace(oldChar, newChar);
这称为三元表达式
,一种如果ith char是空格,那么空格else破折号的方法。

尝试以下方法:

if (s.charAt(i) == ' ') {
   tryWord += ' ';
} else {
   tryWord += '-';
}

谢谢你给我更好的答案。我会把这个也包括在内。我想你实际上想要的是
\\s
,而不是
\\s
。大写的
S
表示所有非空白字符。不需要复制列表来洗牌,也不需要洗牌列表来获得一个元素。你可以得到一个数组的随机元素,而不需要这两个元素中的任何一个。你希望tryWord中的值是多少?
if (s.charAt(i) == ' ') {
   tryWord += ' ';
} else {
   tryWord += '-';
}