【问题标题】:Compiling problem - Why doesn't Int work on my age variable?编译问题 - 为什么 Int 对我的年龄变量不起作用?
【发布时间】:2019-01-14 14:43:22
【问题描述】:

Picture of error

我在 hello world 之后制作的第一个程序。名字、姓氏和年龄。在年龄上使用 String 时,一切都按预期工作。有人告诉我在年龄上使用 Int 而不是 String,但是当我更改为 Int 并尝试编译时,我收到此错误:“找不到符号”。我想如果我想要年龄作为 Int,我必须做一些完全不同的事情。我究竟做错了什么?

导入 java.util.Scanner;

公共类 Oppgave2 {

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);


    System.out.println("Skriv inn fornavn: ");
    String fornavn = scanner.nextLine();



    System.out.println("Skriv inn etternavn: ");
    String etternavn = scanner.nextLine();



    System.out.println("Skriv inn alder: ");
    int alder = scanner.nextLine();

    System.out.println("Ditt navn er: " + fornavn + " " + etternavn);
    System.out.println("Din alder er: " + alder);
}

}

【问题讨论】:

  • Int 不是一个类型,这就是你得到“找不到符号”的原因。可以使用int 或Integer,但您必须使用nextInt() 而不是nextLine(),因为这会返回String。

标签: java cannot-find-symbol


【解决方案1】:

nextLine() 返回一个String,如javadoc of Scanner 中所述。 如果要获取和存储 int,请使用 nextInt()。

【讨论】:

    【解决方案2】:

    使用nextLine读取字符串,然后转换为int

    String reply = sc.nextLine();
    int alder = Integer.valueOf(reply).intValue;
    

    【讨论】:

      【解决方案3】:

      在 Scanner 类中,当期望标记为整数时使用 nextInt()。

      Int alder =scanner.nextInt()

      【讨论】:

      • 您的代码仍然会导致“找不到符号”错误。
      • @f1sh 为什么会这样?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-05
      相关资源
      最近更新 更多