如果...不是 int {

发布于 2024-12-11 14:05:21 字数 980 浏览 0 评论 0原文

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

我已经看到了从:

   if  (v % 1) 

到 的

    parseInt();

所有内容,但它们对我不起作用。

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();
        }

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();
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

梦断已成空 2024-12-18 14:05:21

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

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

try {
   //Attempt the parse here
} catch (...) {
   //Not a proper integer
}

第二种技术(因为您已经在利用 Scanner 类)是使用 Scanner 方法 hasNextInt()nextInt() 来确定 :

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

示例用法是:

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

正如您在更新中提到的,当从 输入时,这一切都很好。扫描仪由空格分隔。默认情况下,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

Scanner API 中有一个很好的示例(请参阅我在该示例中包含的 Scanner 上的第一个链接),它描述了如何执行此操作被使用。我建议检查一下,它会对你来说非常好(我相信)。

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:

  1. The Scanner has a new integer in the stream
  2. Get the actual integer value off of 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).

巴黎盛开的樱花 2024-12-18 14:05:21

还有另一个解决方案,以便您可以选择:在 中JLS §3.10.1 您可以读取整数可以是什么。将定义放入正则表达式形式中,您会得到:

// input s
if (s.matches("(?i)[+-]?(0|[1-9][0-9]*|0[x][0-9a-f]+|0[0-7]+)L?")) { /* do something */}

缺点是,您在代码中添加数字的详细定义 — Java 可以为您做到这一点。不过,好处是您的 2,3 情况很容易解决:(

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 */}

事情不会那么容易,因为您可能喜欢像 2, 3 这样的字符串code> 也有效,但我会把它留给你。)

回到常用的解决方案和你对 2,3 的评论,你必须养成分离问题的习惯:你已经知道几个检查字符串是否包含整数的方法。您现在可以做的就是不去理会这个问题并解决您的逗号问题:

    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());
    }

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());
    }
蛮可爱 2024-12-18 14:05:21

您可以使用 Integer.parseInt(yourInt) ,但是如果您没有收到整数,则必须捕获引发的错误,如下所示:

try {
  Integer.parseInt(yourInt);
}
catch (NumberFormatException e) {
  // do something that indicates to the user that an int was not given.
}

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.
}
挽清梦 2024-12-18 14:05:21
if (coordinate1 != int)

不起作用,因为您正在将值与类型进行比较。这段代码甚至不应该编译。

使用:

try {
    int integer = Integer.parseInt(value);
} catch (NumbumberFormatException e) {
    // Not an integer
}
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
}
晚风撩人 2024-12-18 14:05:21

使用此模型:

Integer result = null;
try {
    result = Integer.valueOf(input);
} catch (NumberFormatException e) {}
if (result != null) {
    // An integer was entered
}

Integer.valueOf 将为带有十进制的数字引发异常,因此您应该不会遇到任何问题。我使用 Integer 类与 int 类,以便可以将其设置为 null。使用-1意味着不能输入-1。

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.

月亮邮递员 2024-12-18 14:05:21

您可以尝试使用的一种方法是新方法。这是我用来获取整数输入的一个:

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.
    }

如果输入是整数,它将返回一个 int;否则,它会重试。注意:添加一个计数器,这样如果有人将午餐袋放在您的输入键上,代码就不会被破坏。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文