java - 无法在数组中获得两个相等数字的两个位置
问题描述
我正在尝试编写一个程序来确定最大的数字是多少,同时我制作了一个包含 20 个变量的数组。我正在尝试检查我是否有 2 个相同且最大的数字。如果它们相同,那么我想显示两个数字。出于某种原因,它总是写入最大的数字,但它总是显示有 2 个数组,其中最大的数字与最大的数字相同,但数组中的两个数字之一是错误的。你能帮我改正吗?谢谢!
int b,c=Integer.MIN_VALUE,d = 0,r = 0;
boolean s= false;
int[] a = new int[20];
for(b = 0 ; b < a.length ; b++) {
a[b] = (int) (Math.random()*899+100);
System.out.print(a[b] + " ");
if(a[b]==c) {
r = b;
s = true;
}
if(a[b]>= c) {
c = a[b];
d = b;
}
}
if (s = true) {
System.out.println("the biggest number was " + c + " and it was placed in the array at " + d + " as well as at " + r + " place" );
}
else {
System.out.println("the biggest number was " + c + " and it was placed in the array at " + d);
}
解决方案
你的问题是if
里面的两个for
。
如果你有a[b] == c
,那么这两个都if
将被读取。所以,这是有效的:
int b,c=Integer.MIN_VALUE,d = 0,r = 0;
boolean s= false;
int[] a = new int[20];
for(b = 0 ; b < a.length ; b++) {
a[b] = (int) (Math.random()*899+100);
System.out.print(a[b] + " ");
if(a[b] > c) {
s = false ;
c = a[b];
d = b;
} else if(a[b] == c) {
s = true;
r = b;
}
}
if (s) {
System.out.println("the biggest number was " + c + " and it was placed in the array at " + d + " as well as at " + r + " place" );
} else {
System.out.println("the biggest number was " + c + " and it was placed in the array at " + d);
}
我更正了你的最后一个if
以显示结果。
推荐阅读
- reactjs - 自定义字体已加载但未在反应打字稿中应用
- javascript - 无法触发 WebRTC onTrack 事件,尽管 peerConnection 与数据通道一起使用
- java - 在 Python 中为 2 个不同的变量初始化 2D 数组/列表
- html - 在 vueJs 中有哪些“主题或设计选择器”的方法
- python - Selenium 在单击下一页按钮后继续滚动浏览不存在的页面
- php - 尝试在浏览器上打开我的 PHP 文件时如何摆脱解析错误
- r - 我可以在闪亮的应用程序中嵌入 PowerPoint 幻灯片吗
- c++ - 如何仅使用 3 个 if 语句对 3 个字符串进行排序(C++)
- java - 新创建的主类不会出现在“浏览主类”对话框中。我该如何解决这个问题?
- javascript - 你们能帮我订购dom吗?