Endless loop while validating user input - java

I'm trying to validate german postcodes in a input form.
But somehow i get stuck in line 15 and my function is just printing "Give me input" in an endless loop.
I expected that sc_plz.nextLine() would be a blocking function but somehow it's not.
import View.AddressView;
import java.io.IOException;
import java.util.Scanner;
public class AddressController {
AddressView view = new AddressView();
public Address addAddress()throws IOException{
//other input questions
Scanner sc_plz = new Scanner(System.in);
int code = 0;
while (!validatePostcode(code))
view.askPostcode(); //simple System.out.println("Input something")
String postcode = sc_plz.nextLine();
try {
code = Integer.parseInt(postcode);
}
catch (NumberFormatException e){
view.invalidData(); //warning about not got a number
}
//other input questions
}
private boolean validatePostcode(int plz) throws IOException {
//legal postcodenumbers are between 01000 -99999
if (1000 <= plz && plz <= 99999){
return true;
}
else {
return false;
}
}
}

Did you forget brackets for your while statement? As it is right now it will always do whatever is in view.askPostcode();. I imagine this is what it should look like:
while (!validatePostcode(code)) {
view.askPostcode(); //simple System.out.println("Input something")
String postcode = sc_plz.nextLine();
try {
code = Integer.parseInt(postcode);
} catch (NumberFormatException e){
view.invalidData(); //warning about not got a number
}
}

Related

Validate Input - String

I am trying to validate input from a textfield so that it only contains characters from a-z. I am using the following method to validate if the input is an int:
//VALIDATE IF INPUT IS NUMERIC.
public static boolean isInt(JFXTextField txtUserInput, String userInput) {
try {
int intValidation = Integer.parseInt(userInput);
txtUserInput.setStyle("-fx-border-color: ; -fx-border-width: 0px ;");
return true;
} catch(NumberFormatException exception) {
showErrorMsg("Invalid Input:", "Please enter a numeric-only value");
txtUserInput.setStyle("-fx-border-color: RED; -fx-border-width: 1px ;");
return false;
}
}
How can I achieve this using a String? I know there is a different way of doing this using an if statement but I was wondering if I can catch an exception like in the example above.
Thanks
Use regex:
if (!userInput.matches("[a-z]+"))
// Has characters other than a-z
If you want to allow uppercase too:
if (!userInput.matches("[a-zA-Z]+"))
// Has characters other than a-z or A-Z
You can use matches with regex so if you want to check your input is an int or not you can use:
String userInput = ...;
if(userInput.matches("\\d+")){
System.out.println("correct");
}else{
System.out.println("Not correct");
}
If you want to check if the input contain only alphabetic, you can use :
if(userInput.matches("[a-zA-Z]+")){
System.out.println("correct");
}else{
System.out.println("Not correct");
}
If you want to check if your input contains alphanumeric you can use :
if(userInput.matches("[a-zA-Z0-9]+")){
System.out.println("correct");
}else{
System.out.println("Not correct");
}
You could use something like:
if (!userInput.matches(".*[^a-z].*")) {
// Do something
}
Alternative solution to #Bohemian♦ to allow uppercase:
if (!userInput.toLowerCase().matches(".*[^a-z].*")) {
// Do something
}
A similar method, according to your source:
public static boolean containsAZ(JFXTextField txtUserInput) {
if (!txtUserInput.getText().toLowerCase().matches(".*[^a-z].*"))
return true;
else
System.err.println("Input is not containing chars between A-Z");
return false;
}
There your question is, if it's possible to throw/catch an exception, you could do the following:
public static boolean containsAZ(JFXTextField txtUserInput) {
try {
if (!txtUserInput.toLowerCase().matches(".*[^a-z].*")) {
return true;
} else
throw new MyException("Something happened");
} catch (MyException e) {
e.printStackTrace();
}
return false;
}
Considering that you'll need a class:
class MyException extends Exception {
public MyException(String e) {
System.out.println(e);
}
}
An abstract solution would be:
public class MyException extends Exception {
// special exception code goes here
}
Throw it as:
throw new MyException ("Something happened")
Catch as:
catch (MyException e)
{
// Do something
}
For more info, check this for regex.

Java Input Validation

So I am working with a program that is supposed to incorporate try-catch blocks for exception handling. What I can't figure out is how to write a simple if statement for checking input from the user via Scanner to make sure it is a double and not a letter or a character so that if it is the program will catch it, display the error message, and tell the user to re-enter another value until a suitable input is entered. What I am looking for is a simple if(_width equals a letter/character) then return false along with an error message to go along with my already present if statement that checks whether the input is greater than zero.
my current code is below:
public class Rectangle {
//two double data fields width and height, default values are 1 for both.
private double width = 1;
private double height = 1;
private String errorMessage = "";
//no-arg constructor creates default rectangle
public Rectangle() {
}
//fpzc, called by another program with a statement like Rectangle rec = new Rectangle(#, #);
public Rectangle (double _width, double _height) throws Exception {
setWidth(_width);
setHeight(_height);
}
//get functions
public double getArea(){
return (width * height);
}
public double getPerimeter() {
return (2*(width + height));
}
public String getErrorMessage() {
return errorMessage;
}
//set functions
public void setWidth(double _width) throws Exception {
if( !isValidWidth(_width)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
width = _width;
}
public void setHeight(double _height) throws Exception {
if ( !isValidHeight(_height)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
height = _height;
}
//isValid methods
public boolean isValidWidth(double _width) {
if(_width > 0){
return true;
}
else {
errorMessage = "Invalid value for width, must be greater than zero";
return false;
}
if ()
}
public boolean isValidHeight(double _height) {
if(_height > 0){
return true;
}
else {
errorMessage = "Invalid value for height, must be greater than zero";
return false;
}
}
}
My class is being called by another test program that i have written correctly. Any help is appreciated! Thank you.
maybe something like:
String errorMessage = "error";
Scanner in = new Scanner(System.in);
String str = in.nextLine();
try {
Double.parseDouble(str);
}
catch( Exception e ){
System.out.println(errorMessage);
}
or iterate through the input and check if each character is digit:
String errorMessage = "error";
Scanner in = new Scanner(System.in);
String str = in.nextLine();
for(int i=0;i<str.length();i++){
char token = str.charAt(i);
if(!Character.isDigit(token) && token!='.' ) {
System.out.println(token + " doesnt work");
break;
}
}
On declaring your scanner you could also:
double num;
String errorMessage = "error";
while(true) {
Scanner in = new Scanner(System.in);
if (in.hasNextDouble()) {
num = in.nextDouble();
System.out.println(num);
break;
}
else System.out.println(errorMessage);
}
Maybe this code helps you:
double Input=0;
while(!(Input > 0)){{
System.out.println("Enter Valid Number");
Input = new Scanner(System.in).nextDouble();
}

Checking for words in a loop

So I have this project for my computer class and I can't seem to get my program to run no matter how many different ways I try it. What I'm trying to do is have the program check if what the user types equals any of the three words (Cookies, Milk, Both) and if it doesn't ask the question again and use that input but since I'm new to java I can't seem to get it to work
Here's my code:
import javax.swing.*;
import java.util.*;
public class Cookie {
public static void main(String[] args) {
try {
Info info = new Info();
} catch(Exception e) {
System.err.println("Error! " + e.getMessage());
}
}
static class Info {
String inputs = JOptionPane.showInputDialog(null,
"What do you want, Cookies, Milk or Both?");
String word1 = "Cookies";
String word2 = "milk";
String word3 = "Both";
String flagger = "";
while (true)
if(inputs.length() !=0) {
}
for(int i=0; i<inputs.length(); i++)
{
for(int j=0; j<word1.length(); j++)
{
if(inputs.charAt(i)==word1.charAt(j))
{
flagger=flagger+word1.charAt(i)+"";
}
}
for(int j=0; j<word2.length(); j++)
{
if(inputs.charAt(i)==word2.charAt(j))
{
flagger=flagger+word2.charAt(i)+"";
}
}
for(int j=0; j<word3.length(); j++)
{
if(inputs.charAt(i)==word3.charAt(j))
{
flagger=flagger+word3.charAt(i)+"";
}
}
if(!(inputs.equalsIgnoreCase(flagger))) {
String message = String.format("%s", "Huh, I didn't get that, please say it again");
JOptionPane.showMessageDialog(null, message);
String inputs = JOptionPane.showInputDialog(null,
"What do you want, Cookies, Milk or Both?");
}
if(inputs.equalsIgnoreCase("cookies")) {
String message = String.format("%s", "Here have some Cookies :)");
JOptionPane.showMessageDialog(null, message);
}
if(inputs.equalsIgnoreCase("MILK")) {
String message = String.format("%s", "Here is the Milk you wanted :)");
JOptionPane.showMessageDialog(null, message);
}
if(inputs.equalsIgnoreCase("BOTH")) {
String message = String.format("%s", "Here is your Cookies and Milk :)");
JOptionPane.showMessageDialog(null, message);
}
}
}
}
}
}
I was able to compile your code after making few fixes. I have used a different approach, this is working, at least for most of the scenarios.
Here's my Cookie.java
public class Cookie {
public static void main(String[] args) {
try {
Info info = new Info();
info.checkInput();
} catch(Exception e) {
System.err.println("Error! " + e.getMessage());
}
}
}
And Info.java
import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;
public class Info {
public void checkInput() {
String inputs = JOptionPane.showInputDialog(null,
"What do you want, Cookies, Milk or Both?");
Map<String, String> words = new HashMap<String, String>();
words.put("cookies", "Here have some Cookies :)");
words.put("milk", "Here is the Milk you wanted :)");
words.put("both", "Here is your Cookies and Milk :)");
while (true) {
if (inputs != null && inputs.length() > 0) {
if (words.containsKey(inputs.toLowerCase())) {
JOptionPane.showMessageDialog(null,
words.get(inputs.toLowerCase()));
inputs = repeat();
} else {
JOptionPane.showMessageDialog(null,
"Huh, I didn't get that, please say it again");
inputs = repeat();
}
} else {
inputs = repeat(); }
}
}
private String repeat() {
return JOptionPane.showInputDialog(null,
"What do you want, Cookies, Milk or Both?");
}
}
You code didn't work because:
you try to use static class Info, like a method - you declare inner static method with some class fields, and then just add code like in method, this is why it will not even compile. You can change it on static or nonstatic method, or add some methods to it. For example change static class Info on static void Info(){, and call it by just Info() (insted of Info info = new Info(); in main method.
you multiple times declare String inputs = JOptionPane.showInputDialog(null,"What do you want, Cookies, Milk or Both?");, it is enough to use just inputs = JOptionPane.showInputDialog(null,"What do you want, Cookies, Milk or Both?"); second time.
you mixed some brackets, like in:
while (true)
if(inputs.length() !=0) {
} // this is problematic bracket
so it will not work at all, and all nested if statments with it.
You need to fix it to at least run your application.
EDIT
It seems that you have a lot of unnecessary code, you can shorten it for example to:
import javax.swing.*;
public class Cookie {
public static void main(String[] args) {
while (true){
String inputs = JOptionPane.showInputDialog(null,
"What do you want, Cookies, Milk or Both?");
if(inputs.equalsIgnoreCase("cookies")) {
JOptionPane.showMessageDialog(null, "Here have some Cookies :)");
break;
}else if(inputs.equalsIgnoreCase("MILK")) {
JOptionPane.showMessageDialog(null, "Here is the Milk you wanted :)");
break;
}else if(inputs.equalsIgnoreCase("BOTH")) {
JOptionPane.showMessageDialog(null, "Here is your Cookies and Milk :)");
break;
}else{
JOptionPane.showMessageDialog(null, "Huh, I didn't get that, please say it again");
}
}
}
}
It seems like you want to get input from the user, and compare it to some preset strings (cookies, milk, and both)
What if you put the whole thing into a while(true) loop, and after getting the input from the user, you wrote something like
String message;
Boolean isValid = true;
if (inputs.equalsIgnoreCase("Cookies")){
message = "Have some cookies";
}
...
else{
message = "Try again";
isValid = false;
}
JOptionPane.showMessageDialog(null, message);
if(isValid) break;
Note: I'm writing this on a mobile, so syntax may not be exact. Use your discretion.

I get an error message as follows: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0

I get an error message as follows: Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at emp.MainClass.main(MainClass.java:52)
Using the following code, how do I alleviate this problem?
public class MainClass {
//main class
public static void main(String[] args){
// variable
String input;
boolean salaryError = true;
boolean dependentError = true;
boolean nameError = true;
boolean charError = true;
Employee emp1 = new Employee();
displayDivider("EMPLOYEE INFORMATION");
do{
input = getInput(" First Name");
nameError = nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setfirstName(input);
do{
input = getInput(" Last Name");
nameError =nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setlastName(input);
do{
input = getInput(" Gender: M or F");
charError = characterChecker(input.charAt(0));
if(!charError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!charError);
char g = input.charAt(0);
emp1.setgender(g);// validates use of M or F for gender
do{
input = getInput(" number of dependents");
dependentError = integerChecker(input);
if(!dependentError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!dependentError);
emp1.setdependents(Integer.parseInt(input));
do{
input = getInput(" annual salary");
salaryError = doubleChecker(input);
if(!salaryError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
} while(!salaryError);
emp1.setannualSalary(Double.parseDouble(input));
emp1.displayEmployee();//displays data for emp1
Employee emp2 = new Employee("Speed","Racer",'M',1,500000.00);
displayDivider("EMPLOYEE INFORMATION");
emp2.displayEmployee();// displays data for emp2
terminateApplication(); //terminates application
System.exit(0);//exits program
}//end of main
// gets Input information
public static String getInput(String data)
{
String input = "";
input = javax.swing.JOptionPane.showInputDialog(null,"Enter your " + data);
return input;
}// end getInput information
// The display divider between employees
public static void displayDivider(String outputLab)
{
System.out.println("********" + outputLab + "********");
}// end display divider
// Terminates the application
public static void terminateApplication()
{ javax.swing.JOptionPane.showMessageDialog(null,"Thanks for the input!");
}// end terminateApplication
public static boolean doubleChecker(String inStr){
boolean outBool = true;
double tmpDbl = 0.0;
try{
tmpDbl = Double.parseDouble(inStr);
if(tmpDbl <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean integerChecker(String intStr){
boolean outBool = true;
int tmpInt = 0;
try{
tmpInt = Integer.parseInt(intStr);
if(tmpInt <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean nameValidate(String str){
for(char ch : str.toCharArray()){
if(!Character.isDigit(ch)){
return true;
}
}
return false;
}
public static boolean characterChecker(char gen){
boolean outBool = true;
try{
if(!( gen ==( 'M') || gen ==('F')))
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
}//end of Main Class
Your string is length 0. Make sure string.length() > 0 before accessing its elements. The problem is at the line the exception says the problem is on.
Better answer: are you using an IDE? If so, observe the line the exception tells you you have an error on. Set a breakpoint before that line, debug, and note the contents of the object on which the error happened (in this case the string). Then check the javadoc for the method that threw the exception to see if there is any problem calling that method on that string.
If you are not using an IDE, you will either need to use one or find a standalone debugger. Having a good debugger is a requirement of Java development.
This should save you a lot of SO questions going forward.
StringIndexOutofBoundsException means you're try to access the String using an index and the index is either negative or greater than the size of the string.
You're wrong in this part:
charError = characterChecker(input.charAt(0));
Because you're not check if the input length is 0.
Try to change that line to this:
charError = input != null && input.length() > 0 && characterChecker(input.charAt(0));

Return to ... in Java (like goto)

I just started to learn Java, so have a lot of questions. And now I need to return to the beginning of program if a problem occurs.
public static int getchartoint() throws IOException {
int a;
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
String k = bReader.readLine();
a = Integer.parseInt(k);
return a;
}
catch (NumberFormatException exc) {
System.out.println(exc);
return a = 0;
}
finally {
}
}
and I have a = 0, I could write case in main() body:
case 0: {
System.out.println("Your entered an incorrect number...");
}
My question is: how can I add a line that moves me to exactly that line of code?
Call the "getchartoint" method before your switch/case statements.
Then when it returns integer 0 it will execute the case statement.
It looks like you just want to return 0; instead of return a=0;.

Categories