gpt4 book ai didi

java - 分配变量以显示数组索引时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-04 11:25:05 25 4
gpt4 key购买 nike

我正在编写一个程序,生成 100 个随机数,提示用户输入一个数字,程序表示在索引 XX 处找到了该数字。或者说找不到该号码。这是我所拥有的:

import java.util.*;
import java.util.Random;
public class lab1
{
public static void main (String[]args)
{
//Let's create an array with 100 random numbers
int [] randomArray = new int [100];
Random randomGenerator = new Random();


for(int i = 0; i < randomArray.length; i++)
{
randomArray[i] = randomGenerator.nextInt(100) + 1;
}
//ask user to enter a number between 1 and 100
Scanner input = new Scanner(System.in);
int searchNumber;

System.out.println("Please enter a number between 1 and 100 to search
for: ");
searchNumber = input.nextInt();

boolean found = false;


for(int i = 0; i < randomArray.length; i++)
{
if(searchNumber == randomArray[i])
{
found = true;
break;//Exits the loop
}
}
if(found)
{
System.out.println("We have found your number, " + searchNumber + "
at index " + index);
}
else
{
System.out.println("We did not find your number");
}
}
}

当我的程序找到一个数字时,我无法获取要显示的索引,我知道这是因为变量“i”仅在 for 循环中定义。我不知道如何在 for 循环之外创建一个新变量并将 i 分配给 for 循环内的该变量。

最佳答案

在循环外声明i,即

int i;
for(i = 0; i < randomArray.length; i++)
{
...
...
...
}

然后您可以在 println 中使用索引 i

if(found)
{
System.out.println("We have found your number, " + searchNumber + "at index " + i);
}
else
{
System.out.println("We did not find your number");
}

关于java - 分配变量以显示数组索引时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44467935/

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