I'm a beginner in Java and the problem that I've run into is I'm not sure how to chain input validation together so that the proper response to the user's incorrect input is given. For example, when the user enters something that's not a letter, the program does tell the user that what they've entered is not a letter, but if I then enter more than one letter, the program doesn't print out the correct response. It's based on whichever mistake the user makes first.
I appreciate all feedback.
String input;
final Pattern alphabet = Pattern.compile("^[A-Za-z]$");
Scanner kb = new Scanner(System.in);
System.out.println("Enter a letter of the alphabet: ");
input = kb.nextLine();
while (!alphabet.matcher(input).matches())
{
System.out.println("That's not a letter, try again.");
input = kb.nextLine();
}
while (input.length() > 1 )
{
System.out.println("Please enter only one letter");
input = kb.nextLine();
}
kb.close();
You can try to do likes this: Make it become check condition in if and get the result
final Pattern alphabet = Pattern.compile("^[A-Za-z]$");
Scanner kb = new Scanner(System.in);
public void drive_main() {
System.out.println("Enter a letter of the alphabet: ");
String input = getInput();
while (input == null) {
input = getInput();
}
}
public String getInput() {
String result;
result = kb.nextLine();
if (!alphabet.matcher(result).matches()) {
System.out.println("That's not a letter, try again.");
return null;
}
if (result.length() > 1) {
System.out.println("Please enter only one letter");
return null;
}
return result;
}
OR you can assign you input to a new class package (input, error, and have an error or not) make it more flexible.
final Pattern alphabet = Pattern.compile("^[A-Za-z]$");
Scanner kb = new Scanner(System.in);
public void drive_main() {
System.out.println("Enter a letter of the alphabet: ");
InputSet input = getInput(kb.nextLine());
while (input.isError) {
System.out.println(input.errorMessage);
input = getInput(kb.nextLine());
}
}
public InputSet getInput(String input) {
InputSet result = new InputSet(input, false, "");
if (!alphabet.matcher(result.input).matches()) {
result.errorMessage = "That's not a letter, try again.";
result.isError = true;
}
if (result.input.length() > 1) {
result.errorMessage = "Please enter only one letter";
result.isError = true;
}
return result;
}
private class InputSet {
String input;
boolean isError;
String errorMessage;
InputSet() {
}
InputSet(String input, boolean isError, String errorMessage) {
this.input = input;
this.isError = isError;
this.errorMessage = errorMessage;
}
}
1st is you should not use the while loop to check the condition.
2nd design your program properly loop > verify error.
You should do more good practical and clean code than you can easily find the error. Try to use less loop as possible it will cause more error and the program memory using
Related
I want to put if () condition to length, So that the user can enter numbers only, if he enters string or char, an error appears.
System.out.print("Determine the length of array> ");
int length = input.nextInt();
You can use Scanner#hasNextInt to guard against invalid input.
if(input.hasNextInt()){
int length = input.nextInt();
System.out.println(length);
} else System.out.println("Invalid input");
One of the ways you could achieve it is as below:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Integer val = null;
try {
val = scan.nextInt();
System.out.println(val);
// do whatever you want to do with your input value
} catch (Exception exception) {
System.out.println("you can enter integer only");
// exit program or log error message
}
}
You can use java regex,which is only looking numbers
^[0-9]*$
So let's check if this is valid,
public static void main(String[] args) {
boolean valid = false;
String regexForNumbers = "^[0-9]*$";
Scanner scanner = new Scanner(System.in);
while (!valid) {
System.out.print("Input Value:");
String s = scanner.nextLine();
if(!s.matches(regexForNumbers)){
valid= false;
System.out.println("Not only Numbers, try again\n");
}else{
valid = true;
System.out.println("Only Numbers:"+ s);
}
}
}
So what happens is if the user input contains only numbers the execution will end, otherwise, it will keep asking the user to input, and the output of this simple logic will be.
Input Value:maneesha
Not only Numbers, try again
Input Value:maneesha123
Not only Numbers, try again
Input Value:123
Only Numbers:123
I'm bulding a console application where I am trying to force a user to enter an int as a possible answer to a question otherwise the same question is repeated to the user.Thus, the user cannot move on without entering the proper data type.
below is my sample code.
Scanner scanner = new Scanner(System.in);
int userInput = 0;
do {
AskQuestion();
if(scanner.hasNextInt()) {
userInput = scanner.nextInt();
}
}
while(!scanner.hasNextInt()) ;
While I know this can be done in C#, I'm not exactly sure how to do it in java without getting stuck in an infinite loop. How do I get my code to do what I want to do? Please help!
You can use something like this. It'a a pretty simple flag combined with the use of the Scanner class.
boolean flag = false;
int val = 0;
while(!flag){
System.out.println("Something");
if(sc.hasNext()){
if(sc.hasNextInt()){
val = sc.nextInt();
flag = true;
}
else{
sc.next();
}
}
}
Try this:
Scanner scanner = new Scanner(System.in);
int userInput;
while(true) {
AskQuestion();
if (scanner.hasNextInt()) {
userInput = scanner.nextInt();
break;
}
scanner.next(); // consume non-int token
}
Another alternative which utilizes the Scanner#nextLine() method along with the String#matches() method and a small Regular Expression (RegEx) to ensure that the supplied string does indeed contain all numerical digits:
Scanner scanner = new Scanner(System.in);
String userInput = "";
int desiredINT = 0; // Default value.
while (desiredINT == 0) {
AskQuestion();
userInput = scanner.nextLine();
if (userInput.matches("\\d+")) {
desiredINT = Integer.parseInt(userInput);
if (desiredINT < 1 || desiredINT > 120) {
System.out.println("Invalid Input! The age supplied is not "
+ "likely! Enter a valid Age!");
desiredINT = 0;
}
}
else {
System.out.println("Invalid Input! You must supply an Integer "
+ "value! Try Again...");
}
}
System.out.println("Your age is: --> " + desiredINT);
And the AskQuestion() method:
private void AskQuestion() {
System.out.println("How old are you?");
}
This is nice and short one
Scanner scanner = new Scanner(System.in);
do askQuestion();
while(!scanner.nextLine().trim().matches("[\\d]+"));
Tell me if you like it
Note it just tell you if number was an int , and keeps repeating if not, but doesn't give you that int back , tell me if you need that, i shall find a way
My solution might be a bit bloated, but I hope it's nice and clear what's going on. Please do let me know how it can be simplified!
import java.util.Scanner; // Import the Scanner class
class Main {public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String unit;
// unit selector
while (true) {
System.out.println("Did you measure ion feet or meters? Type 'meters' or 'feet': ");
String isUnit = myObj.nextLine();
if (isUnit.equals("feet") || (isUnit.equals("meters"))) {
unit = isUnit;
break;
} else {
System.out.println("Please enter either 'meters' or 'feet'.");
}
}
System.out.println("Use selected " + unit);
}
I am really new to learning Java and I am trying to change the user input to lowercase (or uppercase). However it isn't work. Any suggestion?
protected String nextMove()
{
System.out.println("Please enter move");
Scanner in = new Scanner(System.in).toUpperCase();
while (!in.hasNext("['a','b','c']"))
{
String move;
System.out.println("That is not a valid guess");
move = in.nextLine();
in.close();
return move;
}
return nextMove();
}
The Scanner is for getting input, not for translating or transforming it, and your code shouldn't even compile since you're calling a Scanner method that doesn't exist. You instead want to transform the String obtained.
You could simply do:
String myLowerCaseInput = in.nextLine().toLowerCase();
Edit: as a side note, I highly doubt that you will want to create the Scanner object in this method, since you should only create one Scanner object based on System.in. If need be, pass that Scanner into this method using a parameter.
protected String nextMove(Scanner in) {
System.out.print("Please enter move: ");
return in.nextLine().toLowerCase();
}
or better...
private static String nextMove(Scanner in) {
String input = "";
do {
System.out.print("Please enter move: ");
input = in.nextLine().trim().toLowerCase();
} while (input.isEmpty() || input.length() != 1 || !"abc".contains(input));
return input;
}
Try to use this:
Scanner in = new Scanner(System.in);
while (!in.hasNext("['a','b','c']")){
String upercase = in.nextLine().toUpperCase();
...
I need help with looping my code in Java. So far I have:
import java.util.Scanner;
public class chara{
public static void main(String[]args){
int count = 0;
Scanner input = new Scanner(System.in);
System.out.println("Input a string");
String user=input.nextLine();
if(user.length()<7)
{
return;
}
else
{
}
System.out.println("Now input a letter to be replaced");
String letter = input.next();
if(letter.length()!=1)
{
return;
}
else
{
}
String user2 = user.replace(letter, "-");
String user3 = user.replace(letter, "");
count += (user.length() - user3.length());
System.out.println(user2);
System.out.println(user3);
System.out.println("#"+letter+"'s: "+count);
}
}
The code does everything I want it to except that when the string condition is not met (user<7, letter!=1) the program terminates and what I need it to do is ask the question again. Does anyone know how I can achieve this?
You need to put your looping code in method that can be called, then when the conidtion is not met you can go back to your question, and depending on that condidtion, quit the program, or call the loop method.
You just need a loop with a break condition, this should do it for you:
Scanner input = new Scanner(System.in);
System.out.println("Input a string");
String user=input.nextLine();
while (true)
{
if(user.length() <7 ) {break;}
input = new Scanner(System.in);
System.out.println("Too long, input a string < 7");
user=input.nextLine();
}
if(user.length()<7)......
A simple way would be to wrap your main logic within a loop with a boolean condition. This condition stays true when there is an "error" in the input. The condition is then false when the user proceeds as wanted.
Your code would look as so :
import java.util.Scanner;
public class Tester{
public static void main(String[]args){
int count = 0;
boolean keepGoing = true;
Scanner input = new Scanner(System.in);
while(keepGoing) {
System.out.println("Input a string");
String user=input.nextLine();
if(user.length()<7)
{
keepGoing = true;
//enter an error message here
}
else
{
System.out.println("Now input a letter to be replaced");
String letter = input.next();
if(letter.length()!=1)
{
keepGoing = true;
//enter an error message here
}
else
{
String user2 = user.replace(letter, "-");
String user3 = user.replace(letter, "");
count += (user.length() - user3.length());
System.out.println(user2);
System.out.println(user3);
System.out.println("#"+letter+"'s: "+count);
keepGoing = false;
}
}
}
input.close(); //Close resources
}
}
Unrelated
The convention is that class names start with a capital letter. In your case your class should be Chara, not chara.
Also, when opening resources make sure you close them. This is to avoid having resources leaked. Some IDEs will tell you something like this Resource leak: 'input' is never closed. It's a good idea to use a good IDE to help you with potential problems like this one.
Can anyone help me understand why program requires me to input my selection twice before proceeding?
public static void main(String[] args) {
String quit = "quit";
String input = "input";
String print = "print";
#SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
System.out.println("please enter a command : \n 1) Quit \n 2) Input \n 3) Print \n");
String initialSelection = scan.next();
boolean stringInput = scan.hasNext();
boolean intInput = scan.hasNextInt();
boolean boolinput = scan.hasNextBoolean();
if(initialSelection.equalsIgnoreCase(quit)) {
System.out.println("The program has quit.");
System.exit(0);
}else if(initialSelection.equalsIgnoreCase(print)){
[constructor]
do {
System.out.println("\nplease enter a command : \n 1) Quit \n 2) Input \n 3) Print \n");
initialSelection = scan.nextLine();
if (initialSelection.equalsIgnoreCase(print)) {
new BonusArrayList();
} else if(initialSelection.equalsIgnoreCase(quit)) {
System.out.println("The program has quit.");
System.exit(0);
}
} while (initialSelection.equalsIgnoreCase(print));
}else if(initialSelection.equalsIgnoreCase(input)){
System.out.println("\n Please enter some kind of value (ex: 123, hello, True)");
}
}
I believe it is coming from the nested do-while statement, but I cannot seem to fix that issue. Any tips would be appreciated!
It is because you either need to have
String initialSelection = scan.next();
or
boolean stringInput = scan.hasNext();
boolean intInput = scan.hasNextInt();
boolean boolinput = scan.hasNextBoolean();
If you have both you need to enter twice