从另一种方法在 Try{} 中调用 Scanner? --Java

发布于 2024-12-08 00:53:06 字数 730 浏览 1 评论 0原文

我的问题在于尝试从另一种方法访问在一种方法中创建的扫描仪扫描。它说找不到变量扫描。我尝试声明全局扫描仪扫描,但它给了我一个错误,无法从静态上下文引用非静态变量名称。我怎样才能访问这个变量?

import java.util.*;
import java.io.*;

public class MyClass {
    public static void myMethod() {
        final File f = new File("file.txt");
        Scanner scan = null;
        try {
            scan = new Scanner(f);
        }
        catch(FileNotFoundException ex) {
            System.exit(0);
        }
    }

    public static boolean anotherMethod() {
        final String s = scan.next ();

        if (s.equalsIgnoreCase ("true"))  return true;
        if (s.equalsIgnoreCase ("false")) return false;

        throw new java.util.InputMismatchException ();
    }
}

My problem lies with trying to access Scanner scan created in one method from another method. It says it cannot find variable scan. I tried declaring a global Scanner scan, but it gave me an error, non static variable name cannot be referenced from a static context. How can I access this variable?

import java.util.*;
import java.io.*;

public class MyClass {
    public static void myMethod() {
        final File f = new File("file.txt");
        Scanner scan = null;
        try {
            scan = new Scanner(f);
        }
        catch(FileNotFoundException ex) {
            System.exit(0);
        }
    }

    public static boolean anotherMethod() {
        final String s = scan.next ();

        if (s.equalsIgnoreCase ("true"))  return true;
        if (s.equalsIgnoreCase ("false")) return false;

        throw new java.util.InputMismatchException ();
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

秋叶绚丽 2024-12-15 00:53:06

您仅在 flow 方法中声明了 scan 变量。如果您想在其他方法中使用该值,则需要采取以下两种操作之一:

  • 将其声明为非局部变量
  • 通过参数将其传递到其他方法

由于所有方法都是静态的,对于您需要将其声明为的第一个选项:

private static Scanner scan;

但是,目前 flow 方法似乎做了两件完全不同的事情:

  • 它创建 Scanner (但实际上并不使用它)
  • 它尝试使用以下数据它期望已经被读取

在我看来,您应该在 main 方法中创建 Scanner (或者在 readBoolean2D 之前调用的新方法)无论如何)。您当前正在调用 readBoolean2D 作为程序的第一个操作,尝试在创建任何 Scanner 之前读取不存在的变量。

请注意,这一切与 try 块本身没有任何关系 - 事实上,变量是在单独的方法中声明的,这就是问题所在(以及方法调用的时间),不是try块。

我会尝试将程序重组为:

  • 打开输入
  • 读取所有数据
  • 处理所有数据

我怀疑您实际上可以仅使用局部变量和参数 - 第一个方法将返回 一个扫描仪;第二种方法将使用扫描仪并返回它读取的数据;第三种方法将获取数据。

You've only declared the scan variable within the flow method. If you want to use that value within the other methods, you'll need to take one of two courses of action:

  • Declare it as a non-local variable
  • Pass it into those other methods via a parameter

As all your methods are static, for the first option you'd need to declare it as:

private static Scanner scan;

However, currently the flow method seems to do two radically different things:

  • It creates the Scanner (but doesn't actually use it)
  • It tries to use data which it expects to have already been read

It looks to me like you should be creating the Scanner in your main method (or in a new method which is called before readBoolean2D, anyway). You're currently calling readBoolean2D as the very first action of the program, trying to read from a variable which doesn't exist, before any Scanner has even been created.

Note that none of this has anything to do with the try block itself - it's the fact that the variable is declared in a separate method which is the problem (and the timing of the method calls), not the try block.

I would try to think of restructuring the program as:

  • Open input
  • Read all the data
  • Process all the data

I suspect you can actually get away with just local variables and parameters - the first method would return a Scanner; the second method would take a Scanner and return the data it reads; the third method would take the data.

勿忘初心 2024-12-15 00:53:06

scan 变量必须是全局的、静态的,因为您的方法是静态的。如果您想从另一个方法甚至另一个类访问它,则必须全局声明它。

import java.util.*;
import java.io.*;

public class VerticalPercolation {

    private static Scanner scanner;

    public static boolean[][] flow (final boolean[][] open) {
        // ...
    }

    public static boolean percolates (final boolean[][] open) {
        // ...
    }

    public static boolean[][] random (final int n, final double p, final Random rnd) {
        // ...
    }

    public static boolean readBoolean () {
        // ...
    }

    public static boolean[][] readBoolean2D () {
        // ...
    }

    public static void print (final boolean[][] a) {
        // ...
    }

    public static void main (final String[] args) {
        scanner = new Scanner(...);
    }

}

The scan variable has to be global, and static, since your methods are static. If you want to access it from another method, or even another class, it will have to be declared globally.

import java.util.*;
import java.io.*;

public class VerticalPercolation {

    private static Scanner scanner;

    public static boolean[][] flow (final boolean[][] open) {
        // ...
    }

    public static boolean percolates (final boolean[][] open) {
        // ...
    }

    public static boolean[][] random (final int n, final double p, final Random rnd) {
        // ...
    }

    public static boolean readBoolean () {
        // ...
    }

    public static boolean[][] readBoolean2D () {
        // ...
    }

    public static void print (final boolean[][] a) {
        // ...
    }

    public static void main (final String[] args) {
        scanner = new Scanner(...);
    }

}
梦言归人 2024-12-15 00:53:06
public class VerticalPercolation {
      private static Scanner scan;
      //rest of the code

希望有帮助

public class VerticalPercolation {
      private static Scanner scan;
      //rest of the code

Hope that helps

梦言归人 2024-12-15 00:53:06

其他答案建议创建静态或全局 - 忽略它们。

您正在一个不使用它的函数中创建扫描仪扫描,不要在那里创建它,而是在需要的地方创建它。

readBoolean2D 和 readBoolean 都需要将扫描仪作为参数:

public static boolean[][] readBoolean2D (Scanner scan) {

main 是您需要创建和使用扫描仪的地方:

public static void main (final String[] args) throws IOException {
    final File f = new File("file.txt");
    Scanner scan = new Scanner(f);
    try {
        final boolean[][] open = readBoolean2D (scan);
        print (flow (open));
        System.out.println (percolates (open));
    } finally {
        scan.close();
    }
}

The other answers suggest creating a static or global - ignore them.

You're creating the scanner scan in a function that does not use it, don't create it there, create it where it's needed.

readBoolean2D and readBoolean each need to take the scanner as an argument:

public static boolean[][] readBoolean2D (Scanner scan) {

main is where you need to create and use the scanner:

public static void main (final String[] args) throws IOException {
    final File f = new File("file.txt");
    Scanner scan = new Scanner(f);
    try {
        final boolean[][] open = readBoolean2D (scan);
        print (flow (open));
        System.out.println (percolates (open));
    } finally {
        scan.close();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文