java - 双变量输入

标签 java double java.util.scanner

我目前正在学习 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/

相关文章:

c++ - 在 C++ 中,它是从小数点开始还是从整个 #setprecision 开始

ios - String to Double 转换在 Swift 中失去精度

Java Math RoundingMode.HALF_EVEN 不同的结果

java - 使用扫描仪时如何跳过字符

来自 URL 文本文件的 Java 单行扫描器

java - 将 JAX-WS 集成到 Spring Boot

java - OpenIMAJ Jar 文件

java - 在获取用户输入之前的 System.out.println()

java - 在 Java/Android 中读取一段文件

java - 如何删除 Jsoup 中的 HTML 实体?