簡體   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