-2

This is about a java console program in which there are some string variables which are used to search records and display in the console.
When i execute this program there comes the error message:

error: variable "variable name" might not have been initialized.

I want to know how i can initialize string variables in java console program. Here is the code:

Scanner sc=new Scanner(System.in);
String customername;String cname;
String caddress;String cphone
boolean found;
System.out.println("Enter customer name to search records:");
customername=sc.nextLine();
if (customername==cname)
{
  found=true;
  if(found){
    System.out.println("Customer name:"+cname);
    System.out.println("Customer address:"+caddress);
    System.out.println("Customer phone:"+cphone);}
  }
}

Here i want to search records saved in a text file and display records if cname==customername but error tells that string variable cname it is not initialized and also for caddress and cphone.
What should i do to initialize string variables and how to do this?

Giulio Caccin
  • 2,962
  • 6
  • 36
  • 57
  • 1
    You initialize variables by assigning values to them. Like: `String someVariable = "initialValue";` In Java, it is an error to try to read a local variable before it has been assigned a value. – dnault Sep 21 '19 at 04:42
  • thanks for the answer.The problem has been solved now.thanks – skperla Sep 21 '19 at 04:44
  • 2
    Also note that you should never use == to compare strings. Call the equals method instead. – GhostCat Sep 21 '19 at 07:27
  • 1
    And your whole code there, to first compare, then assign a value to that boolean to then immediately afterwards check that boolean value, that is nonsensical. – GhostCat Sep 21 '19 at 07:30
  • Finally: you accept answers by clicking on that check mark icon next to it. Writing a comment "I accept the answer" isn't what that other person really cares about... – GhostCat Sep 21 '19 at 09:43

1 Answers1

-1

If you don't have a default value then you can initialize your string variables to empty strings as below.

Scanner sc=new Scanner(System.in);
String customername = "";
String cname = "";
String caddress = "";
String cphone  = "";
boolean found = false;

System.out.println("Enter customer name to search records:");
customername=sc.nextLine();
if (customername.equals(cname))
{       
    System.out.println("Customer name:"+cname);
    System.out.println("Customer address:"+caddress);
    System.out.println("Customer phone:"+cphone);            
}
Mahesh
  • 107
  • 5