【问题标题】:Only first word of a sentence seen in Java在 Java 中只看到句子的第一个单词
【发布时间】:2011-12-20 15:58:30
【问题描述】:

我是一个编写 Java 代码的新手。我还没有读到循环。我只需要 if-else 语句。我的代码有效,除非我输入一个句子时只识别第一个单词。如果我输入一个没有空格的句子,它会完美运行。如何获取代码以查看整个句子?谢谢!

import java.util.Scanner;

public class Program04
{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Write a complete sentence with proper grammer:");
        String sentence = keyboard.next();
        boolean qMark = sentence.contains("?");
        boolean wow = sentence.contains("!");
        if (qMark)
            System.out.println("Yes");
        else if (wow)
            System.out.println("Wow");
        else
            System.out.println("You always say that.");
    }
}

【问题讨论】:

    标签: java string char if-statement


    【解决方案1】:

    使用

    keyboard.nextLine();
    

    而不是

    keyboard.next();
    

    【讨论】:

      【解决方案2】:

      看看API,尤其是关于nextLine()的部分。

      【讨论】:

      • 谢谢。我试过了,但没有明确说明我需要的答案。在查看 API 时,您可能需要知道答案。
      • 其中包含研究元素。如果您看到nextLine 并阅读了文本,那是显而易见的。但我同意你的看法,有时很难知道该往哪里看。
      【解决方案3】:

      Scanner.next() 只返回下一个标记,默认情况下,它只是一个单词(空格分隔)。如果您想要整个句子,您可以将分隔符更改为'\n':keyboard.setDelimiter("\n");,或者您可以学习循环然后循环整个句子。

      编辑: 或者,正如其他人指出的那样,nextLine()。这更便于携带,因为 mac 使用 '\r',这不会被我所说的所捕获。

      【讨论】:

        【解决方案4】:
        import java.util.Scanner;
        
        public class Program04{
        
            public static void main(String[] args){
        
                Scanner keyboard = new Scanner(System.in);
                System.out.println("Write a complete sentence with proper grammer:");
                String sentence = keyboard.nextline(); 
                
                *//this graps full text but next ignores the other words after a space is given*
                boolean qMark = sentence.contains("?");
                boolean wow = sentence.contains("!");
        
                if (qMark)
                    System.out.println("Yes");
                else if (wow)
                    System.out.println("Wow");
                else
                    System.out.println("You always say that.");
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-03
          • 1970-01-01
          • 2023-03-30
          • 1970-01-01
          • 2011-01-27
          相关资源
          最近更新 更多