Java 如何在数组中仅获取正整数?

Java 如何在数组中仅获取正整数?,java,arrays,Java,Arrays,我正在用用户给定的整数创建一个数组。但是,我只需要正整数。如何检查用户输入的整数是否为正 public static void main(String[] args) { Scanner input = new Scanner(System.in); Integer array [] = new Integer[10]; int userChoice; boolean loop = true; // to loop through the

我正在用用户给定的整数创建一个数组。但是,我只需要正整数。如何检查用户输入的整数是否为正

 public static void main(String[] args)
 {
     Scanner input = new Scanner(System.in);
     Integer array [] = new Integer[10];
     int userChoice;
     boolean loop = true;

     // to loop through the switch and show userChoice to user until chose to 
     // quit

     System.out.println("Please enter the 10 positive integers to be represented in the BST:");

     for (int i = 0 ; i < array.length; i++ ) 
         array[i] = input.nextInt(); 
}
publicstaticvoidmain(字符串[]args)
{
扫描仪输入=新扫描仪(System.in);
整数数组[]=新整数[10];
int用户选择;
布尔循环=真;
//循环切换并向用户显示userChoice,直到用户选择
//退出
System.out.println(“请输入要在BST中表示的10个正整数:”);
for(int i=0;i

我尝试在for
循环的
中执行
if(input.nextInt()>0)
,但当我按enter键时,程序只是冻结,什么也不做。还尝试将
for
循环放入
do while(input.nextInt()>0)
,但我仍然遇到同样的问题。

您可以直接执行以下操作:

for (int i = 0 ; i < array.length; i++ ) {
    int check = input.nextInt();
    if (check > 0)
        array[i] = check;
    else {
        System.out.println("Only positives, try again.");
        i--;
    }
}
for(int i=0;i0)
数组[i]=检查;
否则{
System.out.println(“只有肯定的,再试一次。”);
我--;
}
}

但是,您可以更具创造性,我建议您真的尝试一下。

您缺少一个基本概念,即此代码是如何实现的。应该工作和工作;B这段代码实际上是如何工作的。与其乞求别人来解决你的问题,不如花点时间试着去理解这些控制结构做了什么,你想做什么,为什么它不起作用。Psudocode您的解决方案,然后返回编写代码。如果我们只是解决你的问题,这对你没有帮助,因为你不明白为什么它会解决你的问题。听起来不错,但这里没有人乞讨。你说你尝试在for循环中插入if,但程序冻结了。这实际上是倾向于如何解决这个问题。您需要找出它冻结的原因和冻结的位置。您没有显示任何实际的代码,而是提到“我尝试了执行
if(input.nextInt()>0)
”。。。你认为那到底在干什么?你刚从输入中读取的数字在哪里?那之后你在干什么?也许这就是问题所在。。。