How can I validate data from scanner (Java) [duplicate] - java

This question already has answers here:
validate an integer AND make it 5 digits
(4 answers)
Closed 4 years ago.
I need to ask the user to input a number from 1 to 10 then get the factorial of this number, I was able to do everything except to validation of the user name ( To be within range && not a string)
package test2;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
int userInput = 0 ;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number from 2 to 100");
if (sc.nextInt() < 101) {
userInput = sc.nextInt();
}
System.out.println(userInput);
}
}

one Method you can try is
public static void main(String[] args) {
int userInput = 0 ;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number from 2 to 100");
while (!sc.hasNextInt())
{
System.out.println("wrong input");
sc.next();
}
if (sc.nextInt() < 101) {
userInput = sc.nextInt();
}
System.out.println(userInput);
}
}

int userInput = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number from 2 to 100");
while (!sc.hasNextInt()) {
System.out.println("Please enter number");
sc.next();
}
while(true) {
userInput = sc.nextInt();
if (userInput > 2 && userInput < 100) {
break;
}else{
System.out.println("Please enter a number between 2 to 100");
}
}
System.out.println(userInput);

Or simply use a do-while
do {
userInput = sc.nextInt();
} while (userInput < 1 || userInput > 10);

Related

Please help me be able to print out the if statements at the bottom of my code [duplicate]

This question already has answers here:
System.in.read() does not read
(2 answers)
Closed 1 year ago.
//i just need the if statements at the bottom to work as well. right now I can only input the numeric grade and the gpa, but i need the accept or reject lines of code to print too.
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
int studentGrade;
float gradePointav;
System.out.println("Please enter a your Numeric Grade:");{
studentGrade = (int) System.in.read();}
scan.nextLine();
System.out.println("Please enter a GPA:");{
gradePointav = (float) System.in.read();}
scan.nextLine();
if (gradePointav >= 3.0 && studentGrade >= 60) {
System.out.println("You have been Accepted!");
}
if(gradePointav <= 3.0 && studentGrade <= 60) {
System.out.print("You have been rejected.");
}
}
}
Scanner next line method will return input from terminal:
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
int studentGrade;
float gradePointav;
System.out.println("Please enter a your Numeric Grade:");
studentGrade = scan.nextInt();
System.out.println("Please enter a GPA:");
gradePointav = scan.nextFloat();
if (gradePointav >= 3.0 && studentGrade >= 60) {
System.out.println("You have been Accepted!");
} else if (gradePointav <= 3.0 && studentGrade <= 60) {
System.out.print("You have been Rejected.");
} else {
System.out.println("You are not defined");
}
}

a positive and negative checker with odd and even checker

How can I check if an input number is negative or positive, and if it is positive it will check again if it is odd or even, and if it's negative an error message will appear and ask again the user if he/she wants to check another number?
import java.util.Scanner;
public class OddEvenChecker{
public static void main(String[] args){
int integer=0;
Scanner sc = new Scanner(System.in);
while (true) {
if (integer>=0) {
System.out.print("Enter a positive Integer: ");//gets the user input
integer = sc.nextInt();
}
if (integer<0) { // checks if the entered number is a positive integer
System.out.println("Error");
System.out.print("Do you Want to Continue? y for Yes, n for No: ");
String choices = sc.nextLine();
} else if(integer>0) {
if (integer%2==0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
}
}
}
}
public class OddEvenChecker {
public static void main(String[] args) {
int integer = 0;
String flag = "y";
Scanner sc = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
do {
System.out.print("Enter a positive Integer: ");//gets the user input
integer = intScanner.nextInt();
if(integer>0) {
if(integer%2==0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
} else {
System.out.println("This is negative number. Try again.");
}
System.out.print("Do you want to Continue? y for Yes, n for No: ");
flag = sc.nextLine();
} while(!(flag.equals("n") || flag.equals("no")));
}
}
What do you think about this approach? Does it meet requirements?
do{
choices = sc.nextLine();
if(choices.equals("n") || choices.equals("no"){
return;
}
else if(choices.equals("y") || choices.equals("yes"){
break;
} else {
System.out.println("invalid key");
}
} while(!choices.equals("n") || (!choices.equals("no") || (!choices.equals("y") || (!choices.equals("yes"));
enter code here
public class OddEvenChecker{
public static void main(String[] args){
int integer=0;
Scanner sc = new Scanner(System.in);
while (true) {
if (integer>=0) {
System.out.print("Enter a positive Integer: ");
integer = sc.nextInt();
if(integer%2==0) {
System.out.println("Even");
}
else {
System.out.println("Odd");
}
}
if (integer<0) {
System.out.println("Error");
System.out.print("Do you Want to Continue? y for Yes, n for No: ");
String choices = sc.nextLine();
}
}
}
}//Maybe this is the best and easiest way to do this.

I would like put a optional "wrong number. Try again" when is

I have just started learn java codes, that is why might I have a simple question that is not simple for me.
I would like put a optional "wrong number. Try again" when is entered different number than secretNum. May you guys help me out on this code?
// I need learn how put "try again" when the number is != than guess number.
/* I have tried
* 1)Change the signal "==" or "!=".
* 2) do {
System.out.println("Guess what is the number 0 to 10: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
} while(secretNum != guess);{
System.out.println("Well done");
System.out.println();
System.out.println("Are you ready for the next step?");
System.out.println();
}
*/
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter name:");
if(sc.hasNextLine()) {
String userName = sc.nextLine();
System.out.println("Hello " + userName + ",");
System.out.println();
}
int secretNum = 5;
int secretNum2 = 15;
int guess = 0;
do {
System.out.println("Guess what is the number 0 to 10: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
} while(secretNum != guess);{
System.out.println("Well done\n");
System.out.println("Are you ready for the next step?\n");
}
// I need learn how put "try again" when the number is != than guess number.
/* I have tried
* 1)Change the signal "==" or "!=".
* 2) do {
System.out.println("Guess what is the number 0 to 10: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
} while(secretNum != guess);{
System.out.println("Well done");
System.out.println();
System.out.println("Are you ready for the next step?");
System.out.println();
}
*/
System.out.println("Enter Yes or No");
while(!sc.next().equals("yes")&& !sc.next().equals("no"));{
System.out.print("Yes");
}
do {
System.out.println("Guess what is the number 11 to 20: ");
if (sc.hasNextInt()) {
guess = sc.nextInt ();
}
}while(secretNum2 != guess);{
System.out.println("Congratulations");
System.out.println();
System.out.println("The End");
}
}
}
````````
You don't need do{} while() for the checks you want to do here, just while(){} loops would be enough.
Please try this code instead:
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter name:");
if (sc.hasNextLine()) {
String userName = sc.nextLine();
System.out.println("Hello " + userName + ",");
System.out.println();
}
int secretNum = 5;
int secretNum2 = 15;
int guess = 0;
System.out.println("Guess what is the number 0 to 10: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
while (secretNum != guess) {
System.out.println("Please try again\n");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
}
System.out.println("Well done\n");
System.out.println("Are you ready for the next step?\n");
System.out.println("Enter Yes or No");
while (!sc.next().equals("yes") && !sc.next().equals("no"))
{
System.out.print("Yes");
}
System.out.println("Guess what is the number 11 to 20: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
while (secretNum2 != guess) {
System.out.println("Please try again\n");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
}
System.out.println("Congratulations");
System.out.println();
System.out.println("The End");
}
}

Issue with looping in Java code

Use a while loop to keep asking the user to enter the order of
numbers until the user does give two numbers in the right order (first
smaller than second
Hi! i'm a beginner in java and I have this code but I can't loop the "error" message. it just prints 2 times
import java.util.Scanner;
public class Q6 {
public static void main(String[] args) {
int num1, num2;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type two numbers:");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
if (num1 < num2) {
int counter = num1;
while (counter <= num2) {
System.out.print(counter + " ");
counter = counter + 1;
}
}
else {
System.out.println("Error: the first number must be smaller than the second");
System.out.print("Please type two numbers: ");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
}
}
}
int num1,num2;
while (num1>=num2) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type two numbers");
System.out.printn("first number must be smaller than the second:)";
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
}
int num1,num2;
while (num1>=num2) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type two numbers:");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
if(num1>=num2) {
System.out.println("Error: First number must be smaller than the second.");
}
}

How to check if user input is String, double or long in Java

I'm a beginner in java. I want to check first if the user input is String or Double or int. If it's String, double or a minus number, the user should be prompted to enter a valid int number again. Only when the user entered a valid number should then the program jump to try. I've been thinking for hours and I come up with nothing useful.Please help, thank you!
import java.util.InputMismatchException;
import java.util.Scanner;
public class Fizz {
public static void main(String[] args) {
System.out.println("Please enter a number");
Scanner scan = new Scanner(System.in);
try {
Integer i = scan.nextInt();
if (i % 3 == 0 && (i % 5 == 0)) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i + "は3と5の倍数ではありません。");
}
} catch (InputMismatchException e) {
System.out.println("");
} finally {
scan.close();
}
}
One simple fix is to read the entire line / user input as a String.
Something like this should work. (Untested code) :
String s=null;
boolean validInput=false;
do{
s= scannerInstance.nextLine();
if(s.matches("\\d+")){// checks if input only contains digits
validInput=true;
}
else{
// invalid input
}
}while(!validInput);
You can also use Integer.parseInt and then check that integer for non negativity. You can catch NumberFormatException if the input is string or a double.
Scanner scan = new Scanner(System.in);
try {
String s = scan.nextLine();
int x = Integer.parseInt(s);
}
catch(NumberFormatException ex)
{
}
Try this one. I used some conditions to indicate the input.
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
int charCount = input.length();
boolean flag = false;
for(int x=0; x<charCount; x++){
for(int y=0; y<10; y++){
if(input.charAt(x)==Integer.toString(y))
flag = true;
else{
flag = false;
break;
}
}
}
if(flag){
if(scan.hasNextDouble())
System.out.println("Input is Double");
else
System.out.println("Input is Integer");
}
else
System.out.println("Invalid Input. Please Input a number");
Try this. It will prompt for input until an int greater than 0 is entered:
System.out.println("Please enter a number");
try (Scanner scan = new Scanner(System.in)) {
while (scan.hasNext()) {
int number;
if (scan.hasNextInt()) {
number = scan.nextInt();
} else {
System.out.println("Please enter a valid number");
scan.next();
continue;
}
if (number < 0) {
System.out.println("Please enter a number > 0");
continue;
}
//At this stage, the number is an int >= 0
System.out.println("User entered: " + number);
break;
}
}
boolean valid = false;
double n = 0;
String userInput = "";
Scanner input = new Scanner(System.in);
while(!valid){
System.out.println("Enter the number: ");
userInput = input.nextLine();
try{
n = Double.parseDouble(userInput);
valid = true;
}
catch (NumberFormatException ex){
System.out.println("Enter the valid number.");
}
}

Categories