简单的程序提示用户输入数组大小,然后输入值。然后显示总和,平均值,奇数和偶数之和,最大和最小数然后显示Y/N再次尝试提示重新启动或退出程序。 Try-catch 异常和 Y/N try again 提示重启或退出程序。
import java.util.*;
public class oneDarray {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
float sum = 0,ave,oddsum=0,evesum=0,highnum=0,lownum=0;
boolean prog=true;
while(prog==true){
try{
System.out.println("Enter size of array");
int arrSize = input.nextInt();
if(arrSize>0 && arrSize<=25){
System.out.println("Enter array elements");
float numbers[] = new float [arrSize];
for(int i=0; i<numbers.length;i++){
numbers[i] = input.nextFloat();
sum = sum + numbers[i];
if(numbers[i]==0){
highnum=numbers[i];
lownum=numbers[i];
}
if(numbers[i]%2==0){
evesum=evesum+numbers[i];
}
if(numbers[i]%2!=0){
oddsum=oddsum+numbers[i];
}
if(i==0){
lownum=numbers[i];
highnum=numbers[i];
}
if(numbers[i]<lownum)
lownum=numbers[i];
else if(numbers[i]>highnum)
highnum=numbers[i];
}
ave= sum/numbers.length;
System.out.println("The sum: "+sum);
System.out.println("The average "+ave);
System.out.println("odd sum "+oddsum);
System.out.println("even sum "+evesum);
System.out.println("highest num "+highnum);
System.out.println("lowest num "+lownum);
highnum=0;
lownum=0;
sum=0;
ave=0;
oddsum=0;
evesum=0;
}
else{
System.out.println("Invalid input");
}
System.out.println("Would you like to try again? Y/N");
char YN = input.next().charAt(0);
if(YN=='Y'||YN=='y'){
prog=true;}
else if(YN=='N'||YN=='n'){
prog=false;
System.out.println("Thank you for using the program, have a nice day");
}
}catch(InputMismatchException ime){
System.out.println("Invalid input");
System.out.println("Would you like to try again? Y/N");
char YN = input.next().charAt(0);
if(YN=='Y'||YN=='y'){
prog=true;}
else if(YN=='N'||YN=='n'){
prog=false;
System.out.println("Thank you for using the program, have a nice day");
}
}
}
}
}
复制粘贴catch中try again提示的内容,期望回答Y/N提示。显示但完全跳过提示并循环到程序开始。