java - 你能帮我解决我关于方法的代码吗?
问题描述
我的作业需要一些帮助,所以基本上我们需要创建一个代码,在其中我们在一个数组中输入 10 个数字,然后搜索数组,如果我输入的数字在那里,大部分代码就完成了。我只需要方法循环来搜索输入的数字是否在数组中谢谢你的帮助!!!
public static void main(String[] args) {
int n, x, flag = 0, i = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[10];
System.out.println("Enter all the values:");
for(i = 0; i < 10; i++)
{
System.out.print("Value "+(i+1)+": ");
a[i] = s.nextInt();
}
System.out.print("Enter the value you want to find: ");
x = s.nextInt();
for(i = 0; i < 10; i++)
{
if(a[i] == x)
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
if(flag == 1)
{
System.out.println("The value "+x+" is found at index "+(i+1));
}
else
{
System.out.println("The value "+x+" is found at index "+(-1));
}
}
解决方案
public static void main(String[] args) {
int n, x, flag = 0, i = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[10];
System.out.println("Enter all the values:");
for(i = 0; i < 10; i++)
{
System.out.print("Value "+(i+1)+": ");
a[i] = s.nextInt();
}
System.out.print("Enter the value you want to find: ");
x = s.nextInt();
i = find(a, 10, x);
if(i != -1)
{
System.out.println("The value "+x+" is found at index "+(i+1));
}
else
{
System.out.println("The value "+x+" is found at index "+(-1));
}
}
private static int find(int a[],int n, int x) {
int i, flag = 0;
for(i = 0; i < n; i++)
{
if(a[i] == x)
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
if(flag == 1) {
return i;
} else {
return -1;
}
}
推荐阅读
- php - 在不更改全局版本的情况下,如何在运行 powershell 命令/实例时使用特定的 PHP 版本?
- algorithm - 动态编程范式是否总是专注于将运行时复杂度限制在 O(n) 内?
- docker - FatalErrorException 错误:超过 30 秒的最大执行时间
- angular - 当响应不匹配时,角度可观察接口不会强制任何错误
- java - 如果更改了 url,那么 Glide 是否有任何选项,然后缓存将被清除,否则会加载旧图像?
- swift - 符合 Swift 中关联类型协议的异构数组
- coding-style - oop 中更好的编码风格是什么:一种方法有一个参数 VS 两种方法没有参数?
- python - 如何在熊猫数据框中同时使用部分列名,dcast和重值进行分组
- prestashop - 在 Prestashop 1.7.6 购物车上显示产品可用性
- excel - 如何将时间写入 IF 语句以便识别它