您的代码运行成功。您是否编写了执行该静态方法的代码?
这是您的代码稍作修改的版本。
我将 Scanner 移动到 try-with-resources 以自动关闭它。养成关闭您打开的此类资源的习惯。任何实现 AutoCloseable 的资源都可以在 try-with-resources 中使用。
为了清楚起见,我更改了一些名称。
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println( "running" ) ;
int[] inputs = Ideone.userInput() ;
System.out.println( Arrays.toString( inputs ) ) ;
}
public static int[] userInput() {
try(
Scanner scanner = new Scanner( System.in ) ;
) {
int[] inputs = new int[5];
int currentSize = 0;
while ( scanner.hasNextInt())
{
if (currentSize > inputs.length)
{
inputs = Arrays.copyOf(inputs, 2 * inputs.length);
}
inputs[currentSize] = scanner.nextInt();
currentSize++;
}
inputs = Arrays.copyOf(inputs, currentSize);
return inputs;
}
}
}
看到这个code run live at IdeOne.com。
对于这些输入:
7
42
Exit
…我们得到这个输出:
running
[7, 42]
ArrayList
如果使用List(例如ArrayList)而不是数组,您的代码会简单得多。 ArrayList 在内部处理大小调整,我们无需付出任何努力。
如果您正在学习操作数组,那就太好了。或者,如果您有大量数据,请使用数组,因为它们在使用更少内存的同时执行速度更快。但对于日常编程,请使用 Collections 框架,例如 List。
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println( "running" ) ;
List< Integer > inputs = Ideone.userInput() ;
System.out.println( inputs ) ;
}
public static List< Integer > userInput() {
try(
Scanner scanner = new Scanner( System.in ) ;
) {
List< Integer > inputs = new ArrayList<>() ;
while ( scanner.hasNextInt())
{
inputs.add( scanner.nextInt() ) ;
}
return List.copyOf( inputs ) ;
}
}
}
看到这个code run live at IdeOne.com。
要删除任何值 7,请致电 removeAll。
boolean oneOrMoreRemoved = inputs.removeAll( List.of( Integer.valueOf( 7 ) ) ) ;