gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:52:34 25 4
gpt4 key购买 nike

当我要求用户输入一个要从数组中删除的数字时,它只是输出 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

最佳答案

问题在这里:

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

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

关于java - 当我要求用户输入时,我无法从数组中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53646670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com