Created
October 31, 2010 15:37
-
-
Save Feuda/656729 to your computer and use it in GitHub Desktop.
看如何输入数组
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Example12 { | |
public void input(int[] arr) { | |
System.out.println("请输入5个整数,每输入一个请按回车键:"); | |
try { | |
byte[] buf = new byte[20]; | |
for (int i = 0; i < arr.length; i++) { | |
System.in.read(buf); | |
String str = new String(buf); | |
arr[i] = Integer.parseInt(str.trim()); | |
} | |
} catch (Exception e) { | |
System.out.println("程序遇到异常,即将终止"); | |
System.exit(0); | |
} | |
} | |
public int getMax(int[] arr) { | |
int max = arr[0]; | |
for (int i = 1; i < arr.length; i++) { | |
if (max < arr[i]) { | |
max = arr[i]; | |
} | |
} | |
return max; | |
} | |
public int getSum(int[] arr) { | |
int sum = 0; | |
for (int i = 0; i < arr.length; i++) { | |
sum += arr[i]; | |
} | |
return sum; | |
} | |
public void echo(int[] arr) { | |
System.out.println("数组各元素如下:"); | |
for (int i = 0; i < arr.length; i++) { | |
System.out.print(arr[i] + " "); | |
} | |
System.out.println(); | |
} | |
} | |
public class Example12_Test { | |
public static void main(String[] args) { | |
int[] array = new int[5]; | |
Example12 ob = new Example12(); | |
ob.input(array); | |
int max = ob.getMax(array); | |
int sum = ob.getSum(array); | |
ob.echo(array); | |
System.out.println("其中的最大值为: " + max); | |
System.out.println("其和值为: " + sum); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment