Jump to content
Sign in to follow this  
masokis

Error Handling Bila Terima Huruf

Recommended Posts

Dear PDC.. here is my problem:
I create an java program in cmd. Here ..take look at first to the snippet of my code:

[code]import java.io.*;
class Test
{


public static void main (String args[] )throws IOException
{
int menus;
String input;

BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
{
Arahan(); //<--- calling the function
System.out.print(" \t\t-1 Option A\n \t\t-2 Option B \n \t\t-3 Option C\n");
System.out.print("\n # Pilihan \t\t: ");
input = stdin.readLine();
menus = Integer.parseInt(input);
Menu(menus); //<--- calling the function & pass value
}
}

static void Arahan()
{


System.out.println(" ======================");
System.out.println(" => menu : ");
System.out.println(" ======================");
}

static void Menu(int menu) // <-- pass the value into functiom
{
if(menu == 1)
System.out.println("u get 1 coz u enter "+menu);
if(menu == 2)
System.out.println("u get 2 coz u enter "+menu);
if(menu == 3)
System.out.println("u get 3 coz u enter "+menu);
else
System.out.print("It's only 3 option..lma0..");
}
}[/code]

now, you can see.. my program will get input from user.
the user should enter number only...
but when user mistaken enter CHAR @ ALPHABET.. my program will crash.

image > http://img841.imageshack.us/img841/125/captureydc.png

how to handle this problem? can i warning the user without crashing my program ?

Share this post


Link to post
Share on other sites
Use try catch between this line..

[code]
input = stdin.readLine();
menus = Integer.parseInt(input);
[/code]

by the way below statement should be in If -- Else If right?

[code]
if(menu == 1)
System.out.println("u get 1 coz u enter "+menu);
if(menu == 2)
System.out.println("u get 2 coz u enter "+menu);
if(menu == 3)
System.out.println("u get 3 coz u enter "+menu);
else
System.out.print("It's only 3 option..lma0..");
[/code]

Share this post


Link to post
Share on other sites
yep..setel dah masalah.
kawan maya saya dari (my0d.my) dah bantu utk saya.
solusinya sama mcm awak katakan tu. saya perlu taruk try catch utk
filter input user, sma ada char @ int.

*kod tu snippet ringkasan kod saya je. nak post semua, xleh..panjang 1 & lagi kod ni
utk mini projek. kan leak 0ut..susah lak. so masokis taip je, ringkasan kod snippet mcmtu..
leh plak terlupa masuk if else... hahaa.. copy paste je line tu.. btw, ahaksz28 ..kamu je yang perasan
pasal tu.. kat forum lain yg masokis tanya..xsedar pun :)

Share this post


Link to post
Share on other sites
Guest
This topic is now closed to further replies.
Sign in to follow this  

×
×
  • Create New...