如何在java循环外的while循环中使用变量?

How to use variable in a while loop outside of the loop in java?

我有一个在 while 循环中设置的变量,因为它正在从文件中读取。我需要从循环外部访问和使用代码,因为我在 if 语句中使用变量,而 if 语句不能在 while 循环中,否则它将重复多次。这是我的代码。

 BufferedReader br = null;

            try {

                String sCurrentLine;

                br = new BufferedReader(new FileReader("C:\Users\Brandon\Desktop\" + Uname + ".txt"));

                while ((sCurrentLine = br.readLine()) != null) {
                    System.out.println(sCurrentLine);

                }if(sCurrentLine.contains(pwd)){System.out.println("password accepted");}

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (br != null)br.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

将 if 语句放入 for 循环中,但使用 break:

while...
    if(sCurrentLine.contains(pwd)){
        System.out.println("password accepted");
        break;
    }

这会跳出 for 循环,因此一旦找到密码,它就会停止循环。你不能真正将 if-check 移到循环之外,因为你想检查密码的每一行直到找到它,对吗?

如果这样做,则不需要将 sCurrentLine 变量移出循环。如果您想执行 sCurrentLine.equals(pwd) 而不是使用 contains.

,您可能还需要仔细检查

您已经在 while 循环外声明了 sCurrentLine。问题是您在下一行中一次又一次地使用它。如果您仍然希望它打印文件并且您正在尝试做的是记住已找到密码或在哪一行找到密码,请尝试以下操作:

    BufferedReader br = null;
    boolean pwdFound = false;
    String pwdLine = "";


        try {

            String sCurrentLine;

            br = new BufferedReader(new FileReader("C:\Users\Brandon\Desktop\" + Uname + ".txt"));

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
                if(sCurrentLine.contains(pwd)){
                    System.out.println("password accepted");
                    pwdFound = true;
                    pwdLine = sCurrentLine;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

布尔标志=假; while ((sCurrentLine = br.readLine()) != null) {

   if(sCurrentLine.contains(pwd))
   {
      flag = true;
      break;
   }

} 如果(标志){System.out.println("password accepted");}