Check if the user input fits - java

What i'd like to do is that to check if the user input fits and if so then use the user input, otherwise throw exception.
For fit there can only be one true input which is in form of: x,y;x,y;x,y;x,y where x >= 0 & y > 0. (x and y do not have to be same value in every comma separator, for example true input is 0,1;2,3;4,5;6,7) If user types anything else, for example "asd" or 0,1;2,3;4,5 (missing one x,y), he gets the exception. I think i can handle doing the exception throwing but the problem is i don't know how to check if the user input fits. I don't know if it's necessary to provide my code here because the checking part is not in my code yet and anything else is unimportant anyways.
Code was requested, don't know for what reasons but created some for quick example:
TextField tf1 = new TextField();
String inputText = tf1.getText();
if (inputText == form(x,y;x,y;x,y;x,y)) {
// do things;
}
else {
throw exception;
}

From your test case 0,1;2,3;4,5, it is defined that a number of yours ("x") would consist of either zero of a sequence of integers not trended by zero. This would be:
(?:0|[1-9]\d*+)
From there you can quantify a subpattern for repeating the rest of the section "x,y":
(?:0|[1-9]\d*+),[1-9]\d*+(?:;(?:0|[1-9]\d*+),[1-9]\d*+){3}
Here is a regex demo.

Use regexp
if (inputText.matches("[0-9]+,[1-9]+[0-9]*(?:;[0-9]+,[1-9]+[0-9]*){3}"))
{
// do things
}

Related

Recursive java method to parse a string with condition?

Fairly new to java and programming.
Wrote this recursive method, with the objective of asking for a valid string that is both an integer and greater than 0:
private int getDimension(String tableElement){
Integer Input= 0;
System.out.println("Define table rows "+tableElement+"'s."
+"Enter an integer >= 1:");
if( !Reader.hasNextInt() || (Input=Input.parseInt(Reader.nextLine())) <= 0)
return getDimension(tableElement);
return Input;
}
I'd like to stick to using a short and recursive method. It seems to handle the >= 0 logic fine, but blows up when i pass it something other than an integer.
Can someone explain why does that happen to me please?
hasNextInt() doesn't actually consume your input, so you're stuck with the same non-int input on your next call.
Simply spoken, your code doesn't make much (any?) sense.
First of all, there is not really a point in using a recursive method that asks the user for input; and that does not at all do anything about the argument passed to it!
private int getDimension(String tableElement){
Integer Input= 0;
Bad: you keep up mixing int and `Integer. They are not the same. And - read about java coding style guides. Variable names start lower case!
if( !Reader.hasNextInt() || (Input=Input.parseInt(Reader.nextLine())) <= 0)
The first condition gives:
true: when there is NO int ...
false: when there is an int
true leads to: calling your method again without retrieving a value from the reader.
false leads to parsing an int; and checking its value for <= 0.
In one case, you are doing a recursive call; completely ignoring the input you got from the reader; in the other case, you returning 0; or that value in input.
Solution: do something like:
while (true) {
if (reader.hasNextInt()) {
input = reader.nextInt();
break;
}
// there is no number!
read.nextLine(); // consume & throw away non-number!
print "Enter a number"
}
instead.
But seriously: start with throwing away this code.
Final side note: you do Input.parseInt() ... but that is a static method on the Integer class. Just call that as Integer.parseInt() instead! But as said; throw away your code; and learn how to properly use that Scanner class; start reading here.
Because the user can enter anything, you must always read in the line, then compare it:
String num = Reader.nextLine();
return num.matches("[1-9][0-9]*") ? Integer.parseInt(num) : getDimension(tableElement);
Here I've use regex to figure out if it's a positive number; the expression means "a 1-9 char followed by 0 or more of 0-9 chars"

while loop parsing Double.IsNaN improperly

Language: Java, IDE: eclipse mars
The program is supposed to prompt the user (using JOptionPane) for a positive value. I'm trying to catch the invalid entries. My while statement catches the negative numbers but not the strings. When a negative number is entered, the prompt is shown again, but when a string value is entered, the exception is caught and the program moves on (when it should re prompt the user).
Once a positive value has been entered, the program assigns it to a value in another class. (We're learning the MVC OOP design pattern).
Double.isNaN(Double.parseDouble(h)) ---> can anyone help me find what am I missing?
// prompt to get bandwidth from user
// check for validity
// if invalid, prompt again
try{
h = JOptionPane.showInputDialog("Enter bandwidth as a positive number");
// loop until parsed string is a valid double
while (Double.isNaN(Double.parseDouble(h)) || Double.parseDouble(h) <=0) {
h = JOptionPane.showInputDialog("Enter bandwidth as a positive number");
}
// h has been set to valid double, set it to bandwidth
model.setBandwidth(Double.parseDouble(h));
}catch(NumberFormatException|NullPointerException NFE){
System.err.println("Caught exception: " + NFE.getMessage());
}
This is because of how parseDouble() works.
Throws:
NumberFormatException - if the string does not contain a parsable double.
(See here)
So if the String is not a double parseDouble() will not return NaN but throw an exception, which means your catch clause will be called.
To solve this problem maybe use recursively algorithm which will call your method again if an exception is thrown.
As 4castle already stated, you need to move your try/catch block inside your while loop.
However, for validating user input you can basically stick to the following pattern:
public Foo getUserInput() {
Foo result;
do {
try {
String s = requestUserInput(); // something like Scanner.nextLine()
result = parseUserInput(s); // something like Double.parseDouble(String)
}
catch(Exception exc) {
// maybe you want to tell the user what's happened here, too
continue;
}
}
while(!isValid(result)); // something like (0 < result)
return result;
}

Searching only for a zero in Java with nothing preceding it or following it

I am working on a program that takes in 2 numbers and either adds, subtracts, multiplies, or divides them. The numbers can either be binary, hexadecimal, octal, or decimal numbers. In order for a user of the program to enter a binary number they must enter a "0b" in front of it. They would need to enter a "0" in front of the octal numbers, "0x" for hexadecimal, and just the number for a decimal number. The original number that is read in is a String then the method below converts it to an int or a double. I am trying to find out a solution if a user enters in a "0" for the number itself. Is there a way to see if the users input is only a 0 with nothing preceding it or following it? Here is my method I am working with. Any help would be awesome!
public double evaluate()
{
int sign = getSign();//makes number positive or negative
if (getOperand().startsWith("0"))// this is where i am trying to see if the number is just 0
{
return 0 * sign;
}
else if (getOperand().startsWith("0x"))
{
String op = getOperand().substring(2);
return Integer.parseInt(op, 16)*sign;
}
else if (getOperand().startsWith("0b"))
{
String op = getOperand().substring(2);
return Integer.parseInt(op, 2)*sign;
}
else if (getOperand().startsWith("0"))
{
String op = getOperand().substring(1);
return Integer.parseInt(op, 8)*sign;
}
else
{
String op = getOperand();
return (Double.parseDouble(op)) * sign;
}
You're making more work for yourself than you need. Just parse plain "0" as an octal number -- the result is still 0. No need to remove the leading zero.
That is,
// ...
else if (getOperand().startsWith("0"))
{
String op = getOperand();
return Integer.parseInt(op, 8)*sign;
}
// ...
Simply do this:
getOperand().equals("0")
If you want to check that the string is actually a zero with nothing before or after, you want equality.
getOperand().equals("0")
You can always check
if (getOperand().equals("0"))
However, you have another problem - your code will throw exceptions for invalid inputs. If the user enters just the prefix "0b" or "0x", your substring call would throw an exception. You must verify that there's at least one character following the prefix. It will also throw an exception if the substring can't be parsed as a number of the requested base.

How to accept strings or integers in the same user input

I want to accept user input as either an integer or a string in Java but I always get an error no matter what I do.
My code is very simple (I'm a beginner):
System.out.println(
"Enter the row number (or enter e to quit the application):"
);
Scanner rowInput = new Scanner(System.in);
int row1 = rowInput.nextInt();
I want the user also to be able to press "e" to exit.
I have tried several things:
1) To convert row1 to a String and and say:
if((String)(row1).equals("e"){
System.out.println("You have quit") }
2) To convert "e" to an integer and say:
if(row1 == Integer.ParseInt("e"){
System.out.println("You have quit") }
3) To do the switch statement but it said I had incompatible types (String and an int).
My errors usually say: Exception in thread "main" java.util.InputMismatchException
Is there somebody who could help me?
Many thanks in advance!
You can try something like this
Scanner rowInput = new Scanner(System.in);
String inputStr = rowInput.nextLine();
try{
int row1 = Integer.parseInt(inputStr);
} catch (NumberFormatException e) //If exception occurred it means user has entered 'e'
{
if ("e".equals(inputStr)){
System.out.println("quiting application");
}
}
you should read the input from your scanner as String type and the try to convert that String input into integer using Integer.parseInt().
If its successful in parsing, it means user has input an Integer.
And If it fails, it will throw an exception NumberFormatException which will tell you that its not an Integer. So you can go ahead and check it for e if it is, do whatever you want as per your requirement.
You can't use nextInt() if you aren't sure that you will have a number coming in. Also, you can't parse e as an integer, because it is not an integer, it's either char or string (I'll suggest string in this case).
That means, your code should look like:
System.out.println("Enter the row number (or enter e to quit the application):");
Scanner rowInput = new Scanner(System.in);
string row1 = rowInput.next();
Then you have the data in a string. You can simply check if the string is e:
if (row1.Equals("e")) ...
It is also a good idea to check if the input is actually an integer then. Good way to check it is described here:
How to check if a String is numeric in Java
1) you should say Integer.parseInt() instead of Integer.ParseInt()
2) if you pass "e" to Integer.parseInt() you'll get java.lang.NumberFormatException
3) get your input as a string this way (cause it's safer)*:
Scanner rowInput = new Scanner(System.in);
String row = rowInput.next();
if (row.equals("e")) {
//do whatever
}
else if(row.matches("\\d+$")) {
//do whatever
}
*In your approach if user enters a non-integer input you'll encounter java.util.InputMismatchException
I have tried several things ....
Attempting to solve this problem by "trying things" is the wrong approach.
The correct approach is to understand what is going on, and then modify your solution to take this into account.
The problem you have is that you have a line of input that could be either a number or the special value e which means quit. (And in fact, it could be a couple of other things too ... but I will come to that.)
When you attempt to either:
call Scanner.nextInt() when the next input is not an integer, OR
call Integer.parseInt(...) on a String that is not an integer
you will get an exception. So what do you do?
One way is to change what you are doing so that you don't make those calls in those situations. For example:
call Scanner.hasInt() to see if the next token is an integer before calling nextInt(), or
test for the "e" case before you attempt to convert the String to an integer.
Another way to deal with this is to catch the exception. For example, you could do something like this:
String s = ...
try {
number = Integer.parseInt(s);
} catch (NumberFormatException ex) {
if (s.equals("e")) {
...
}
}
Either way will work, but I'm going to leave you to work out the details.
But the real point I'm trying to make is that the right way to solve this is to understand what is happening in your original version / versions, and based on your understanding, modify what you were doing. If you just randomly "try" alternatives that you found with Google, you won't progress to the point of being a productive programmer.
I said there were other cases. They are:
The user types something that is neither a number of your special e character. It could be anything. An empty line, hi mum ...
The user types the "end of file" character; e.g. CTRL-D on Linux or CTRL-Z on windows.
If you want your program to be robust you need to deal with these cases too.
Try this:
public class Demo{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String choice = null;
System.out.println("Enter e to exit or some other key to stay:");
choice=s.next();
if(choice.equals("e"))
{
System.out.println("quits");
System.exit(0);
}
else
{
System.out.println("stays");
}
}
}
You can't convert a string into integer, use char ASCII codes instead.

Program compiles but does not run

This is an assignment i have to complete.
Can someone lead me in the right direction?
The program compiles but wont run correctly.
The error is InputMissmatch exception.
The error you are getting means that you are trying to use some kind of data as another one, in your case, you are probably trying to use a String as a float.
When using any of the next methods in the Scanner class you should first be sure that there's an appropiate input from the user.
In order to do so, you need to use the has methods.
Your problem is that you are not checking wether the input is a correct float or not before using your Scanner.nextFloat();
You should do something like this:
if (hope.hasNextFloat())
{
// Code to execute when you have a proper float,
// which you can retrieve with hope.nextFloat()
}
else
{
// Code to execute when the user input is not a float
// Here you should treat it properly, maybe asking for new input
}
That should be enough to point you in the right direction.
Also, check the Scanner api documentation for further details.
EDIT
Also, you are asking the user to input characters (or strings): "A", "B", etc..., but you are trying to compare them with a float. That's wrong, you should compare them with a string or character, like this:
if (hope.hasNextString())
{
if (hope.nextString().equals("A"))
{
// Code for option "A"
}
else if (hope.nextString().equals("B"))
{
// Code for option "B"
}
else ...
}
You could use a switch there, but it seems that you are not yet very fammiliar with java, so I'll leave it for another time.
Your problem is that you are entering a letter into a float field.
In your program you're asking the user to enter a float:
A = hope.nextFloat();
But if you enter the letter "A", you're going to get an exception because "A" is not a float, it's a string.
A simpler way to solve your problem is instead of having all the choices fields, you just read the input the user enters from the scanner like:
String choice = hope.next();
Next in the if statement, you check if the value from the string choice is equal to a specific letter, for example
if (choice.equals("A")) {
number4 = (number1 + number2 + number3);
System.out.printf("Your results are:" + (number4));
}
And you can do the same thing for the other choices you have.

Categories

Resources