BleepingComputer.com: catch syntax in java

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

catch syntax in java

#1 User is offline   sausage 

  • Forum Regular
  • PipPipPip
  • Find Topics
  • Group: Members
  • Posts: 317
  • Joined: 01-November 08
  • Gender:Male
  • Location:Louisville Colorado

Posted 05 November 2008 - 10:53 PM

So I need help with using the catch method

here's my code

int cclass;
System.out.println("Please choose your character class");
System.out.println("1) Fighter");
System.out.println("2) Theif");
System.out.println("3) Mage");
try
{
	 cclass = keyboard.nextInt();	
} 
catch ( InputMismatchException inputMismatchException )
{
	 System.err.printf( "\nException: %s\n",
		 inputMismatchException );
	 scanner.nextLine();
	 System.out.println(
		"You must an integer. Please try again.\n" );
}
f (cclass <=1)//the < is to solve the need for boolean in that statement
{
	 cclassname = Fighter; 
}
else if (cclass <=2)
{
	 cclassname = Theif; 
}
else
{
	  cclassname = Mage;
}//the new variable cclassname is used in dialogue inside my game and is already initialized using the String method
//Also, all of it is inside a public static void main(String[] args) method with import.java.util.*; at the top


What I get when I compile it is variable cclass might not have been initialized... help?
If I'm posting, I probably have something horribly wrong with my computer, there's no obvious explanation for it, that's just the way it is.

#2 User is online   Billy O'Neal 

  • Bleepin Engineer GRADUATE
  • PipPipPipPipPipPip
  • Find Topics
  • Group: Malware Response Instructor
  • Posts: 10,401
  • Joined: 17-January 08
  • Gender:Male
  • Location:Cleveland, Ohio

Posted 05 November 2008 - 11:05 PM

You didn't initialize cclass until you entered the try block:
{
cclass = keyboard.nextInt();
}

This means that cclass could still be pointing to completely random RAM when you try to access it later in your catch blocks.

You can't simply assume that INT is 0 just because you haven't put something there.

Change
int cclass;

to
int cclass = 0;

Billy3

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users