Charles_Su 2017-02-18 13:16 采纳率: 21.4%
浏览 1260

输入两个数输出这两个数的均值 输入个数或格式有误 提示输入错误使用trycatchfinally报错

package com.xmu.hellojava.main;
import com.xmu.hellojava.domain.Student;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StudentTest {

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
//Calculating the average
System.out.printf("Please enter two numbers:(Separated by spaces)\n");//Prompt message
StudentTest t = new StudentTest();
System.out.println("Average Value:"+t.average());
//end calculating the average

}
public double average() throws IOException
{
double []result=new double[2];
while(true)
{
BufferedReader input5= new BufferedReader(new InputStreamReader(System.in));
String str=input5.readLine();//读取字符串
String[]new_str= str.split("\s+");//以空格分割字符串
double []num=new double[new_str.length];
int flag=-1,flag1=-1;//用于判断输入结果是否正确
for (int i = 0; i<new_str.length; i++){
try {
num[i]=Double.valueOf(new_str[i].toString());
flag1=2;
} //end try
catch (NumberFormatException e) {
e.printStackTrace();
}//end catch
}//将字符串转化为数,结束循环
finally{
try{
flag=new_str.length;
if(flag!=2||flag1!=2){
Exception me=new Exception("Invalid input");
throw me;
}//end if
result[0]=num[0];
result[1]=num[1];
break;
}//end try
catch(Exception e)
{//若输入个数或格式有误,提示用户输入错误
System.out.println(e.getMessage()+",try again\n");//Prompt message
}//end catch
}//end finally
}//end while
return (result[0]+result[1])/2.0;

}//average

}

  • 写回答

1条回答 默认 最新

  • threenewbee 2017-02-18 16:33
    关注

    说了半天也没说清楚你想问什么,哪里有问题

    目测double.valueof换成Double.parseDouble试试看

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题