实现直线类

 //实现直线类,通过输入一次函数的参数(a,b,c)建模直线,并且对直线进行检查,如果输入的a和b都为零的话,

//则需要重新输入,其他功能为:判断所输入的两条直线是否平行,如果平行则告知用户,

//如果不平行则将这两条直线的交点输出来。(初学者仅供参考考)

import java.io.BufferedReader; import java.io.InputStreamReader; import java.text.DecimalFormat; public class Line { private double a; private double b; private double c; Line() { a = getValue(); b = getValue(); c = getValue(); } public double getValue() { return inputValue(); } //输入数值 public double inputValue() { double value = 0.0; System.out.println("Enter value:"); try { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); String s=in.readLine(); value = Double.parseDouble(s); }catch (Exception e){} return value; } //检查输入的直线是否合法,如果不合法将循环输入 public void checkLine() { while(a == 0 && b == 0) { System.out.println("This isn't a line: a and b can't be 0 " + "at the same time.Please input again."); a = getValue(); b = getValue(); c = getValue(); } System.out.println("This is a line. And input another."); } //输出直线 public void displayLine() { System.out.println("line: " + a + "x + " + b + "y + " + c + " = 0.0"); } //判断两条直线是否平行 public void isParallel(Line l1, Line l2 ) { if((l1.a == 0 && l2.b == 0 && l2.a != 0 && l1.b != 0) || (l2.a ==2 && l1.b == 0 && l1.a != 0 && l2.b != 0)) { System.out.println("/nline1 and line2 aren't parallel."); pointOfIntersection(l1, l2); } else if(l1.a * l2.b == l2.a * l1.b) System.out.println("/nline1 and line2 are parallel."); else { System.out.println("/nline1 and line2 aren't parallel."); pointOfIntersection(l1, l2); } } //求交点 public void pointOfIntersection(Line l1, Line l2) { DecimalFormat twoDigits = new DecimalFormat("0.00"); double y = 0.0; double x = 0.0; double n1 = 0.0; //若其中某个系数为零的情况 if(l1.a == 0) { y = (-l1.c) / l1.b; x = (-l2.c - l2.b * y) / l2.a; } else if(l2.a == 0) { y = (-l2.c) / l2.b; x = (-l1.c - l1.a * y) / l1.a; } //系数都不为零的情况 else { n1 = l1.a / l2.a; y = (-l1.c + n1 * l2.c) / (l1.b - n1 * l2.b); x = (-l2.c - l2.b * y) / l2.a; } System.out.println("The point of intersection is (" + twoDigits.format(x) + " , " + twoDigits.format(y) + ")"); } public static void main(String[] args) { System.out.println("Enter value of a, b and c about every line." + " Make sure a and b can't be 0 at the same time!!"); Line line1 = new Line(); line1.checkLine(); Line line2 = new Line(); line2.checkLine(); line1.displayLine(); line2.displayLine(); line1.isParallel(line1, line2 ); } }

你可能感兴趣的:(exception,string,input,import,class,c)