为什么不编译?

Rya*_*ach -2 java

为什么这个班不编译?

import java.util.*;

public class Caesar
{
    public static void main(String [] args)
    {
        final boolean DEBUG = false;
        System.out.println("Welcome to the Caesar Cypher");
        System.out.println("----------------------------");
        Scanner keyboard = new Scanner (System.in);
        System.out.print("Enter a String : ");
        String plainText = keyboard.nextLine();
        System.out.print("Enter an offset: ");
        int offset = keyboard.nextInt();
        String cipherText = "";
        for(int i=0;i<plainText.length();i++)
        {
            int chVal = plainText.charAt(i);

            if (DEBUG) {int debugchVal = chVal;}

            chVal +=offset;

            if (DEBUG) {System.out.print(chVal + "\t");}

            while (chVal <32 || chVal > 127)
            {
                if (chVal < 32) chVal += 96;
                if (chVal > 127) chVal -= 96;

                if(DEBUG) {System.out.print(chVal+" ");}

            }

            if (DEBUG) {System.out.println();}

            char c = (char) chVal;
            cipherText = cipherText + c;

            if (DEBUG) {System.out.println(i + "\t" + debugchVal + "\t" + chVal + "\t" + c + "\t" + cipherText);}
        }
        System.out.println(cipherText);
    }
}
Run Code Online (Sandbox Code Playgroud)

Pét*_*rök 9

debugchValif块内定义变量:

if (DEBUG) {int debugchVal = chVal;}
Run Code Online (Sandbox Code Playgroud)

所以它只存在于那个区块内.稍后再次引用它时:

if (DEBUG) {System.out.println(i + "\t" + debugchVal + "\t" + chVal + "\t" + c + "\t" + cipherText);}
Run Code Online (Sandbox Code Playgroud)

它不再在范围内,因此编译器尽职尽责地发出错误.

像这样修改第一个代码部分:

int debugchVal;
if (DEBUG) {debugchVal = chVal;}
Run Code Online (Sandbox Code Playgroud)


cod*_*ict 5

变量声明debugchVal在if块内:

if (DEBUG) {int debugchVal = chVal;}
Run Code Online (Sandbox Code Playgroud)

因此,它不会在if块之外可用.将声明移到if块之外:

int debugchVal = /*some default value that makes sense if DEBUG is false */;
if (DEBUG) {debugchVal = chVal;}
Run Code Online (Sandbox Code Playgroud)


Jac*_*ack 5

因为您debugchVal在范围内定义并且稍后尝试使用它.

你在做:

if (DEBUG) {int debugchVal = chVal;}
Run Code Online (Sandbox Code Playgroud)

然后:

if (DEBUG) {System.out.println(i + "\t" + debugchVal + "\t" + chVal + "\t" + c + "\t" + cipherText);}
Run Code Online (Sandbox Code Playgroud)

但由于debugchVal在大括号之间定义,因此它只是该范围的本地定义.尝试将其移出范围:

int debugchVal = -1;
if (DEBUG) { debugchVal = chVal; }
Run Code Online (Sandbox Code Playgroud)