How do I access my text file from other methods if it is passed as a command line argument in the main method(java)

huangapple 未分类评论42阅读模式
英文:

How do I access my text file from other methods if it is passed as a command line argument in the main method(java)

问题

以下是翻译好的代码部分:

public class Practice {

    public static void main(String[] args) throws FileNotFoundException {
        In in = new In(args[0]); // 定义局部变量
        abc(in);                 // 将其传递给方法
    }

    public static void abc(In in) throws FileNotFoundException {
        String s = in.readAll();     // 使用方法参数
        double[][] boxes = readFile(s);

        System.out.println(boxes);
    }

    public static double[][] readFile(String s) throws FileNotFoundException {      
        File f = new File(s);
        Scanner scF = new Scanner(f);
        int R = scF.nextInt();
        int C = scF.nextInt();
        double[][] boxes = new double[R][C];
        while (scF.hasNextLine()) {
            for (int i = 0; i < R; i++) {
                for (int j = 0; j < C; j++) {
                    boxes[i][j] = scF.nextInt();
                } // 读取文件并将值添加到 double[][] 数组中            
            }               
        }
        return boxes;
        // 返回一个 double[][] 数组
    }
}

如果有任何问题需要进一步解答,请随时提问。

英文:

I am new to using multiple methods in Java so I am struggling quite a bit with this. I am using the stdIn library and the location of the text file is passed as a command line argument in the main method as follows: In in = new In(args[0]);.
How do I read this file from another method and what method do I use? I am not quite sure how to access it from other methods as it keeps saying variables of type "In" are not allowed.

this is the code I have done so far

public class Practice {

	public static void main(String[] args) throws FileNotFoundException {
		In in = new In(args[0]); // define the local variable
		abc(in);                 // pass it to the method
	}

	public static void abc(In in) throws FileNotFoundException {
		String s = in.readAll();     // use the method parameter
		double[][] boxes = readFile(s);

		System.out.println(boxes);
	}

	public static double[][] readFile(String s) throws FileNotFoundException {      
		File f = new File(s);
		Scanner scF = new Scanner(f);
		int R = scF.nextInt();
		int C = scF.nextInt();
		double[][] boxes = new double[R][C];
		while (scF.hasNextLine()) {
			for (int i = 0; i &lt; R; i++) {
				for (int j = 0; j &lt; C; j++) {
					boxes[i][j] = scF.nextInt();
				} //reads file and adds values to a double[][] array            
			}               
		}
		return boxes;
		//returns a double[][] array 
	}
}

Any help will be greatly appreciated!

huangapple
  • 本文由 发表于 2020年4月5日 21:10:18
  • 转载请务必保留本文链接:https://java.coder-hub.com/61043122.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定