解析字符串 (JAVA)

huangapple go评论125阅读模式
英文:

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;
    }

}

解析字符串 (JAVA)

** 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.

huangapple
  • 本文由 发表于 2023年2月9日 03:21:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75390750.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定