gpt4 book ai didi

Java - 找到匹配时数组比较不会终止?

转载 作者:行者123 更新时间:2023-12-01 08:52:23 24 4
gpt4 key购买 nike

虽然关于提问的建议并没有禁止这样做,但如果我提出具体问题违反了任何规则,请告诉我。

我试图将用户输入与之前的用户输入(1-9)进行比较,然后检查是否有重复。但是,如果我的程序遇到重复,它不会停止。我做错了什么?

import java.util.Scanner;

public class No_Duplicates {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
boolean repeat = false;
do {
int[] array = new int[9];
for(int i = 1; i <= 9; i++)
{
System.out.println("Enter a number 1 - 9");
int num = scan.nextInt();
array[i] = num;
for(int j = 1; j <= i; j++)
{
if(num==array[j])
repeat = true;
}
}
}while(!(repeat == true));
System.out.println("No Duplicates Allowed!");
}
}

最佳答案

您的代码在遇到重复元素时不会停止。

我还注意到您正在从 1 而不是 0 访问数组索引。在Java中,数组索引从0开始。因此,您应该从 0 开始,并在数组长度之前停止。否则,您将遇到ArrayIndexOutOfBoundsException

您可以尝试以下方法:

    boolean repeat = false;

int[] array = new int[9];

for(int i=0 ; i<9 && repeat!=true ; i++)//checks for repeated input
{
System.out.println("Enter a number 1 - 9");
int num = scan.nextInt();
array[i] = num;

for(int j=0; j<i; j++)
{
if(num==array[j])
{
repeat = true;
break; //breaks out of the loop if encounters a repeated input
}
}
}

if(repeat)
System.out.println("No Duplicates Allowed!");

关于Java - 找到匹配时数组比较不会终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42306601/

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