簡體   English   中英

嘗試捕獲塊中的可變范圍

[英]Variable scope in try catch block

我正在通過命令行創建一個用戶界面,該界面將要求1-4中的選項,並且我想進行錯誤檢查。 只能使用1-4之間的整數。 這是我到目前為止的代碼。 我希望該方法將userInput整數返回到另一個將對其進行處理的方法。

package contactmanager;

import java.util.InputMismatchException;
import java.util.Scanner;

/**
 *
 * @author andyjohnson
 */
public class UserInterface {

    public static Integer GetInput() {
        Scanner in = new Scanner(System.in);
        //Integer userInput;
        System.out.println("Welcome to the contact manager\nMake a selection below:");
        System.out.println("1)Display Contacts\n2)Add new business contact\n3)Add new personal contact\n4)Quit");
        try {
            Integer userInput = in.nextInt();
            if (userInput < 1 || userInput > 4) {
                System.out.println("Please enter a valid selection");
                UserInterface.GetInput();
            }

        } catch (InputMismatchException e) {
            e.getMessage();
            System.out.println("Please enter a valid selection");
            UserInterface.GetInput();
        }

        return userInput;

    }

}

我的return語句在IDE中帶有下划線,並告訴我它尚未初始化。 我想全局初始化它,但允許try語句更改值。 我已經試過this.userInput = userInput,但是我不知道我的范圍在哪里壞了。 我如何給try塊全局范圍? 我是Java的新手,所以一切都對您有所幫助。 謝謝!

您可以在try-catch塊之外聲明userInput變量:

package contactmanager;

import java.util.InputMismatchException;
import java.util.Scanner;

public class UserInterface {

    public static Integer GetInput() {
        Scanner in = new Scanner(System.in);
        System.out.println("Welcome to the contact manager\nMake a selection below:");
        System.out.println("1)Display Contacts\n2)Add new business contact\n3)Add new personal contact\n4)Quit");
        Integer userInput = null;
        try {
            userInput = in.nextInt();
            if (userInput < 1 || userInput > 4) {
                System.out.println("Please enter a valid selection");
                UserInterface.GetInput();
            }

        } catch (InputMismatchException e) {
            e.getMessage();
            System.out.println("Please enter a valid selection");
            UserInterface.GetInput();
        }

        return userInput;

    }

}

try-catch塊的作用域不同於僅與該方法的其余部分內聯編寫代碼。

我認為您遇到的問題是在try-catch塊中首先聲明變量userInput這一行:

Integer userInput = in.nextInt();

這是一個問題的原因:

考慮try-catch塊是否失敗。 然后會退還什么? 甚至沒有定義變量userInput ,因此Java不知道返回什么。

解決方法相對簡單。 您只需要將其從try-catch塊中移出即可。 那應該擺脫您的return錯誤。 我注意到您評論了此更改。 為什么?

但是我還有一個建議。 為什么要調用UserInterface.GetInput() 為什么在數據格式不正確的情況下,該方法為什么不接受有效輸入的參數而僅僅不調用它呢? 你用嗎? 這將消除對真正的全局范圍變量的需求。

由於此方法的編寫方式,它必須返回某種Integer ,除非您編寫該方法,否則該方法將引發在下游某處捕獲的異常。

我試圖做出一些我認為最有意義的修復:

Scanner in = new Scanner(System.in);
Integer userInput; // Integer representation of user input

try {
    Integer a = in.nextInt(); // if a can be assigned to an Integer this line work
    if (a < 1 || a > 4) {
        // called if the input can be assigned to an Integer and is within the range
        userInput = a;
    }

} catch (InputMismatchException e) {
    // otherwise the catch block is called
    System.out.println("Please enter a valid selection");
}

return userInput;

也許您想在范圍檢查中調用UserInterface.GetInput() 希望這可以幫助!

編輯:使用前哨標志而不是調用方法

Scanner input = new Scanner(System.in);
System.out.println("Please enter a valid Integer.  When done type DONE ");

// this method will keep cycling until the String DONE is typed
// you could make this condition whatever you want
while (!input.hasNext("DONE")) {

    String a = input.next(); // gets the next item from the Scanner

    try {
        Integer b = Integer.parseInt(a); // tries to 'cast' the String to an Integer

        if (b < 1 || b > 4) {
            System.out.println("Input is valid!");
        } else {
            System.out.println("Input is invalid!");
        }

    } catch (NumberFormatException e) {
        System.out.println("Please enter a valid selection!");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM