如果......不是int {

Pyt*_*sPi 1 java int

我试图让程序识别是否未输入int.

我见过以下所有内容:

   if  (v % 1) 
Run Code Online (Sandbox Code Playgroud)

    parseInt();
Run Code Online (Sandbox Code Playgroud)

但他们不适合我.

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();
        }
Run Code Online (Sandbox Code Playgroud)

pse*_*ble 6

检查值是否是这样的原语是行不通的.Java将无法以这种方式将值与类型进行比较.

一种方法是利用静态函数Integer.parseInt(String s)来查看是否输入了适当的int值.请注意,它会抛出一个NumberFormatException.如果您可以利用这一事实,则可以获取函数是否提供了整数.

try {
   //Attempt the parse here
} catch (...) {
   //Not a proper integer
}
Run Code Online (Sandbox Code Playgroud)

第二种技术(因为你已经在利用这个Scanner类)是使用这些Scanner 方法 hasNextInt()nextInt()确定是否:

  1. Scanner具有流中的一个新的整数
  2. 从流中获取实际的整数值

一个示例用法是:

if (myScanner.hasNextInt()) {
   int totalAmount = myScanner.nextInt();
   // do stuff here
} else {
   //Int not provided
}
Run Code Online (Sandbox Code Playgroud)

正如你在更新中提到,这是一切优秀和良好时从输入Scanner分隔的空间.默认情况下,Scanner按空格分隔流中的值.当你有一个不同的分隔符(例如:","或"//"等)在逻辑上在流上分隔两个唯一值时会发生什么?

解决方案是修改Scanner正在使用的分隔符.有一种方法useDelimiter(String pattern)可以让您指定如何在流中逻辑分隔值.它对于您正在处理的内容(或任何空格不分隔值的情况)非常有用.

用法看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

ScannerAPI中有一个很好的例子(参见Scanner我在该示例中包含的第一个链接),它描述了如何使用它.我建议检查出来,它会非常好地为你(我相信).