Приложение 1. Програма за изчисляване на средна стойност.
Вариант 1: методът average() не “улавя” изключения от вида NumberFormatException, хвърлени от метода parseDouble() и затова при грешка във формата на въвежданите числа програмата не завършва.
import java.io.*;
import java.util.*;
class EssentialMath{
public static double average() throws IOException{
System.out.println("Enter numbers at the same line");
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
String s=b.readLine();
StringTokenizer st=new StringTokenizer(s);
double sum=0;
int numberOfValues =0;
while(st.hasMoreTokens()){
String n=st.nextToken();
double num=Double.parseDouble(n);
sum +=num;
numberOfValues++;
}
double average=sum/numberOfValues;
return average;
}
}
public class FindAverage {
public static void main(String[] args)throws IOException {
double avg=EssentialMath.average();
System.out.println("The average value is: "+avg);
}
}
Вариант 2. Модифициран метод average(), който “улавя” изключения от вида NumberFormatException, хвърлени от метода parseDouble(). Това позволява числата с грешен формат да се пренебрегнат и да се изведе информация къде са грешните числа.
public static double average() throws IOException{
System.out.println("Enter numbers at the same line");
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
String s=b.readLine();
StringTokenizer st=new StringTokenizer(s);
double sum=0;
int numberOfValues =0;
int numberOfErrors=0;
while(st.hasMoreTokens()){
String n=st.nextToken();
try{
double num=Double.parseDouble(n);
sum +=num;
numberOfValues++;
}catch(NumberFormatException e){
numberOfErrors++;
System.out.println("Invalid number at position "+
(numberOfValues+numberOfErrors)+" ignored.");
} }
double average=sum/numberOfValues;
return average;
}
Приложение 2. Програма за решаване уравнението на Кортевег де Вриз за три случая: 1) Начална вълна с две нива 2) Разпространение на 2 солитона
3) Формиране на ударна вълна
import java.io.*;
import java.util.Scanner;
public class Soliton {
//define constants
static double mu=0.1;//dispersion parameter
static double eps=0.15;//nonlinear parameter
static double dx=0.4;//space step
static double dt=0.1;//time step
static int tmax=1000;//number of time iterations
static int xmax=131;//number of x points
static int pause=50;//pause before writing results
public static void main(String[] args)throws FileNotFoundException {
int i, j, k, number;
double a1,a2,a3;//terms in brackets
double time,param1=eps*dt/(3*dx),param2=mu*dt/(dx*dx*dx);//time and parameters
double u[][]=new double[xmax][3];
System.out.println("Enter 1 for two-level wave; 2 for 2 solitons;");
System.out.println("3 for shock wave");
Scanner sc=new Scanner(System.in);
number=sc.nextInt();
//open file to write the results
PrintWriter w=new PrintWriter(new FileOutputStream("soliton.txt"),true);
switch(number){
case 1: //initial two-level form
for(i=0;i
u[i][0]=0.5*(1-Math.tanh((i*dx-25)/5.));
//boundary conditions
u[0][1]=1.; u[0][2]=1.;u[xmax-1][1]=0.; u[xmax-1][2]=0.;
break;
case 2: //initial form for 2 solitons
for(i=0;i
u[i][0]=0.8*(1-Math.pow(Math.tanh(3*i*dx/12-3),2))+
0.3*(1-Math.pow(Math.tanh(4.5*i*dx/26-4.5),2));
//boundary conditions
u[0][1]=0.; u[0][2]=0.;u[xmax-1][1]=0.; u[xmax-1][2]=0.;
break;
case 3: //initial form for shock-wave
param2=0;//no dispersion
for(i=0;i
u[i][0]=0.5*Math.sin(i*dx*2*Math.PI/((xmax-1)*dx));
//boundary conditions
u[0][1]=0.; u[0][2]=0.;u[xmax-1][1]=0.; u[xmax-1][2]=0.;
break;
}//end of switch
//write initial wave in file
for(i=0; i
w.print(u[i][0]+"\t");
w.println();
//first time step
time=dt;
for(i=1;i
a1=u[i+1][0]+u[i][0]+u[i-1][0];
a3=u[i+1][0]-u[i-1][0];
if(i>1 && i< (xmax-2)) a2=u[i+2][0]+2*u[i-1][0]-2*u[i+1][0]-u[i-2][0];
else a2=u[i-1][0]-u[i+1][0];
u[i][1]=u[i][0] - param1*a1*a3/2 - param2*a2/2;
}
//other time steps
for(j=1; j
time +=dt;
for(i=1;i
a1=u[i+1][1]+u[i][1]+u[i-1][1];
a3=u[i+1][1]-u[i-1][1];
if(i>1 && i< (xmax-2)) a2=u[i+2][1]+2*u[i-1][1]-2*u[i+1][1]-u[i-2][1];
else a2=u[i-1][1]-u[i+1][1];
u[i][2]=u[i][0] - param1*a1*a3 - param2*a2;
}
//write results in file
if(j==1||j%pause==0){
for(k=0;k
w.println();
}
for(k=0;k
u[k][0]=u[k][1]; u[k][1]=u[k][2]; //make a time-step shift
}
}//end of j-loop
System.out.println("Find results in file: soliton.txt");
}
}
Сподели с приятели: |