我一直在尝试构造一个while循环,当一个字符串包含我正在寻找的“模式”时,该循环用于遍历字符串。该字符串是一个局部变量,在while循环的上方声明,并且我无法在while循环内对其进行子字符串处理,因此每个连续的循环都将查看字符串的下一部分。
如果能解决这个问题,我将不胜感激
这是代码;只是您有一个想法,onlineList通常以数组列表输出的形式出现,例如[Adrian,Bob,Buddy]
String onlineList = networkInput.nextLine();
//Declare a local variable for modified online list, that will replace all the strings that contain ", " "[" and "]"
String modifiedOnlineList = onlineList.replaceAll("\\, ", "\n").replaceAll("\\[", "").replaceAll("\\]", "");
//Loop the modifiedOnlineList string until it contains "\n"
while (modifiedOnlineList.contains("\n")) {
//A local temporary variable for the first occurence of "\n" in the modifiedOnlineList
int tempFirstOccurence = modifiedOnlineList.indexOf("\n");
//Obtain the name of the currently looped user
String tempOnlineUserName = modifiedOnlineList.substring(0, tempFirstOccurence);
//Substring the remaining part of the string.
modifiedOnlineList.substring(tempFirstOccurence + 2);
System.out.println(modifiedOnlineList);
}
字符串在Java中是不可变的
modifiedOnlineList = modifiedOnlineList.substring(tempFirstOccurence + 2);
您必须接收方法返回的新 String
对象substring
。
modifiedOnlineList.substring(tempFirstOccurence + 2);
System.out.println(modifiedOnlineList); // still old value
当您收到
modifiedOnlineList = modifiedOnlineList.substring(tempFirstOccurence + 2);
System.out.println(modifiedOnlineList); // now re assigned to substring value
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句