简体   繁体   English

如何修复我的if / else语句Java

[英]How to fix my if/else statement Java

I am pretty new to the java language and tried to run a simple text based program where once you push 1 or 0 it will either continue the story or stop it. 我对Java语言很陌生,并尝试运行一个简单的基于文本的程序,一旦按下1或0,它将继续执行该故事或停止该故事。 What I can't figure out is if I run this portion of code below and I select the wrong answer it bypasses my if statement. 我不知道的是,如果我在下面运行这部分代码,并且选择了错误的答案,它将绕过我的if语句。

    package game;
import java.util.Scanner;
class chase {
public static void main (String args[]){

    int answer1;
    answer1 = 1;

    Scanner chase = new Scanner(System.in);

    System.out.println("You hear a noise form a house you walk by. What do you     do?");
    System.out.println("Press 1 to enter the house. Press 0 to run away like a panzy");

    chase.nextLine();

    if (answer1 == 1){
        System.out.println("Good Choice!");
        }else{
        System.out.println("You ran away and was crushed by a falling pig");
        System.out.println("Try again!");
    }

    }

}

What I tried to do was once you push 1 it says "Good Choice!" 我试图做的是,一旦您按1就会说“好选择!” and once you push 0 it runs the else statement. 一旦按下0,它将运行else语句。 But every time I push 0 it says "Good Choice!" 但是每次我按下0时都会说“好选择!”

I don't know what I did wrong. 我不知道我做错了什么。 Please help. 请帮忙。

The problem is here: 问题在这里:

chase.nextLine();

You should read a number into answer1 instead of just reading a line and throwing it away: 您应该在answer1读一个数字,而不是只读一行然后扔掉它:

answer1 = chase.nextInt();

That will also make it so you don't need the answer1 = 1; 这样也可以做到,因此您不需要answer1 = 1; line anymore. 行了。 Since you were just ignoring the line of data you read in, that meant you never changed the value of answer1 , so it was always 1 no matter what you typed. 由于您只是忽略读取的数据行,因此,您永远不会更改answer1的值,因此无论您键入什么内容,它始终为1

似乎您从未将输入分配给answer1,并且由于其初始值为1,因此始终为true。

you're setting the value of answer1 equal to 1 with this line: 您需要在此行中将answer1的值设置为等于1:

answer1 = 1;

and never changing it based on the input from your question. 永远不要根据您问题的输入来更改它。 Thus answer is always equal to 1 and your else is ever reached. 因此, answer始终等于1,并且您的else answer一直都达到了。

You are using 'chase' variable the wrong way, and in this case, 'answer1' initialization is not necessary. 您以错误的方式使用了“追逐”变量,在这种情况下,不需要“ answer1”初始化。

Try this. 尝试这个。

answer1 = chase.nextInt();

Then proceed with your if else statement just like you did in your code. 然后像处理代码一样继续执行if else语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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