gpt4 book ai didi

java - 双变量输入

转载 作者:行者123 更新时间:2023-11-29 04:55:41 25 4
gpt4 key购买 nike

我目前正在学习 Java。我正在尝试制作一个示例应用程序,当我们输入 4 个数字时,打印这些数字的平均值。

这是我的尝试:

package ave4numbers;

import java.util.Scanner;

public class Ave4Numbers {

double a,b,c,d;
double e = (a+b+c+d)/4;
Scanner sc = new Scanner(System.in);

public static void main(String[] args) {

System.out.println("Enter your numbers ");
a = sc.nextDouble();
b = sc.nextDouble();
c = sc.nextDouble();
d = sc.nextDouble();

System.out.println(e);

}

}

但这行不通。怎么了?谢谢。

最佳答案

除了在获得数字之前尝试进行数学运算的错误之外,您还需要在 main 方法中声明变量或将变量设为静态。

    public static void main(String[] args) {
double a,b,c,d; //These don't have to be static, if they are inside your method.
Scanner sc = new Scanner(System.in);
System.out.println("Enter your numbers ");
a = sc.nextDouble();
b = sc.nextDouble();
c = sc.nextDouble();
d = sc.nextDouble();
double e = (a+b+c+d)/4; //Do math after we save the numbers
System.out.println(e);
}

或者...

    static double a,b,c,d;  //If you leave these outside your method, it has to be static
static Scanner sc = new Scanner(System.in); //This as well

public static void main(String[] args) {

System.out.println("Enter your numbers ");
a = sc.nextDouble();
b = sc.nextDouble();
c = sc.nextDouble();
d = sc.nextDouble();
double e = (a+b+c+d)/4; //Do math after we save the numbers
System.out.println(e);

}

静态示例

public class Solution
{
public static void main(String[] args) {
//You can call static methods from another static method without an instance of the class.
//So you can do this if it is static. Notice I did not create an instance of Example.
Example.staticMethod();
System.out.println(Example.staticVariable);
//However these will NOT compile
//Example.nonStaticMethod
//System.out.println(Example.nonStaticVariable);

//If you want access to the nonStaticMethod you need an instance.
Example myExample = new Example();
myExample.nonStaticMethod(); //This WILL compile.
System.out.println(myExample.nonStaticVariable); //Will compile
}
}

class Example{
static String staticVariable = "";
public String nonStaticVariable = "";
public static void staticMethod(){
}
public void nonStaticMethod(){
}
}

关于java - 双变量输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33873843/

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