我在if-loop之前声明了我的变量但是我无法在循环之外访问它?

时间:2015-09-13 01:43:11

标签: java loops variables if-statement scope

所以我需要在循环之外使用我的变量,但是它从if-loops中获取它的值但是我一直收到这个错误:

  

变量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);
    }
}

1 个答案:

答案 0 :(得分: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在String pool中使用String池来不必要地创建新对象。