我在下面的代码中写入以搜索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);
}
}
}
答案 0 :(得分:1)
您尚未实现搜索数组中最高元素的任何功能。您可以在输入函数中添加一小段代码。不需要分类。这将导致你nlogn,而你只需通过一次遍历你的数组就可以做得更好。它将花费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);
}
}
}
答案 1 :(得分:0)
这是解释概念的参考代码。请参考它&amp;相应地调试你的代码。
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
答案 2 :(得分:0)
您可以使用以下代码找到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);
}
}
}