简体   繁体   中英

Only first word of a sentence seen in Java

I'm a newbie writing Java code. I haven't read about loops yet. I'm just up to if-else statements. My code works except when I enter a sentence only the first word is recognized. If I enter a sentence with no spaces it works perfectly. How can I get the code to see the whole sentence? Thanks!

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.");
    }
}

Use

keyboard.nextLine();

instead of

keyboard.next();

看看API ,特别是关于nextLine()的部分。

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.");
    }
}

Scanner.next() only returns the next token, which, by default, is just one word (whitespace-delimited). If you want the whole sentence you can change the delimiter to '\\n': keyboard.setDelimiter("\\n"); , or you can learn loops and then loop over the whole sentence.

Edit: Or, as others have pointed out, nextLine() . That's more portable because macs use '\\r', which won´ t be caught with what I said.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM