【问题标题】:incompatible types required: int found: java.lang.String (basic programming)需要不兼容的类型:int found: java.lang.String(基本编程)
【发布时间】:2015-08-02 00:47:28
【问题描述】:

我遇到过几次这个错误,我尝试了很多方法来修复它,但我似乎无法找出问题所在。这是代码:

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

        Scanner scan = new Scanner(System.in);
        String name1 = scan.nextLine();
        String name2 = scan.nextLine();
        int num1 = scan.nextLine();
        double num2 = scan.nextLine();

        System.out.println("Employee Name:" + name2 + name1);
        System.out.println("Age:" + num1);
        System.out.println("Salary:" + (double)num2);
    }
}

具体出现的错误是:

[文件:/InputExample.java 行:9,列:25] 需要不兼容的类型:int found: java.lang.String

[文件:/InputExample.java 行:10,列:28] 需要不兼容的类型:双重发现:java.lang.String

【问题讨论】:

  • 这是因为scan.nextLine(); 返回一个String,而您正试图将返回的String 分配给int。我想你需要scan.nextInt();

标签: java types


【解决方案1】:

您正在读取字符串,但希望将其保存为整数/双精度数。试试这个:

int num1 = Integer.valueOf(scan.nextLine());

Double 也是如此。

或者正如 OldCurmudgeon 提到的:

int num1 = scan.nextInt();

【讨论】:

  • scan.nextInt(); 可能会更好。
  • 你可以在你的答案中改变它 - 被认为是让你的答案尽可能最好的好习惯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
  • 1970-01-01
  • 2017-03-29
  • 1970-01-01
  • 1970-01-01
  • 2012-12-28
  • 1970-01-01
相关资源
最近更新 更多