简体   繁体   English

整数等于isEmpty()吗?

[英]what is equivalent to isEmpty() for integers?

Below is the script I have at the moment 以下是我目前拥有的脚本

import java.util.Arrays;
import java.util.Scanner;

public class SeeWhatTo 
{   
     public static void main(String args[]) {
       Scanner scan = new Scanner(System.in); //define scan  
       int a = scan.nextInt();
       int sum =0;
           while (a>0 )
     {                   
            sum = sum +a;
            a = scan.nextInt();    
     }
        System.out.println(sum);   //print out the sum
    }    
}

Currently, it stores an input value in a and then adds it to sum and once a negative or zero is given as an input, it suspends itself and outputs the sum. 当前,它将输入值存储在a ,然后将其加到sum ,一旦输入负数或零作为输入,它将暂停自身并输出和。

I was wondering if there's an integer equivalent of isEmpty so that i can do while (! a.isEmpty() ) so when there's no input but an enter, then it would stop and prints out the sum. 我想知道是否有一个等于isEmpty的整数,这样我就可以while (! a.isEmpty() )来做while (! a.isEmpty() )所以当没有输入但只有Enter时,它将停止并打印出总和。

A natural followup from that would be, is there a way to assign an input integer to a and check if it is empty or not at the same time in the while condition as in while ( ! (a=scan.nextInt()).isEmpty() ) 随之而来的自然是,有一种方法可以将输入整数分配给a并在while条件中与while ( ! (a=scan.nextInt()).isEmpty() )检查它是否为空while ( ! (a=scan.nextInt()).isEmpty() )

There isn't an equivalent in the sense that you describe, since String is a variable-length collection of characters, and having zero characters is still a valid String. 从描述的意义上讲,这不是等效的,因为String是可变长度的字符集合,而具有零个字符仍然是有效的String。 One integer cannot contain zero integers, since by definition, it is already an integer. 一个整数不能包含零个整数,因为根据定义,它已经是一个整数。

However, your problem revolves around how Scanner works, rather than how int works. 但是,您的问题与Scanner的工作方式有关,而不是int的工作方式。

Take a look at scan.hasNextInt() , which returns true if there is an int to read, and false otherwise. 看一下scan.hasNextInt() ,如果有要读取的int,则返回true,否则返回false。 This may give you what you want, using something like: 这可能会给您所需的内容,例如:

Scanner scan = new Scanner(System.in);
int sum = 0;
while(scan.hasNextInt())
{
    int a = scan.nextInt();
    sum = sum + a;
}
System.out.println(sum);

Scanner can do 2 things: Scanner可以做两件事:

  • Read line-by-line ( nextLine ). 逐行读取( nextLine )。
  • Read token-by-token ( next or eg nextInt ). 逐个令牌读取令牌( next或eg nextInt )。

These are really two different functionalities of Scanner , and if you're reading tokens then your Scanner basically doesn't know about empty lines. 实际上,这是Scanner两种不同功能,如果您正在读取令牌,则您的Scanner基本上不了解空行。

If you call nextInt , Scanner does two things: 如果调用nextInt ,则Scanner执行以下两项操作:

  • Finds the next token (default: delimited by any whitespace). 查找下一个标记(默认值:由任何空格分隔)。
  • Tries to turn it in to an int . 尝试将其转换为int

The tokenizing behavior is an important feature of Scanner . 标记化行为是Scanner的重要功能。 If you enter 1 2\\n and call nextInt twice, you get 1 and 2 . 如果输入1 2\\n并调用nextInt两次,则得到12 However, if you enter an empty line, the tokenizing Scanner just skips it as whitespace and keeps looking for another token. 但是,如果您输入一个空行,则标记化Scanner只会将其跳过为空白,并继续寻找另一个标记。

So the straightforward answer is "no": you can never get an "empty" int from a call to nextInt in a simply way and still retain the token-by-token behavior. 因此,直接的答案是“否”:您永远无法通过简单的方式从对nextInt的调用中获得“空” int ,而仍然保留逐个令牌的行为。 (That's beyond the fact that a primitive variable in Java can't be "empty".) (这超出了Java中的原始变量不能为“空”的事实。)

One easy way to do what you're asking is to use line-by-line reading instead and call parseInt yourself: 一种简单的方法来执行您要的操作,而是使用逐行读取,然后自己调用parseInt

Scanner systemIn = new Scanner(System.in);
int sum = 0;

String line;
while (!(line = systemIn.nextLine()).isEmpty()) {
    sum += Integer.parseInt(line);
}

But you lose the tokenizing behavior. 但是您会失去标记化行为。 Now, if you enter 1 2\\n , an exception is thrown because nextLine finds 1 2 . 现在,如果输入1 2\\n ,则将引发异常,因为nextLine找到1 2

You can still read token-by-token with nextInt , but it's more complicated, using a second Scanner : 您仍然可以使用nextInt逐个令牌地读取令牌,但是使用第二个Scanner则更为复杂:

Scanner systemIn = new Scanner(System.in);
int sum = 0;

String nextLine;
while (!(nextLine = systemIn.nextLine()).isEmpty()) {
    Scanner theInts = new Scanner(nextLine);

    while (theInts.hasNextInt()) {
        sum += theInts.nextInt();
    }
}

Here, we can enter 1 2\\n , get 1 2 as our next line, then ask the second Scanner to tokenize it. 在这里,我们可以输入1 2\\n ,将1 2作为下一行,然后要求第二个Scanner将其标记化。

So yes, you can program the functionality you're looking for, but not in an easy way, because Scanner is more complicated. 是的,您可以对所需的功能进行编程,但并不容易,因为Scanner更加复杂。

edit 编辑

Possibly another way is to use a delimiter on the line separator: 可能的另一种方法是在行分隔符上使用定界符:

// use System.getProperty("line.separator") in 1.6
Scanner systemIn = new Scanner(System.in).useDelimiter(System.lineSeparator());
int sum = 0;

while (systemIn.hasNextInt()) {
    sum += systemIn.nextInt();
}

Now, nextInt tokenizes the same way as nextLine . 现在, nextInt令牌化方式与nextLine相同。 This will break the loop for any input that's not an int , including empty tokens. 这将中断所有非int输入(包括空标记)的循环。 (Empty tokens aren't possible with the default delimiter.) I'm never really sure if people actually expect Scanner 's default delimiting to work the way it does or not. (使用默认的定界符不可能获得空令牌。)我永远无法真正确定人们是否真的希望Scanner的默认定界以它的方式工作。 It's possible creating a Scanner in this way makes it behave closer to what people seem to expect for reading the console, just line-by-line. 可能以这种方式创建Scanner ,使其行为更接近人们似乎希望阅读控制台的内容,只是逐行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM