当我要求用户输入时,我无法从数组中删除元素

时间:2018-12-06 07:41:38

标签: java arrays class random numbers

当我要求用户输入要从数组中删除的数字时,它只输入0,然后要求再次尝试,我希望数字被完全删除,直到数组为空,这是我到目前为止的代码:

import java.util.Scanner;
import java.util.Random;
public class DeleteElements
{
    public static void main(String[]args)
    {
        Scanner keyboard = new Scanner(System.in);
        int arr[] = new int[20];
        int num, found = 0,
        arrSize = 10;
        String choice;

        Random randomGenerator = new Random();
        for (int i = 0; i<10; i++)
        {
            arr[i] = randomGenerator.nextInt(100);
        }  

        for(int i = 0; i<10; i++)
        {
            System.out.print("" + arr[i] + " "); 
        }

        do 
        {
            System.out.print("Number to Delete: ");
            num = Integer.parseInt(keyboard.nextLine());

            if(arrSize <=0)
            {
                System.out.println("The array is now empty");
                break;
            }
            else
            {
                for (int i = 0; i<10; i++)
                {
                    if(arr[i] == num)  
                    {
                        found = 1;  
                    }

                    if (found == 1)
                        arr[i] = arr[i + 1];
                }
                if (found == 0)
                    System.out.println("Number not found,");

                else
                {
                    arrSize--;
                    int i = 0;
                    for ( i = 0; i <arrSize; i++);
                    {
                        System.out.print("" + arr[i] + " ");
                    }
                   found = 0;
               }
               System.out.println(" Try again (y/n) ? ");
               choice = keyboard.nextLine();
           }
       }while (choice.charAt(0) == 'y' || choice.charAt(0) == 'Y');
    }
}

我希望它看起来像这样: 数组:3、63、45 删除NUmber:“用户输入45” 数组:3、63

1 个答案:

答案 0 :(得分:1)

问题在这里:

for ( i = 0; i <arrSize; i++);

for循环后有一个分号。删除它,您的代码将按预期工作。