【问题标题】:I am unable to delete elements from within my array when i ask for user input当我要求用户输入时,我无法从数组中删除元素
【发布时间】:2019-05-07 20:53:45
【问题描述】:

当我要求用户输入要从数组中删除的数字时,它只会输出 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 删除号码:“用户输入 45” 数组:3、63

【问题讨论】:

  • 非常感谢任何帮助!

标签: java arrays class random numbers


【解决方案1】:

问题在这里:

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

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

【讨论】:

  • 非常感谢,我注意到另一个问题,即当数组为空时,它不会显示任何建议?
  • arrSize 变为 0 并且它不会进入那个 for 循环。您应该添加一个条件检查 arrSize 变量。如果它变为 0,则打印一条消息,指出数组中没有剩余元素并中断循环。
猜你喜欢
  • 1970-01-01
  • 2021-06-14
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多