import java.util.开发者_高级运维Scanner;
public class Main extends Hashmap{
public static void main(String[] args) {
Hashmap hm = new Hashmap();
int x=0;
Scanner input = new Scanner(System.in);
do{
System.out.print("Enter any integer value between 1 to 12: ");
x = input.nextInt();
}while(x<=0 || x>12);
Scanner sc = new Scanner(System.in);
//int number;
do {
while (!sc.hasNextInt())
{
System.out.println("That's not a number!");
sc.next();
}
x = sc.nextInt();
}while(x>=0);
String month = hm.getEntry(x);
System.out.println(month);
}
}
here I need to restrict user from entering an alphabet.But its not working. pls help...
public static void main(String[] args) {
HashMap<Integer, String> hm = new HashMap<Integer, String>();
/**
* Populate hashmap.. Your logic goes here
*/
Scanner sc = new Scanner(System.in);
int x;
System.out.println("Enter a number between 1 and 12");
do {
while (!sc.hasNextInt()) {
System.out.println("That's not a number! Enter a number between 1 and 12");
sc.next();
}
x = sc.nextInt();
String month = hm.get(x);
System.out.println("The corresponding month is " + month);
} while (x >= 0);
}
I think this is what you are trying to achieve..
First, have a look at polygenelubricants comprehensive answer to your problem again. I'm pretty sure, he solved it for you in Example 3.
Then, as an alternative design for a user interface: accept any user input, validate the input and if the input is not correct, provide a helpful message and ask the user to enter a value again. This is much, much easier to implement and a user should be happy with this too.
精彩评论