Skip to content

Instantly share code, notes, and snippets.

@dforsyth
Forked from anonymous/gist:1227536
Created September 19, 2011 20:49
Show Gist options
  • Select an option

  • Save dforsyth/1227569 to your computer and use it in GitHub Desktop.

Select an option

Save dforsyth/1227569 to your computer and use it in GitHub Desktop.
all instances of String "name" and int "secondDenom": local variable name may not have been initialized
import java.util.Scanner;
public class Money {
public static void main (String args[]) {
Scanner sc= new Scanner(System.in);
String name, secondName; //Name is for the first branch, etc.
int nameOrDenom, firstDenom, secondDenom; //firstDenom is for the first branch, etc.
System.out.print("Type 1 to enter a last name, 2 to enter a denomination: ");
nameOrDenom= sc.nextInt(); // enter 2
if (nameOrDenom == 1) {
System.out.println("Enter a name: ");
name= sc.next();
}else if (nameOrDenom == 2) {
System.out.println("Enter a denomination: ");
secondDenom= sc.nextInt(); // enter any denomination
}else System.out.println("Invalid input value!");
// we have reached this block, name has yet to be set
// *** this will not be skipped. name == ? here? you should do name = null at the top and then add if name != null or some other boolean logic to escape the init problems.
if (name.equals("Jefferson") || name.equals("Jackson") || name.equals("Grant")) { // we will crash here
System.out.println("What denomination does " + name + " appear on? ");
firstDenom= sc.nextInt();
if((name.equals("Jefferson") && firstDenom == (2) ||
(name.equals("Jackson") && firstDenom == (20) ||
(name.equals("Grant") && firstDenom == (50)))))
System.out.println("Right!");
else System.out.println("Wrong!");
}else System.out.println("Invalid name!");
if (secondDenom == 2 || secondDenom == 20 || secondDenom ==50) {
System.out.println("Who is on the " + secondDenom +" dollar bill?");
secondName= sc.next();
if (secondDenom == 2 && secondName.equals("Jefferson") ||
secondDenom == 20 && secondName.equals("Jackson") ||
secondDenom == 50 && secondName.equals("Grant"))
System.out.println("Right!");
else System.out.println("Wrong!");
}
else { System.out.println("Invalid choice!"); }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment