Home > Back-end >  Why can only enter a number?
Why can only enter a number?

Time:04-23

Why can only enter a number, enter the second number?

 public class Demo extends Exception {//custom Exception, must inherit the Exception or its subclasses 
Public Demo () {
Super ();
}
Public Demo (String code) {
Super (code);
}
}

 import Java. Util. Scanner; 

Public class Test {

Public static void main (String [] args) {
//TODO Auto - generated method stub
System. The out. Println (" code: ");
Scanner input=new Scanner(System.in);

Try {
Int code=input. NextInt ();
Show (code);
} the catch (Demo e) {
//TODO Auto - generated the catch block,
e.printStackTrace();
} the catch (Exception e) {
e.printStackTrace();
}
System. The out. Println (" the end ");
}
Public static void show (int code) throws Demo {
If (code<1 | | code> 3) {
Throw new Demo (" course coding cross-border ");//use throws keyword statement exception object
} else if (code==1) {
System. The out. Println (" c + + ");
} else if (code==2) {
System. The out. Println (" Java ");
}
The else {
System. The out. Println (" mysql ");
}
}
}

CodePudding user response:

It is ok to add a loop
While (1) {
Try {
Int code=input. NextInt ();
Show (code);
} the catch (Demo e) {
//TODO Auto - generated the catch block,
e.printStackTrace();
} the catch (Exception e) {
e.printStackTrace();
}
System. The out. Println (" the end ");
}
}

CodePudding user response:

Slightly changed, throw an exception, stop
 

Public class Test {

Public static void main (String [] args) {
//TODO Auto - generated method stub
System. The out. Println (" code: ");
Try {
While (true) {
Show ();
}
} the catch (Demo e) {
//TODO Auto - generated the catch block,
e.printStackTrace();
} the catch (Exception e) {
e.printStackTrace();
}
System. The out. Println (" the end ");
}
Public static void show () throws Demo {
Scanner input=new Scanner(System.in);
Int code=input. NextInt ();
If (code<1 | | code> 3) {
Throw new Demo (" course coding cross-border ");//use throws keyword statement exception object
} else if (code==1) {
System. The out. Println (" c + + ");
} else if (code==2) {
System. The out. Println (" Java ");
}
The else {
System. The out. Println (" mysql ");
}
}
}
  • Related