How to validate input type(java) [duplicate] - java

This question already has answers here:
How to verify that input is a positive integer in Java [closed]
(3 answers)
Closed 15 hours ago.
I have the following snippet of code and I don't know how to make sure that the user is entering a positive int. What can I do so that the code makes sure the input type is valid.
public static void main(String[] args)
{
//creates a scanner
Scanner output = new Scanner(System.in);
//declare all the variables
int fours;
//ask the user how many fours they have
System.out.println("How many 4's do you have");
fours = output.nextInt();
}
I tried using a do while loop like shown below, but it only makes sure that the input is greater than or equal to zero, but does not make sure it is an int.
do
{
System.out.println("How many 4's do you have");
fours = output.nextInt();
}
while(fours <= 0 );

You can check Scanner#hasNextInt:
Scanner sc = new Scanner(System.in);
System.out.println("How many 4's do you have");
while (!sc.hasNextInt()) {
sc.next(); // skip the invalid input
System.out.println("Please enter an integer");
}
int fours = sc.nextInt();

Related

Can I input in arrayList similar to array? [duplicate]

This question already has answers here:
How to append elements at the end of ArrayList in Java?
(4 answers)
Closed last year.
public void getDisMarks()
{
marks=new int[3];
System.out.print("Enter marks of Physics: ");
marks[0]=sc.nextInt();
System.out.print("Enter marks of Chemistry: ");
marks[1]=sc.nextInt();
System.out.print("Enter marks of Maths: ");
marks[2]=sc.nextInt();
}
So in this piece of code we are using array for 3 definite subjects. And we're using scanner class to input from the user. Let's say in the future I want to add a couple of more subject. So coding it again would not make it any flexible.
So I read that we could use arrayList, How can I use scanner class with arrayList similar to this piece of code.
You could do something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
System.out.println("How many marks to enter?");
int marksToEnter = sc.nextInt();
for (int i = 0; i < marksToEnter; i++) {
System.out.println("Enter next mark");
list.add(sc.nextInt());
}
System.out.println(list);
}

Using scanner to recognize both integers and strings, and stopping user input if a certain string is inputted [duplicate]

This question already has answers here:
How to type a string to end a integer Scanning process in Java
(3 answers)
Closed 2 years ago.
Trying to use scanner to recognize both integers and strings, and stopping user input if a certain string is inputted.
Scanner myObj = new Scanner(System.in);
System.out.println("Enter number of students");
int numberof = myObj.nextInt();
Need to make it so if the user types "end", the scanner no longer takes user input. I can't put the line int numberof = myObj.nextInt(); in a loop or something and limit the variable scope, as i'm using that value of numberof throughout the rest of my code.
You can use Scanner#next and then parse integers if needed. I wouldn't recommend just directly using Scanner#nextInt.
Scanner sc = new Scanner(System.in);
do {
System.out.println("Enter number of students");
String next = sc.next();
if (next.equals("end")) break;
else {
try {
int num = Integer.parseInt(next);
} catch (NumberFormatException e) {
System.out.println("Please enter a valid input");
}
}
} while (true);

How to use a Do-while loop that continuously prompts a user?

(I have a homework question that I've been stuck on that concerns "do-while loops" in Java. )
It is asking me to have a do-while loop that continues to prompt a user to enter a "number less than 100", up until the entered number is actually less than 100.
(It will run three tests:)
Ex: Test 1:
For the user input 123, 395, 25, the expected output is:
Enter a number (<100):
Enter a number (<100):
Enter a number (<100):
Your number < 100 is: 25
(Here's my code so far:)
public class NumberPrompt {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
int userInput = 0;
do {
System.out.println("Enter a number (<100):" );
System.out.println("Enter a number (<100):" );
System.out.println("Enter a number (<100):" );
userInput = userInput + 25;
} while (userInput > 100);
System.out.print("");
System.out.println("Your number < 100 is: " + userInput);
}
(My Output matches exactly with the Test 1 results above, but I realize I'm not setting up the loop right at all because when it does the second test of "-9", the output exactly the same as my first test:)
Enter a number (<100):
Enter a number (<100):
Enter a number (<100):
Your number < 100 is: 25
(This is my first week being introduced to loops, I searched around for some walk through examples but I haven't found many "Do" while loops that remind me of this one. If anyone has some good tips or guides to point me to I would greatly appreciate it.)
You don't need to write System.out.println("Enter a number (<100):" ); three times. It will be displayed automatically every time when user inputs value less than 100. And you are assigning value to userInput by your own instead of taking input from user. You should write the code given below.
do {
System.out.println("Enter a number (<100):" );
userInput = scnr.nextInt();
} while (userInput > 100);
System.out.println("Your number < 100 is " + userInput);
1.Reading value
As Juan's comment suggested, you are not reading user input value. Basically, this is done with nextInt() method. Morever, int is a primitive type and must be initialised. You choose the value of 0. So why not choosing 101 so that it starts with an incorrect value? Then you are sure that the while loop will be triggered:
public static void main(String... aArgs) {
Scanner sc = new Scanner(System.in);
// initialise at 101 to trigger the while loop
int userInput = 101;
// as we start at 101, it will enter the loop at least once
while (userInput > 100) {
System.out.println("Enter a number (<100):");
userInput = sc.nextInt();
}
System.out.println("Your number < 100 is: " + userInput);
}
2.Never trust the user
2.1 Exception catching
The above code may be sufficient for your assignement. However, for learning sake, I have a fundamental principal: never trust the user!. If the previous example, if an user inputs azerty, then your program will throw you an InputMismatchException. What's that? This error tells you that the scanner expected an int and you fed him with something else: it throws this up.
A simple analogy is: the scanner can only eat apple. You give him a pear: he takes a bit and throws that up: "I can only eat apple". To prevent your scanner from throwing up, you can ask him: "try a bit, and if this is not an apple, let's try something else"
In code, it gives you something like:
public static void main(String... aArgs) {
Scanner sc = new Scanner(System.in);
// initialise at 101 to trigger the while loop
int userInput = 101;
// as we start at 101, it will enter the loop at least once
while (userInput > 100) {
// tell the scanner to try something
try {
System.out.println("Enter a number (<100):");
userInput = sc.nextInt();
}
// if the input is not a number, tell him do this this:
catch (InputMismatchException e) {
System.out.println("This is not a number!");
}
}
System.out.println("Your number < 100 is: " + userInput);
}
If you are not familiar with try/catch clause, you can read this
2.1 Scanner feeding
The above code is not working. How? If you enter something which is not a number, like "aaaa", you will have an infinite of
Enter a number (<100):
This is not a number!
Why? Because the scanner did not throw your input out. Basically, he either should eat the pear (but he will throw up) or throw it to the dust bin but you never told him to throw it to the dust bin! The scanner needs to consume the input before trying the next input.
In a nutshell:
userInput starts at 101 so the while loop is entered
You enter aaaa.
The InputMismatchException is caught. The "This is not a number!" is printed out
userInput value did not change (still at 101), so the loop keeps going
At this stage, the scanner did not consume the previous input so the next input is still aaaa.
Go to 3. and start again
How to fix this? By telling the scanner to consume the input with next():
public static void main(String... aArgs) {
Scanner scnr = new Scanner(System.in);
// initialise at 101 to trigger the while loop
int userInput = 101;
// as we start at 101, it will enter the loop at least once
while (userInput > 100) {
// tell the scanner to try something
try {
System.out.println("Enter a number (<100):");
userInput = scnr.nextInt();
}
// if the input is not a number, tell him do this this:
catch (InputMismatchException e) {
// consume the incorrect input with scnr.next()
// so that user can enter another input
System.out.println(scnr.next() + " is not a number!");
}
}
System.out.println("Your number < 100 is: " + userInput);
}

The code runs again no matter what. [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
I don't know why, but the below code makes the user run the code again, whether they choose to or not. I've tried many things, but it doesn't work correctly.
Thanks!
public static void main (String [ ] args)
{
boolean a = true;
while (a)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: ");
int x = scan.nextInt();
System.out.print("\n\nEnter a second integer: ");
int z = scan.nextInt();
System.out.println();
System.out.println();
binaryConvert1(x, z);
System.out.println("\n\nWould you like to run this code again? Enter \"Y\" or \"N\".");
System.out.print("Enter your response here: ");
String RUN = scan.nextLine();
String run = RUN.toLowerCase();
if (run.equals("n"))
{
a = false;
}
System.out.println();
System.out.println();
}
System.out.println("Goodbye.");
}
Scanner.nextInt() doesn't consume the line ending characters from the buffer, which is why when you read the value of the "yes/no" question with scan.nextLine(), you'll receive an empty string instead of the value the user entered.
A simple way to fix this is to explicitly parse the integer from raw lines using Integer.parseInt():
System.out.print("Enter an integer: ");
int x = Integer.parseInt(scan.nextLine());
System.out.print("\n\nEnter a second integer: ");
int z = Integer.parseInt(scan.nextLine());

Dice Rolling Game

So in this dice rolling game, what the user inputs must follow the format of xdy, where "x" is the number of dice and "y" is the number of sides the dice has. If the input doesn't follow the format, the program should ask the user to put in another input.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner user_input = new Scanner(System.in);
String input;
System.out.println("Please enter the number and type of dice to roll in the format <number>d<sides>.");
input = user_input.nextLine();
while()
{
System.out.println("Input is not valid. Please enter a new input");
input = user_input.nextLine();
}
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(5);
My question is, how do I make the while loop check for a character between two integers?
One elegant way to do this would be with a Pattern:
Pattern p = Pattern.compile("\\d+d\\d+");
input = user_input.nextLine();
while (!p.matcher(input).matches) {
System.out.println("Input is not valid. Please enter a new input");
input = user_input.nextLine();
}
Separate numberOfSides and number OfDice into two variables and then do whatever you want with them.
String input="6d3";
int numSides=Integer.parseInt(input.split("d")[0]);
int numDice=Integer.parseInt(input.split("d")[1]);

Categories

Resources