首页 > 解决方案 > 如何执行这个java双扫描仪?

问题描述

当调用 scanDouble(); 我得到一个错误。

package com.company;
import java.util.Random;
import java.util.Scanner;

public class Main {

Scanner in = new Scanner(System.in);
public static void printLogarithm(double x){
    if(x <= 0.0){
        System.err.println("Error: x must be positive.");
        return;
    }
    double result=Math.log(x);
    System.out.println("The log of x is"+ result);
}
public static void scanDouble(Scanner in) {
    System.out.print("Enter the name: ");
    if (!in.hasNextDouble()){
        String word = in.next();
        System.err.println(word + "is not a number");
        return;
    }
    double x = in.nextDouble();
    printLogarithm(x);

}

public static void main(String[] args) {
scanDouble();
}
}

有谁知道如何执行 scanDouble(); 我应该在方法调用中包含一些内容吗?

标签: javainput

解决方案


如果我遵循您的逻辑,请尝试inscanDouble()方法中传递 Scanner 变量,如下所示:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);   
    scanDouble(in);
}

例如,将双精度值x作为参数传递是行不通的,我只是对其进行了测试。


推荐阅读