gpt4 book ai didi

java - 方法不更新原始字符串变量

转载 作者:行者123 更新时间:2023-12-01 23:14:54 40 4
gpt4 key购买 nike

我编写的用于转换字符串的代码有问题....该字符串在整个代码中没有更新...

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class PigLatin {
private static String str = "pig";
private char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
private Character firstChar, secondChar;

public void inputString(String str) {
try {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(isr);
str = input.readLine();
} catch (Exception e) {
// TODO: handle exception
System.out.println("unable to input String");
e.printStackTrace();
}
firstChar = str.charAt(0);
secondChar = str.charAt(1);
System.out.println(firstChar);
System.out.println(secondChar);
}

public static void main(String[] args) {
PigLatin pl = new PigLatin();
System.out.println("Enter an english word to convert to PigLatin");
pl.inputString(str);
System.out.println(str);
pl.convert(str);
}

public void convert(String lowerCase) {
// TODO Auto-generated method stub
System.out.println("Original string:" + str);
if (isVowel())
str.concat("yay");
else {
String suffix = firstChar.toString() + "ay";
// String suffix = String.valueOf(str.charAt(0))+"ay";
str = str.substring(1) + suffix;
}
System.out.println("PigLatin:" + str);

}

public boolean isVowel() {
// TODO Auto-generated method stub
for (char ch : vowels) {
if (firstChar.equals(ch)) {
if (firstChar.equals('v') && secondChar.equals('q'))
return false;
return true;
}
if (firstChar.equals('y') && !secondChar.equals(ch))
return true;
}
return false;
}
}

输出结果如下:输入一个英语单词以转换为 PigLatin

风筝

k“第一个字符”

我“第二个字符”

pig

原字符串:pig

pig 拉丁:igkay

即使从我输入的字符串中正确读取第一个和第二个字符,即使我在命令行中给出输入,为什么字符串也没有更新..请帮助....

最佳答案

if (isVowel())
str.concat("yay");

字符串在java中是不可变的,所以你必须更新str :

if (isVowel())
str = str.concat("yay");
<小时/>

如果您不想重新分配str每次,您都可以声明 strStringBuilder并通过 append 更新它方法:

private static StringBuilder str = new StringBuilder("pig");

//other code...

public void convert(String lowerCase) {
//other code...
if (isVowel())
str.append("yay"); // this will modify the current object, as it is
// a StringBuilder and not a string
//other code...
}

关于java - 方法不更新原始字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21400819/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com