java - How to find if in an array of scores each score is equal to or lower than the one preceding it?
问题描述
Under some set of scores the code "misbehave" and ending with false result. This occurs for example on this set of scores:
5, 4, 3, 2, 5
As long as the numbers decreasing everything is fine, but at the last step, where it's increasing again, the code fails to return the right answer.
Any help and explanation would be really appreciated.
Task Given an array of scores, print 'true' if each score is equal to or lower than the one preceding it. Input Format The first line contains a single integer, n, denoting the size of the array. Each of the subsequent n lines contains a single integer denoting the value of the array at the next position. Constraint The length of the array will be 2 or more. Output Simply the word 'true' or 'false'.
Input 5 4 3 2 1 1 Expected Output true Output true Input 5 4 3 2 1 2 Expected Output false Output true
Already tried multiple solutions by my own but I'm an absolutely beginner, all my attempts failed.
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int[] array3 = new int[a];
int m; int j = 1; int ctn=-1;
//System.out.println("ctn= -1");
for(int i=0; i<array3.length; i++){
m = sc.nextInt();
while(j<array3.length && array3[j] < m){
j++;
}
if(j == array3.length){
array3[i] = m;
ctn++;
j = 0;
//System.out.println("ctn+1 m>j " + ctn);
}else{
array3[i] = m;
j = 0;
//System.out.println("ctn m<=j " + ctn);
}
}
if(ctn != 0){
System.out.println("false");
}else{
System.out.println("true");
}
}
}
解决方案
编辑:我不完全确定您是否希望每个分数等于或低于它之前的所有分数(或)它之前的直接分数。
如果它只是它之前的直接分数,那么一个带有查找的简单循环来检查以前的值就可以了,否则请参阅下面的内容。
执行此操作的简单方法是跟踪您迄今为止遇到的最低“分数”并将其用于检查条件。
Scanner scan = new Scanner(System.in);
int count= scan.nextInt();
int lowest = Integer.MAX_VALUE;
boolean flag = false;
for(int i=0;i<count;i++) {
int current = scan.nextInt();
if(lowest<current) {
flag = true;
break;
} else if(current<lowest) {
lowest = current;
}
}
if(flag) {
System.out.println("false");
} else {
System.out.println("true");
}
推荐阅读
- r - 按年份分组数据并总结价值
- qt - qt 资源 在 qml qrc:///bg.png vs ../bg.png 中使用资源的正确形式是什么
- haskell - Haskell Servant(客户端):由于奇怪的 Accept 标头导致 UnsupportedContentType 错误
- docker - 即使测试成功,nginx 容器也会以代码 0 退出
- ios - 有没有办法在 SwiftUI 中的动画之后执行函数?
- python - 如何在机器人框架中将设置下的变量设置为环境变量
- android - App Inventor:如何从列表中删除空项目?
- web-scraping - 无法通过 chrome 控制台访问谷歌翻译元素
- sql - Oracle Pivot 的值包含 &
- php - 在 nginx 的某个目录上的图像文件中运行 php 代码