【问题标题】:I declared my variable before the if-loop but I can't access it outside of the loop?我在 if 循环之前声明了我的变量,但我无法在循环之外访问它?
【发布时间】:2015-12-09 07:35:29
【问题描述】:

所以我需要在循环之外使用我的变量,但它从其中一个 if 循环中获取其值,但我不断收到此错误:

变量newLastName已经在方法main(java.lang.String[])中定义了

但我从来没有收到变量newFirstName 的错误。

import java.util.Scanner;

public class Meme
{
    public static void main (String[] args)
    {
       Scanner scan = new Scanner (System.in);

       System.out.println("Please enter your first name.");
       String firstName = scan.nextLine();
       char firstChar = firstName.charAt(0);
       System.out.println("Please enter your last name.");
       String lastName = scan.nextLine();
       char lastChar = lastName.charAt(0);

       String newFirstName = null;

       if (firstChar =='A')
       {
         String newfirstname = new String("Applebees");
       }
       if (firstChar =='B')
       {
         String newfirstname = new String("Btchstick");
       }  
       if (firstChar =='C')
       {
         String newfirstname = new String("Cathy");
       }
       if (firstChar =='D')
       {
         String newfirstname = new String("Donger");
       }
       if (firstChar =='E')
       {
         String newfirstname = new String("Egg");
       }

       String newLastName = null;

       if (lastChar =='A')
       {
           String newLastName = new String("Ant Hill Supreme");
       }
       if (lastChar =='B')
       {
           String newLastName = new String("Blue Jay Junior");
       }
       if (lastChar =='C')
       {
           String newLastName = new String("...Catwoman?");
       }
       if (lastChar =='D')
       {
           String newLastName = new String("Dipstick");
       }
       if (lastChar =='E')
       {
           String newLastName = new String("Egg-Egg");
       }

       System.out.println("Your new name is: " + newFirstName + " " + newLastName);
    }
}

【问题讨论】:

  • 没有if loop 这样的东西。循环是可能被多次执行的代码块。在它到达最后一条语句后,它循环回到第一条语句(也许)。这就是为什么它被称为循环。

标签: java loops variables if-statement scope


【解决方案1】:

您正在 if 块中重新声明它。不要这样做。

改变

String newFirstName = null;

if (firstChar =='A')
{
  // the variable below is declared inside the if block and is
  // thus local to and visible only in the if block
  String newfirstname = new String("Applebees");
}

String newFirstName = null;

if (firstChar =='A')
{
  newFirstName = "Applebees";
}

编辑:根据paisanco的评论:

另外还有一个错字,块外是newFirstName,块内是newfirstname

编辑2:根据elliott-frisch的评论:

请不要使用new String(...)

这会在字符串池时阻止 Java 使用字符串池,从而不必要地创建新对象。

【讨论】:

  • 另外还有一个错字,块外newFirstName,块内newfirstname。
  • 请不要使用new String
猜你喜欢
  • 1970-01-01
  • 2022-07-18
  • 1970-01-01
  • 2010-09-29
  • 1970-01-01
  • 2013-07-03
  • 1970-01-01
  • 1970-01-01
  • 2021-05-22
相关资源
最近更新 更多