繁体   English   中英

是否可以在 main 方法之外使用 Scanner 并仍然调用它?

[英]Is it possible to use the Scanner outside the main method and still call it in?

所以我想做的是使用我的扫描仪方法 go 保存用户在 for 循环中输入的输入,但是我如何调用他们输入的特定类型的输入? 我的意思是,假设用户输入 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 作为问题方法和答案方法的输入。 在 main 方法或任何方法中,我如何调用 10 或 12 的输入。

package com.ez.ez;
import java.util.Scanner;
public class ReWrittingBetterCode{
        public static void Questions(){
        for (int i = 1; i <= 10; i++) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a question "+i+"/10");
        String firstQuestion = scanner.nextLine();
        }
    }
    public static void Answer() {
        for (int i = 1; i <= 10; i++) {
        Scanner scanner = new Scanner(System.in); 
        System.out.println("Enter a answer "+i+"/10");
        String answerAnswer = scanner.nextLine();
        }

    }

    public static void main (String[] args) {
        Questions();
        Answer();

    } 
}

您需要分配一个数组来保存问题。 然后,当您提示答案时,您可以重复这些问题。 为了与你的循环保持一致,你应该有一个名为noq的变量或一些问题,并在你使用 for 循环时在任何地方使用它。

static int noq = 10;
static String[] questions = new String[noq];
static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
    Questions();
    Answer();

}

public static void Questions() {
    for (int i = 1; i <= noq; i++) {
        System.out.println("Enter a question " + i + "/" + noq);
        String firstQuestion = scanner.nextLine();
        questions[i - 1] = firstQuestion;
    }
}

public static void Answer() {
    for (int i = 1; i <= noq; i++) {
        System.out.println(questions[i - 1]);
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a answer " + i + "/" + noq);
        String answerAnswer = scanner.nextLine();
    }
}

您还应该避免在任何地方使用 static。 我不得不这样做以简化示例。 查看Java 教程,了解有关 Java 编程的更多信息,重点是 arrays 和static关键字的使用。

所以我想要做的是使用我的扫描仪方法来保存用户在 for 循环中放入的输入,但是我如何调用他们放入的特定类型的输入? 我的意思是,假设用户输入 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 作为问题方法和答案方法的输入。 在主方法或任何方法中,我如何调用 10 或 12 的输入。

package com.ez.ez;
import java.util.Scanner;
public class ReWrittingBetterCode{
        public static void Questions(){
        for (int i = 1; i <= 10; i++) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a question "+i+"/10");
        String firstQuestion = scanner.nextLine();
        }
    }
    public static void Answer() {
        for (int i = 1; i <= 10; i++) {
        Scanner scanner = new Scanner(System.in); 
        System.out.println("Enter a answer "+i+"/10");
        String answerAnswer = scanner.nextLine();
        }

    }

    public static void main (String[] args) {
        Questions();
        Answer();

    } 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM