简单如果,否则如果。不能让它工作

时间:2014-09-08 00:48:06

标签: java if-statement java.util.scanner

我试图制作一个小程序,要求1-10之间的数字然后给出不同的预写响应。这是我到目前为止所做的。

import java.util.Scanner;
public class AlasFutureTeller
{
        public static void main(String [ ] args)
    {
        System.out.println("I CAN READ YOUR FUTURE!");
        System.out.println("TYPE A NUMBER BETWEEN 1 AND 10 TO MEET YOUR FATE!!");
        Scanner oneTen = new Scanner (System.in);
        int one == oneTen;
        if (oneTen=="one")
            System.out.println("YOU WILL GO TO SLEEP TODAY!!");
        else if ( oneTen=="two")
            System.out.println("YOU WILL HAVE A BIRTHDAY EVERY YEAR UNTIL YOU DIE!!");
        else if ( oneTen=="three")
            System.out.println("YOU WILL SHOWER SOMETIME IN THIS YEAR!!");
        else if ( oneTen=="four")
            System.out.println("YOU WILL LIVE UNTIL YOU THE DAY YOU DIE!!");
    }
}

2 个答案:

答案 0 :(得分:0)

您无法将Stringsints愚蠢的鹅进行比较!

if (oneTen=="one")

尝试:

if (oneTen.nextInt() == 1)

答案 1 :(得分:-1)

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        System.out.println("I CAN READ YOUR FUTURE!");
        System.out.println("TYPE A NUMBER BETWEEN 1 AND 10 TO MEET YOUR FATE!!");

        Integer number = new Scanner (System.in).nextInt();

        if (number.equals(1))
            System.out.println("YOU WILL GO TO SLEEP TODAY!!");
        else if (number.equals(2))
            System.out.println("YOU WILL HAVE A BIRTHDAY EVERY YEAR UNTIL YOU DIE!!");
        else if (number.equals(3))
            System.out.println("YOU WILL SHOWER SOMETIME IN THIS YEAR!!");
        else if ( number.equals(4))
            System.out.println("YOU WILL LIVE UNTIL YOU THE DAY YOU DIE!!");

    }

}

您可以将变量编号的类型更改为“int”,并将比较模式更改为

if(number == 1)...

您可以选择更喜欢的内容。但是现在你需要理解int是一个原始类型,Integer是这个原始类型的包装器,它给你一个表示基本类型的对象。