gpt4 book ai didi

java - 如何在方法中使用键盘输入

转载 作者:行者123 更新时间:2023-12-01 22:29:27 24 4
gpt4 key购买 nike

我是 JAVA 新手,在尝试实现此代码时遇到困难。你能帮我吗?谢谢

import java.util.Scanner;

public class Derivative {


public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println(degree());
}

public int degree(){
System.out.println("degree of function?");
int n = keyboard.nextInt();
return n;
}

}

最佳答案

您已在 main 方法的范围内声明了 Scanner 变量。 level 方法不知道存在任何名为 keyboard 的变量。如果您想了解有关变量作用域的更多信息(我相信您应该这样做),您可以查看资源 here 。它更详细地解释了您所面临的情况。

你可以做两件事

  1. 首先,您可以将 Scanner 设为类变量。
  2. 第二个是将其传递到函数中

类变量:

您可以在主方法上方声明它,对于类变量策略,例如:

公共(public)静态扫描仪键盘 = new Scanner(System.in);

类方法的示例是:

public static Scanner keyboard = new Scanner(System.in);

public static void main(String[] args) {

System.out.println(degree());

}

public static int degree() {
System.out.println("degree of function?");
int n = keyboard.nextInt();
return n;
}

传递给函数:

或者,您可以更改方法来使用扫描仪,例如:

public static int Degree(扫描仪键盘){

并这样调用它:

学位(键盘)

将其传递到方法的示例是:

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println(degree(keyboard));

}

public static int degree(Scanner keyboard) {
System.out.println("degree of function?");
int n = keyboard.nextInt();
return n;
}

额外:

还应该注意的是,由于您是从 static 方法 (main) 调用 level,因此您应该使 Degree 静态方法。通过更改来做到这一点:

public int Degree() {

至:

public static int Degree() {

关于java - 如何在方法中使用键盘输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28114532/

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