为什么这段代码在没有错误的情况下编译时不会打印答案行?编程新手

时间:2015-04-24 13:32:50

标签: java

我只是想知道为什么在编译期间没有出现错误时,此代码不会打印答案行。我正在完成Learnjavathehardway(https://programmingbydoing.com/a/two-more-questions.html

的作业#35
import java.util.Scanner;

public class TwoMoreQuestions
{
    public static void main( String[] args )
    {
        Scanner keyboard = new Scanner(System.in);

        System.out.print( "Question 1: Does it belong inside or outside or both? ");
        String q1 = keyboard.next();

        System.out.println( "Question 2: Is it alive? ");
        String q2 = keyboard.next();

        if((q1.equals("inside"))&&(q2.equals("not alive")))
        {   
            System.out.println( "Then what else could you be thinking of besides a shower curtain?!?" );
        }
        if((q1.equals("inside"))&&(q2.equals("alive")))
        {   
            System.out.println( "Then what else could you be thinking of besides a houseplant?!?" );
        }
        if((q1.equals("outside"))&&(q2.equals("alive")))
        {   
            System.out.println( "Then what else could you be thinking of besides a bison?!?" );
        }
        if((q1.equals("outside"))&&(q2.equals("not alive")))
        {   
            System.out.println( "Then what else could you be thinking of besides a billboard?!?" );
        }
        if((q1.equals("both"))&&(q2.equals("alive")))
        {   
            System.out.println( "Then what else could you be thinking of besides a dog?!?" );
        }
        if((q1.equals("both"))&&(q2.equals("not alive")))
        {   
            System.out.println( "Then what else could you be thinking of besides a cellphone?!?" );
        }
    }
}

1 个答案:

答案 0 :(得分:1)

查看您的代码如果使用Scanner.next()方法,它将在空格后获取值。因此,如果您输入bothalive没有任何空格,它会显示结果,但如果您打算在空格使用后获取值Scanner.nextLine();

查看旁边的代码和评论

        Scanner keyboard = new Scanner(System.in);

        System.out.print( "Question 1: Does it belong inside or outside or both? ");
        String q1 = keyboard.next();//will not take any value after space


            System.out.println( "Question 2: Is it alive? ");
            String q2 = keyboard.next();//will not take any value after space
 //so if you enter "not alive" q2 will store only "not".
            //String q2 = keyboard.nextLine();
// this will take all character even after space