[英]How to search the highest value with Java
我有下面的代码写在1维数组中搜索最大值。 但是由于某些错误,它无法正常工作。 下面是代码:
import java.io.*;
public class theHigest{
int max = 0;
int[] value = new int[5];
BufferedReader objInput = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[]args){
theHigest obj6 = new theHigest();
obj6.input();
}
void input(){
try{
for(int i=0;i<=4;i++){
System.out.println("===========================");
System.out.print("Value input-"+(i+1));
value[i]= Integer.parseInt(objInput.readLine());
System.out.println("===========================");
}
}
catch(Exception e){
System.out.println("Error "+ e);
}
}
}
您尚未实现用于搜索数组中最高元素的任何功能。 您可以在输入函数本身中添加少量代码。 无需排序。 这将导致您登录,而您仅通过遍历数组一次就可以做得更好。 这将花费O(n)。
void input(){
try{
for(int i=0;i<=4;i++){
System.out.println("===========================");
System.out.print("Value input-"+(i+1));
value[i]= Integer.parseInt(objInput.readLine());
System.out.println("===========================");
}
// searching for highest element in array
int highest = value[0];
for(int i=1;i<=4;i++){
if(value[i]>highest){
highest = value[i];
}
}
System.out.println("The Highest is :: "+ highest);
}
catch(Exception e){
System.out.println("Error "+ e);
}
}
}
这是解释该概念的参考代码。 请参考它并相应地调试代码。
public class FindLargestSmallestNumber {
public static void main(String[] args) {
//array of 10 numbers
int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23};
//assign first element of an array to largest and smallest
int smallest = numbers[0];
int largest = numbers[0];
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > largest)
largest = numbers[i];
else if (numbers[i] < smallest)
smallest = numbers[i];
}
System.out.println("Largest Number is : " + largest);
System.out.println("Smallest Number is : " + smallest);
}
}
该程序的输出为
最大数字是:98
最小数字是:23
您可以使用以下代码找到max:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class TheMax {
int max = 0;
int[] values = new int[5];
BufferedReader objInput = new BufferedReader(new InputStreamReader(
System.in));
public static void main(String[] args) {
TheMax obj6 = new TheMax();
obj6.input();
}
void input() {
try {
for (int i = 0; i <= 4; i++) {
System.out.println("===========================");
System.out.print("Value input [" + (i + 1) +"] :: ");
values[i] = Integer.parseInt(objInput.readLine());
System.out.println("===========================");
}
Arrays.sort(values);
System.out.println("The Max is :: "+ values[values.length - 1]);
} catch (Exception e) {
System.out.println("Error " + e);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.