Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java try块中的代码被忽略,为什么?_Java_Try Catch - Fatal编程技术网

Java try块中的代码被忽略,为什么?

Java try块中的代码被忽略,为什么?,java,try-catch,Java,Try Catch,我是编程新手,一直试图通过编写一个简单的程序来学习Java的基础知识,该程序将对某些文本应用Caesar变换。我已经能够做到这一点,到目前为止,我的代码所做的是: 询问用户希望文本移动多少单位。 提示用户输入一些文本。 应用Caesar移位的单位数并打印结果。 以下是工作代码: import java.util.Scanner; class Shift{ public static void main(String[] args){ //This will scan for user

我是编程新手,一直试图通过编写一个简单的程序来学习Java的基础知识,该程序将对某些文本应用Caesar变换。我已经能够做到这一点,到目前为止,我的代码所做的是:

询问用户希望文本移动多少单位。 提示用户输入一些文本。 应用Caesar移位的单位数并打印结果。 以下是工作代码:

import java.util.Scanner;
class Shift{

public static void main(String[] args){

    //This will scan for user input.
    Scanner sc = new Scanner(System.in);
    System.out.print("Shift by this many characters (0-25): ");
    int shift = sc.nextInt();
    sc.nextLine();//Skips over the whitespace after the integer
    System.out.print("Enter Text: ");
    String input = sc.nextLine();
    sc.close();

    //Initialise a character array containing every letter in the alphabet. 
    char[] alphabetArray = {'a','b','c','d','e','f','g','h','i','j','k','l','m',
                            'n','o','p','q','r','s','t','u','v','w','x','y','z'};
    char[] alphabetArrayCaps = {'A','B','C','D','E','F','G','H','I','J','K','L','M',
                                'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

    //Initialise the two variables that will be used in the next step.
    char[] constantArray = input.toCharArray();
    char[] output = input.toCharArray();

    //Implement a Caesar shift by the given number of units.
    for (int i=0; i < constantArray.length; i++){ //cycles through the user input character by character
        for (int j=0; j <= 25; j++){ //cycles through the alphabet
            if (constantArray[i] == alphabetArray[j]){
                    output[i] = alphabetArray[(j+shift)%26];
            }
            else if (constantArray[i] == alphabetArrayCaps[j]){
                        output[i] = alphabetArrayCaps[(j+shift)%26];
            }
        }
    }
    System.out.println(output);
    }
    }
此代码的问题在于,当要求用户输入整数时,如果输入了其他内容,则会出现异常。我认为这将是一个学习异常处理的好地方,并且已经提到了如何为此使用try-catch块

我遇到的问题是下面的代码似乎完全忽略了我的try块。我认为这是因为我的try块包含声明整数移位的行,当我向下滚动到代码中实际使用移位的位置时,会收到一条警告,说明移位无法解析为变量,并且无法编译

这是导致问题的代码,唯一的区别是我在try块中包含了一行,并在它后面添加了一个catch块,它应该会打印一条错误消息,尽管我还没有编译代码,所以还没有机会使用它并查看它的实际功能

import java.util.Scanner;
class Shift{

public static void main(String[] args){

    //This will scan for user input.
    Scanner sc = new Scanner(System.in);
    System.out.print("Shift by this many characters (0-25): ");

    try {
        int shift = sc.nextInt();
    }
    catch (java.util.InputMismatchException e){
        System.err.println("InputMismatchException: " + e.getMessage());                        
    }

    sc.nextLine();//Skips over the whitespace after the integer
    System.out.print("Enter Text: ");
    String input = sc.nextLine();
    sc.close();

    //Initialise a character array containing every letter in the alphabet. 
    char[] alphabetArray = {'a','b','c','d','e','f','g','h','i','j','k','l','m',
                            'n','o','p','q','r','s','t','u','v','w','x','y','z'};
    char[] alphabetArrayCaps = {'A','B','C','D','E','F','G','H','I','J','K','L','M',
                                'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

    //Initialise the two variables that will be used in the next step.
    char[] constantArray = input.toCharArray();
    char[] output = input.toCharArray();

    //Implement a Caesar shift by the given number of units.
    for (int i=0; i < constantArray.length; i++){ //cycles through the user input character by character
        for (int j=0; j <= 25; j++){ //cycles through the alphabet
            if (constantArray[i] == alphabetArray[j]){
                    output[i] = alphabetArray[(j+shift)%26];
            }
            else if (constantArray[i] == alphabetArrayCaps[j]){
                        output[i] = alphabetArrayCaps[(j+shift)%26];
            }
        }
    }
    System.out.println(output);
    }
    }

那么,为什么这一个小小的变化突然停止了移位的声明呢?

在块外声明移位。出现问题是因为移位的作用域在try only中。将其更改为:

int shift=0;
try {
    shift = sc.nextInt();
}

变量被限制在其声明的范围内。有关更多信息,请参阅或查看是否希望获得技术支持,在您的情况下,以局部变量声明范围开头的行是相关的

作用域的最简单解释是它们在其中声明的{…}对

就你而言:

...
try {
    int shift = sc.nextInt();
} ...
变量shift在该try块的{…}外部不可见。您必须在更高的范围内声明它,例如,作为方法的局部变量。但是,在try块的情况下,如果您只是将声明移到外部,您仍然会遇到一个变量可能被用于未初始化警告,因为在这种情况下:

int shift;

try {
    shift = sc.nextInt();
} catch (...) {
    ...
}
nextInt引发异常的代码路径仍然可以使shift保持未初始化状态。在这种情况下,要解决此问题,一个选项是仅对其进行初始化:

int shift = 0;

try {
    shift = sc.nextInt();
} catch (...) {
    ...
}
另一个选项是确保即使引发异常也能获取值:

int shift;

try {
    shift = sc.nextInt();
} catch (...) {
    shift = 0;
    ...
}
第三种选择是以这样一种方式构造代码,即在抛出异常时从不尝试使用shift,尽管这不太适合您的示例,但为了完整性:

int shift;

try {
    shift = sc.nextInt();
} catch (Exception x) {
    throw x;
}

// shift can never be used uninitialized here
第四种选择是以这样的方式构造代码,即在try块之外不需要移位:


问题是,当您在try块内声明变量时,该变量的作用域就是该try块。一旦try块完成执行,try块中声明的所有变量都将被擦除。您需要将声明移到try块之外。像这样:

int shift = 0;
try {
    shift = sc.nextInt();
}
catch (java.util.InputMismatchException e){
    System.err.println("InputMismatchException: " + e.getMessage());                        
}

希望这能有所帮助:

在Java中,无论何时在块内声明变量,都是对该变量进行本地声明。这意味着该变量仅在声明它的块中可见。在本例中,由于您在try块内声明了移位,因此在try之外的任何位置都看不到移位。要解决此问题,只需在try块之外声明它,如下所示:

int shift;
try {
    shift = sc.nextInt();
}
...

您可以在此处了解有关Java声明范围的更多信息:

此处不提供答案,但如果您将char数组声明更改为char[]alphabetArray=abcdefghijklmnopqrstuvwxyz.toCharArray和char[]alphabetArrayCaps=abcdefghijklmnoprstuvxyz.toCharArray,则会更容易些@itrollin98我在想,当我这么做的时候,一定有一个更简单的方法。这是一个非常好的提示,谢谢。请注意,这将导致移位可能被用于未初始化错误,除非您对其进行初始化或确保catch块也给它一个值。@JasonC您完全正确。我没有注意到。我改了。
int shift;
try {
    shift = sc.nextInt();
}
...