gpt4 book ai didi

java - 是什么原因导致这个 "Incompatible operand types int and java.lang.String"

转载 作者:行者123 更新时间:2023-12-02 04:48:43 24 4
gpt4 key购买 nike

我在 if 行上得到不兼容的操作数类型 int 和 java.lang.String。我不知道它在问什么或如何解决它。

import java.io.*;
import static java.lang.System.*;

//不确定是否需要上面的导入 导入java.util.Scanner;

class Main{

public static void main (String str[]) throws IOException {

Scanner scan = new Scanner(System.in);

String ap = "April";
String mar = "March";

int one = 1;
int two = 2;

System.out.println("What month were you born in? (number)");
int month = scan.nextInt();
System.out.println("What day (number)");
int day = scan.nextInt();
if(((month == ap) && (day <= 19) || (month == mar) && (day >= 21))){
System.out.println("Your birthday is: "+ month+ " "+day);
System.out.println("Aries");
System.out.println("Horoscope: ");
}else
System.out.println("HI"); //Just some filler code for compiling



}

}

最佳答案

您无法直接比较Stringint(您可以获取intString值但我不认为这会对您有帮助),在您的用例中对我来说唯一有意义的导入静态是 java.util.Calendar.*。然后你需要从输入的月份中减一,因为Java认为Calendar.JANUARY (第一个月和 Static Import 的作用)为月份 0。最后,当您的输入不在预期范围内时,请显示一些有意义的内容而不是“HI”。类似的东西

import java.io.IOException;
import java.util.Scanner;
import static java.util.Calendar.*;

class Main {
public static void main(String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("What month were you born in? (number)");
int month = scan.nextInt() - 1;
System.out.println("What day (number)");
int day = scan.nextInt();
if (((month == APRIL) && (day <= 19) ||
(month == MARCH) && (day >= 21))) {
System.out.println("Your birthday is: " + month + " " + day);
System.out.println("Aries");
System.out.println("Horoscope: ");
} else {
System.out.printf("Month %d, Day %d%n", month, day);
}
}
}

关于java - 是什么原因导致这个 "Incompatible operand types int and java.lang.String",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29450853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com