本文目錄一覽:
java中如何取得一組數字的最大值?
以下是Java中的List ,如果是數組,大同小異
package com;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
//初始化數組
ListInteger nums = new ArrayListInteger();
nums.add(2);
nums.add(5);
nums.add(10);
nums.add(6);
nums.add(3);
//設置最大值Max
int Max = Collections.max(nums);
System.out.println(“Max = ” + Max);
}
}
如何用java求最大值?
測試結果為
請輸入第1個數
2
請輸入第2個數
3
請輸入第3個數
4
請輸入第4個數
5
請輸入第5個數
6
請輸入第6個數
7
請輸入第7個數
7
請輸入第8個數
8
請輸入第9個數
9
請輸入第10個數
423
最大數為:423
import java.util.Scanner;
public class MaxNum {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int max = Integer.MIN_VALUE;
for(int i = 1; i = 10; i++) {
System.out.println(“請輸入第” + i + “個數”);
int num = in.nextInt();
if(num = max) max = num;
}
System.out.println(“最大數為:” + max);
}
}
java求數組的最大值
public class B {
public static void main(String[] args) {
int[] array = {10,29,18,30,43,69};
int max = 0;//初始最大值
//遍歷循環數組
for (int i = 0; i array.length; i++) {
if(maxIndex array[i]){
maxIndex = array[i];
}
}
System.out.println(“最大值:”+max);
}
}
如有幫助請採納(不懂請提問),可以看我主頁,歡迎來交流學習;
java如何求最大值?
測試結果為
請輸入第1個數
2
請輸入第2個數
3
請輸入第3個數
4
請輸入第4個數
5
請輸入第5個數
6
請輸入第6個數
7
請輸入第7個數
7
請輸入第8個數
8
請輸入第9個數
9
請輸入第10個數
423
最大數為:423
import java.util.Scanner;
public class MaxNum {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int max = Integer.MIN_VALUE;
for(int i = 1; i = 10; i++) {
System.out.println(“請輸入第” + i + “個數”);
int num = in.nextInt();
if(num = max) max = num;
}
System.out.println(“最大數為:” + max);
}
}
Java求最大值的三種方法
普通方法:
public class Max {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5,10,11,15,100,-1,-4.5}; //定義一維數組
double num = myList[0]; //0為第一個數組下標
for (int i = 0; i myList.length; i++) { //開始循環一維數組
if (myList[i] num) { //循環判斷數組元素
num = myList[i]; } //賦值給num,然後再次循環
}
System.out.println(“最大值為” + num); //跳出循環,輸出結果 }
}
三元運算符:
public class Max {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5,10,11,15,1,-1,-4.2}; //定義一維數組
double num = myList[0]; //0為第一個數組下標
for (int i = 0; i myList.length; i++){ //開始循環一維數組
num=(myList[i] num?num: myList[i]); //三元運算符,詳情看註解
}
System.out.println(“最大值為” + num); //跳出循環,輸出結果
}}
一般函數/方法:
public class Max {
double[] myList = {1.9, 2.9, 3.4, 100,3.5,10,11,12,13,-1};
double num = myList[0];
void getValue(){ //創建一般方法
for (int i = 0; i myList.length; i++) {
num=(myList[i] num?num: myList[i]);//三元運算符
}
System.out.println(“最大值為” + num);
}
public static void main(String args[]){
Max max=new Max(); //創建對象
max.getValue(); //通過對象調用一般方法
}
}
三種求最大值的方法
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/150490.html