Java程序输出5个数的总和_如何在java中编写一个程序,它将取5个整数并输出最小和最大整数?...

为什么你需要120个不同的if语句?

你已经得到了关于调用数学函数来完成工作的答案,我已经使用了一种简单的排序方法来完成工作。

您的问题的解决方案分为以下几种:

1)读取用户输入

2)排序

3)从排序的束中找出最大最小值

码:

//Import relevant packages

import java.io.BufferedReader;

import java.io.InputStreamReader;

class MinMax {

public static void main(String[] args) {

int[] myArray = new int[5]; //Array to hold user input of 5 integers

int[] resultArray; //reference var to hold the resultArray object

//Buffered reader is wrapped around the input stream reader to read user input

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

//Loop to get user input, 5 times

for (int i=1;i<=5;i++){

System.out.println("Enter a number: ");

try{

myArray[i-1] = Integer.parseInt(reader.readLine()); //String to integer the user input

}

catch(Exception e){

e.printStackTrace();

}

}

//Calling the function sortme() to do the sorting

resultArray = sortme(myArray);

//After bubble sort has sorted the input array, the min is the first and max is the last, values of the array

System.out.println("The min is: " + resultArray[0] + ", and the max is: "+myArray[4]);

}

//Bubble sort

static int[] sortme(int[] array){

int temp;

for (int i=(array.length-1);i>=0;i--){

for (int j=1;j<=i;j++){

if (array[j-1] > array[j]){

temp = array[j-1];

array[j-1] = array[j];

array[j] = temp;

}

}

}

return array;

}输入:

1 4 6 3 9输出:

The min is: 1, and the max is: 9编辑

Yetti先生指出了排序方法的低效率,因为它首先不需要。这是迭代方法:

import java.io.BufferedReader;

import java.io.InputStreamReader;

class MinMax_nosort {

public static void main(String[] args) {

int[] myArray = new int[5]; //Array to hold user input of 5 integers

//Buffered reader is wrapped around the input stream reader to read user input

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

//Loop to get user input, 5 times

for (int i=1;i<=5;i++){

System.out.println("Enter a number: ");

try{

myArray[i-1] = Integer.parseInt(reader.readLine()); //String to integer the user input

}

catch(Exception e){

e.printStackTrace();

}

}

minmax(myArray);

}

static void minmax(int[] array){

int max, min;

max = min = array[0];

for (int i=1;i

if (array[i] > max)

max = array[i];

else if(array[i] < min)

min = array[i];

}

System.out.println("The min is:" + min + " and the max, is: " + max);

}输入:

1 4 6 3 9输出:

The min is:1 and the max, is: 9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值