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 aNumberFormatException. If you can take advantage of this fact, you can obtain whether or not an integer was provided from a function.A second technique (since you’re already taking advantage of the
Scannerclass) is to use theScannermethodshasNextInt()andnextInt()to determine if:Scannerhas a new integer in the streamAn example usage would be:
As you mentioned in your update, this is all fine and good when input from the
Scanneris 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
Scanneris using. There is a method calleduseDelimiter(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:
There is a good example of this within the
ScannerAPI (see the first link onScannerI 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).