I am trying to get the program to recognize if an int is not entered .
I have seen everything from:
if (v % 1)
to
parseInt();
but they aren't working for me .
import java.util.Scanner;
public class LinearSlopeFinder {
public static void main(String[]args){
double x1, y1, x2, y2, n1, equation, constant = 0 ;
double slope, slope1, slopeAns;
Scanner myScanner = new Scanner(System.in);
System.out.print(" What is the first set of cordinants? example: x,y ... ");
String coordinate1 = myScanner.nextLine();
//below is what i am referring to
if (coordinate1 != int ){ // if it is a double or String
System.out.println("Sorry, you must use whole numbers.What is the first set of cordinants? example: x,y ... ");
System.out.print(" What is the first set of cordinants? example: x,y ... ");
String coordinate1 = myScanner.nextLine();
}
Checking that a value is a primitive like that won't work. Java will not be able to compare a value to a type in such a way.
One method is to take advantage of the static function Integer.parseInt(String s)
to see if an appropriate int value has been entered. Notice that it throws a NumberFormatException
. If you can take advantage of this fact, you can obtain whether or not an integer was provided from a function.
try {
//Attempt the parse here
} catch (...) {
//Not a proper integer
}
A second technique (since you're already taking advantage of the Scanner
class) is to use the Scanner
methods hasNextInt()
and nextInt()
to determine if:
Scanner
has a new integer in the stream An example usage would be:
if (myScanner.hasNextInt()) {
int totalAmount = myScanner.nextInt();
// do stuff here
} else {
//Int not provided
}
As you mentioned in your update, this is all fine and good when input from the Scanner
is delimited by spaces. By default, Scanner delimits values within the stream by spaces. What happens when you've got a different delimiter (ex: "," or "//" etc) that separates two unique values logically on the stream?
The solution to that is to modify the delimiter that the Scanner
is using. There is a method called useDelimiter(String pattern)
which allows you to specify how values will be separated logically within the stream. It's very useful for cases like what you're dealing within (or any cases where spaces do not delimit the values).
The usage will look something like this:
Scanner myScanner = ...; # Get this how you normally would
String delimiter = ...; # Decide what the separator will be
myScanner.useDelimiter(delimiter); # Tell the Scanner to use this separator
There is a good example of this within the Scanner
API (see the first link on Scanner
I included for that example) that describes how this is used. I suggest checking that out, and it'll come together very nicely for you (I believe).
Yet another solution, so that you had choice: in JLS §3.10.1 you can read what integer can be. Putting the definition in a regexp form, you have:
// input s
if (s.matches("(?i)[+-]?(0|[1-9][0-9]*|0[x][0-9a-f]+|0[0-7]+)L?")) { /* do something */}
The downside would be, you add a verbose definition of a number in your code—Java could do that for you. The bonus, though, is that your case with 2,3
is easily addressed:
String intLiteral = "[+-]?(0|[1-9][0-9]*|0[x][0-9a-f]+|0[0-7]+)L?";
// input s
if (s.matches("(?i)" + intLiteral + "," + intLiteral)) { /* do something */}
(things are not going to be that easy, because you'd probably like strings like 2, 3
valid, too—but I'll leave it with you.)
Returning to the commonly used solution and your comment about 2,3
, you must get into habit of separating problems: you already know several ways to check whether a string contains integer or not. What you can do now is to leave this problem alone and address your commas:
String s = "2,3";
String[] parts = s.split(","); // here we deal with commas
try {
// now when we have parts, deal with parts separately
System.out.println("First: " + Integer.parseInt(parts[0]));
System.out.println("Second: " + Integer.parseInt(parts[1]));
} catch (NumberFormatException e) {
System.out.println("There was a problem, you know: " + e.getMessage());
}
You can use Integer.parseInt(yourInt)
, but then you have to catch the error that is thrown if you do not receive an integer, like this:
try {
Integer.parseInt(yourInt);
}
catch (NumberFormatException e) {
// do something that indicates to the user that an int was not given.
}
One method you could try using is a new method. Here's one I use for getting integer inputs:
public static int getIntInput(Scanner s) { // Just put your scanner into here so that the method can read inputs without creating a new scanner each time
System.out.print("Enter int here: ");
try {
return Integer.parseInt(s.nextLine());
} catch (NumberFormatException e) {
System.out.println("You must enter a valid Integer literal.");
return getIntInput(s); // Note that this line just repeats the try statement all over again.
}
If the input is an integer, it will return an int; otherwise, it tries again. Note: add a counter so that the code doesn't break if someone sets their lunch bag on your enter key.
if (coordinate1 != int)
won't work, because you're comparing a value to a type. This code shouldn't even compile.
Use:
try {
int integer = Integer.parseInt(value);
} catch (NumbumberFormatException e) {
// Not an integer
}
Use this model:
Integer result = null;
try {
result = Integer.valueOf(input);
} catch (NumberFormatException e) {}
if (result != null) {
// An integer was entered
}
Integer.valueOf will throw an exception for numbers with deciamls, so you shouldn't have any problems. I'm using the Integer class vs int so that it can be set to null. Using -1 means that -1 cannot be entered.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.