-3

i'm a beginner at java scripting only been coding for no longer than 3 weeks and i've been stuck on this for a while.

I get the error variable vYourName might not have been initialized, when i compile. This is what i have wrote so far.

import java.util.Scanner;

public class GetInput

{

public static void main(String[] args){

    Scanner sc= new Scanner(System.in);//create a scanner object to collect user input
    String vYourName;
    String vPraise;
    System.out.print("Enter your name? >>");


  if(vYourName=="giacomo")
  {
    vYourName= sc.next();
    vPraise =vYourName + " ,hi there";
}
    else
{
    vYourName= sc.next();
    vPraise =vYourName + " how are you";
}
    System.out.println(vPraise);
}
}
Uli Köhler
  • 13,012
  • 16
  • 70
  • 120
  • possible duplicate of [Variables might not have been initialized](http://stackoverflow.com/questions/8284779/variables-might-not-have-been-initialized) and of course the ever-popular [How do I compare Strings in Java](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Brian Roach Feb 15 '14 at 04:04
  • Just check the variable **vYourName**, You have not taken any user input for that nor even initialized that. In this line- if(vYourName=="giacomo") You are trying to check a variable that is not initialized in any way – Jay Dharmendra Solanki Feb 15 '14 at 04:06
  • Go through line by line... You'll see it. – Josh M Feb 15 '14 at 04:12
  • i fixed the problem guys but it ignores the if and else statement its always writing back to me hi there i only want that to appear when i write "giacomo" and everything else to be responded by how are you any ideas? – user3312455 Feb 15 '14 at 04:24

3 Answers3

0

Simply initialize it before comparing it.

String vYourName = null;

or

String vYourName = "";

Scanner sc= new Scanner(System.in);
System.out.print("Enter your name? >>");
String vYourName = "";
String vPraise = "";
vYourName = sc.next();
vPraise = vYourName + ((vYourName.equals("giacomo"))? ", hi there" : ", how are you") ;
System.out.println(vPraise);
meda
  • 45,103
  • 14
  • 92
  • 122
  • it fixed the problem thanks! but one problem every word writes back hi there i only want the word giacomo to do that and all the others to write back to me how are you – user3312455 Feb 15 '14 at 04:18
0

Your checking whether the vYourName string equals to something before you even read it. Furthermore, you should use the .equals() method instead of the ==.

Kent Shikama
  • 3,910
  • 3
  • 22
  • 55
0

You have an instance variable String vYourName; with no value. What does the string hold? " ", "Hello World", ???

You always need to declare AND initialize any variables.

The proper way to do this would String vYourName = ""; this will default it to "" which holds nothing.

ChriskOlson
  • 513
  • 1
  • 3
  • 12