英文:
Parsing Strings (JAVA)
问题
I'm trying to complete this assignment, but I'm stuck on how to proceed.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
while (true)
{
System.out.println("Enter input string: ");
String userInput = scan.nextLine();
if (userInput.contains(","))
{
System.out.println("First word: " + userInput.split(",")[0]);
System.out.println("Second word:" + userInput.split(",")[1]);
System.out.println("\n");
}
else if (!userInput.contains(","))
{
System.out.println("Error: No comma in string");
}
else if (userInput.equalsIgnoreCase("q"))
{
break;
}
}
return;
}
}
I've fixed the issue with the quit, still need help with the weird whitespace.
英文:
I'm trying to complete this assignment, but I'm stuck on how to proceed.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
while (true)
{
System.out.println("Enter input string: ");
String userInput = scan.nextLine();
if (userInput.contains(","))
{
System.out.println("First word: " + userInput.split(",")[0]);
System.out.println("Second word:" + userInput.split(",")[1]);
System.out.println("\n");
}
else if (!userInput.contains(","))
{
System.out.println("Error: No comma in string");
}
else if (userInput.equalsIgnoreCase("q"))
{
break;
}
}
return;
}
}
** I've fixed the issue with the quit, still need help with the weird whitespace.
答案1
得分: 1
你的代码永远不会实际进入最后的"else if",因为"q"不包含逗号,所以只有第二个"else if"被访问。另外,你没有去掉字符串中的空格,在拆分单词之后仍然保留它们。
英文:
Your code never actually goes to the last "else if", because "q" doesn't contain a comma, so only the second "else if" is accessed. Also, you aren't removing the spaces in your string, you still keep them after spliting the words.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论