简体   繁体   中英

I declared my variable before the if-loop but I can't access it outside of the loop?

So I need to use my variable outside of the loop but it gets its value from inside one of the if-loops but I keep getting this error:

variable newLastName is already defined in method main(java.lang.String[])

But I never get that error for the variable 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);
    }
}

You're re-declaring it inside the if block. Don't do this.

Change

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");
}

to

String newFirstName = null;

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

Edit: as per paisanco 's comment:

Plus there is a typo, newFirstName outside the block, newfirstname inside the block

Edit 2: as per elliott-frisch 's comment:

Please don't use new String(...) .

This creates new objects needlessly by preventing Java from using the String pool when String pool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM