java期末 xy PTA

文章目录

选择题

1. 如果需要从文件中读取数据,则可以在程序中创建哪一个类的对象(A)。 (2分)

FileInputStream
FileOutputStream
DataOutputStream
FileWriter

2. 下列关于System类的叙述中,错误的是( C)。 (2分)

System类是一个final类
System类不能实例化
System类中没有定义属性
System类主要提供了系统环境参数的访问

3. 在面向对象的软件系统中,不同类对象之间的通信的一种构造称为D_。 (2分)

属性
封装

消息

4. 在面向对象方法中,继承定义了超类和子类的概念,子类在维持原有父类中方法签名不变的前提下,用适合于自己要求的实现去置换父类中的相应方法的实现称为_B_。 (2分)

A. 继承
B. 覆盖(overriding)
C. 重载(overloading)
D. 多态

特性 解释
覆盖 在面向对象方法中,继承定义了超类和子类的概念,子类在维持原有父类中方法签名不变的前提下,用适合于自己要求的实现去置换父类中的相应方法的实现
重载 重载(overloading) 是在一个类里面,方法名字相同,而参数不同。返回类型可以相同也可以不同。
重写 重写是子类对父类的允许访问的方法的实现过程进行重新编写, 返回值和形参都不能改变。即外壳不变,核心重写!
多态 多态是同一个行为具有多个不同表现形式或形态的能力

5. 以下哪句是错误的?C (2分)

编译器会搜索要import的类的编译结果文件而不是源文件
import是告诉编译器要import的包的信息
import是把要import的类的源代码插入到import语句所在的地方
编译器在编译的时候需要能访问得到要import的类的编译结果文件

6. 在Java中,负责对字节代码解释执行的是 (B ) (2分)

应用服务器
虚拟机
垃圾回收器
编译器

7. 下面哪一个描述是正确的?B (2分)

Node对象可以被放置在 Scene中.
Node对象可以被放置在 Pane中.
Shape 对象可以被放置在Control中.
Pane对象可以被放置在Control中.

8. 为了从pane中删除两个节点 node1和node2 ,使用下面哪一个语句 C__. (2分)

pane.removeAll(node1, node2);
pane.remove(node1, node2);
pane.getChildren().removeAll(node1, node2);
pane.getChildren().remove(node1, node2);

9. 为了在BorderPane p的左部放置一个node对象, 使用下面哪一个语句 _A. (2分)

p.setLeft(node);
p.placeLeft(node);
p.left(node);
p.setEast(node);

填空题

10. 下面的程序将唐诗《登鹳雀楼》写入登鹳雀楼.tx文件中,

然后再将该文件的内容读出,打印在显示器上。 请阅读分析程序并填空。

import java.io.*;

public class FileRW {
	public static void main(String[] args) {
		String str = "白日依山尽\n";
		char[] ch = str.toCharArray();
		FileWriter fw = null;
		FileReader fr = null;
		try {
			fw = new ==FileWriter== (2)("登鹳雀楼.txt");
			fw.write(ch);
			fw.write("黄河入海流\n");
			fw.==write==(2)("欲穷千里目\n");
			fw.write("更上一层楼\n");
			fw.close();
		} catch (IOException e) {
			System.err.println("流的创建、写和关闭都可能产生IOException异常。");
			System.exit(-1);
		}
		try {
			fr = new ==FileReader==(2)("登鹳雀楼.txt");
			int i;
			while ((i = fr.==read==(2)()) != -1) {
				System.out.print((char) i);
			}
			System.out.println();
			fr.close();
		} catch (==FileNotFoundException==(2) e) {
			System.err.println("文件未找到!");
			System.exit(-2);
		} catch (==IOException==(2) e) {
			System.err.println("读和关闭都可能产生IOException异常。");
			System.exit(-3);
		}
	}
}

. 该程序将10个整数写入一个文件,然后读出来并显示。

import java.io.*;

public class TestFileStream {
  public static void main(String[] args) throws IOException {
    FileOutputStream output = new ==FileOutputStream==(2)("temp.dat"); // Create an output stream to the file
 // Output values to the file
    for (int i = 1; i <= 10; i++)
      output.write(i);
// Close the output stream
    output.close();
// Create an input stream for the file
  ==FileInputStream== (2) input = new FileInputStream("temp.dat");
// Read values from the file
    int value;
    while ((value = input.read()) != -1)
      System.out.print(value + " ");
 // Close the output stream
    input.close();
  }
}

2. (4分)该程序将10个整数写入一个文件,然后读出来并显示。

import java.io.*;
public class TestFileStream {
  public static void main(String[] args) throws IOException {
    // Create an output stream to the file
    FileOutputStream output = new (==FileOutputStream==)(2)("temp.dat");
 // Output values to the file
    for (int i = 1; i <= 10; i++)
      output.write(i);
 // Close the output stream
    output.close();
 // Create an input stream for the file
   (==FileInputStream==)(2) input = new FileInputStream("temp.dat");

    // Read values from the file
    int value;
    while ((value = input.read()) != -1)
      System.out.print(value + " ");

    // Close the output stream
    input.close();
  }
}

3. 下列程序将容器中的所有字符串转换成大写然后输出。请阅读分析程序并填空。

import java.util.*;
public class TestIterator {
  public static void main(String[] args) {
    Collection<String> collection = new ArrayList<>();
    collection.add("New York"); 
    collection.add("Atlanta"); 
    collection.add("Dallas"); 
    collection.add("Madison"); 

    Iterator<String> iterator = collection.iterator();
    while (iterator.(==hasNext==)(2)()) {
      System.out.print(iterator.(==next==)(2)().toUpperCase() + " ");
    }
    System.out.println();
  }
}

4.面向对象的基本特征是: 面向对象的基本特征是(封装)(1分), (继承)(1分),(多态) (1分)


程序填空

1. (检验密码)一些网站设定了一些制定密码的规则。

编写一个方法,检验一个字符串是否合法的密码。假设密码规则如下: 密码必须至少有8个字符。 密码只能包含字母和数字。 密码必须至少有2个数字。 请编写一个程序,提示用户输入密码,如果改密码符合规则就显示“Valid password”,否则显示“Invalid password”。

public class Main {
	  public static void main(String[] args) {
	    // Prompt the user to enter a password
	    java.util.Scanner input = new java.util.Scanner(System.in);
	    //System.out.print("Enter a string for password: ");
	    String s = input.nextLine();
	    if (isValidPassword(s)) {
	      System.out.println("Valid password");
	    }
	    else {
	      System.out.println("Invalid password");
	    }
	  }
	  /** Check if a string is a valid password */
	  public static boolean isValidPassword(String s) {
	    // Only letters and digits?
	    for (int i = 0; i < s.length(); i++) {
	      if (((!Character.isLetter(s.==charAt(i)==))(3)) && 
	          !Character.isDigit(s.charAt(i)))
	        return false;
	    }
	    // Check length
	    if ((==s.length()==)(2) < 8)
	      return false;
	    // Count the number of digits
	    int count = 0;
	    for (int i = 0; i < s.length(); i++) {
	      if ((Character.isDigit(s.charAt(i)))(2))
	        count++;
	    }
	    if (count >= 2)
	      return true;
	    else 
	      return false;
	  }
	}

2. 相同的数组。如果两个数组list1和list2的内容相同,那么就说它们是相同的。使用下面的程序可以判断两个数组是否相同,请填空补全程序。

import java.util.*;
public class Main {
  public static void main(String[] args) {
     Scanner input = new Scanner(System.in);
     int size1 = input.nextInt();
     int[] list1 = new int[size1];
     // Enter values for list1
     for (int i = 0; i < list1.length; i++)
        list1[i] = input.nextInt();
     int size2 = input.nextInt();
     int[] list2 = new int[size2];
     // Enter values for list2
     for (int i = 0; i < list2.length; i++)
        list2[i] = input.nextInt();
     input.close();
     if ((equals(list1,list2))(4)) {
        System.out.println("Two lists are identical");
     } else {
        System.out.println("Two lists are not identical");
     }
  }
  public static boolean equals(int[] list1, int[] list2) {
     if ((list1.length != list2.length)(3))
        return false;
     Arrays.sort(list1);
     (Arrays.sort(list2))(3);
     for (int i = 0; i < list1.length; i++)
        if (list1[i] != list2[i])
           return false;
     return true;
  }
}

3. 下面的程序从键盘输入一个整数,然后输出该整数的10倍数。

import java.io.*;
public class Main {
    public static void main(String[] args) {
    	(BufferedReader)(3) in=new BufferedReader(new (InputStreamReader)(3)(System.in));
    	System.out.print("Please input a integer:");
    	try{  int i = Integer.(parseInt)(2)(in.readLine());
    	       System.out.println("Ten times of the number:"+10*i);
    	       in.close();
    	}catch((IOException e)(2)){
    		System.err.println(e.toString());    	
    		}    	
    }
}

4. 求解圆柱体的体积

import java.util.Scanner;
class Circle 
{
      private double radius;
      public Circle(double radius) {this.radius = radius;}
      public double getRadius() {(return radius)(2);}
      public void setRadius(double radius) {(this.radius = radius)(2);}
      public double getArea() {return (Math.PI*radius*radius)(2) ;}
}
class Cylinder (extends)(2)  Circle
{
   double height =100;
   public Cylinder(double radius,double height) {super(radius); this.height = height ;}
   public double getVolumn() {
   return getArea()  * height;
  }
}
public class Main{
  public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       double height = sc.nextDouble();
       double radius = sc.nextDouble();
        Cylinder obj = new Cylinder(radius, height);
        System.out.printf("Cylinder obj Volumn is %.2f",(obj.getVolumn())(2) );
  }
}

5. 有一张足够大的纸,厚0.01 毫米。问将它对折多少次后可以达到珠穆朗玛峰的高度(8848.43米)。

class FoldCount {
       public int getCount(double h)  {
              int n =0 ;
              while(h<8848.43)  {
                   (h = h*2)(2);
                   (n++)(2);
                }
               (return n)(2);
     }
}
public class Main {
      public static void main(String[] args)  {
           FoldCount obj;
           obj =(new FlodCount())(2);
           System.out.println(“count=+(obj.getCount(0.0001))(2)) ;
       }
   }
}

5-1

这是程序填空题模板。题目要求写在这里。例如:本题目要求打印“Hello World!”。

下面的程序从键盘输入一个整数,然后输出该整数的10倍数。
import java.io.;
public class Main {
public static void main(String[] args) {
(3分) in=new BufferedReader(new inputStreamReader(3分)(System.in));
System.out.print(“Please input a integer:”);
try{ int i = Integer.(2分)(in.readLine());
System.out.println(“Ten times of the number:”+10
i);
in.close();
}catch((2分)){
System.err.println(e.toString());
}
}
}

【说明】现欲构造一文件/目录树,

采用组合(Composite)设计模式来设计,得到的类图如下图所示:
目录树.png

import java.util.ArrayList;
import java.util.List;

(2分) abstractclass AbstractFile {
protected String name;
public void printName() {
System.out.println(name);
}
public abstract boolean addChild(AbstractFile file);
public abstract boolean removeChild(AbstractFile file);
public abstract List getChildren();
}

class File extends AbstractFile {
public File(String name) {
this.name = name;
}
public boolean addChild(AbstractFile file) {
return false;
}
public boolean removeChild(AbstractFile file) {
return false;
}
public List getChildren() {
return Null (2分);
}
}

class Folder extends AbstractFile {
private List childList;
public Folder(String name) {
this.name = name;
this.childList = new ArrayList();
}
public boolean addChild(AbstractFile file) {
return childList.add(file);
}
public boolean removeChild(AbstractFile file) {
return childList.remove(file);
}
public (2分)List getChildren() {
return ChildList(2分);
}
}

public class Main {
public static void main(String[] args) {
// 构造一个树形的文件/目录结构
AbstractFile rootFolder = new Folder(“root”);
AbstractFile compositeFolder = new Folder(“composite”);
AbstractFile windowsFolder = new Folder(“windows”);
AbstractFile file = new File(“TestComposite.java”);
compositeFolder.addChild(file);
rootFolder.addChild(compositeFolder);
rootFolder.addChild(windowsFolder);
// 打印目录文件树
printTree(rootFolder);
}
private static void printTree(AbstractFile ifile) {
ifile.printName();
List children = ifile.getChildren();
if (children == null)
return;
for (AbstractFile file : children) {
return (2分);
}
}
}

函数题

1.从抽象类shape类扩展出一个圆形类Circle

请从下列的抽象类shape类扩展出一个圆形类Circle,这个类圆形的半径radius作为私有成员,类中应包含初始化半径的构造方法。 public abstract class shape {// 抽象类 public abstract double getArea();// 求面积 public abstract double getPerimeter(); // 求周长 } 主类从键盘输入圆形的半径值,创建一个圆形对象,然后输出圆形的面积和周长。保留4位小数。
答案:

class Circle extends shape{
    double r;
    Circle(double r) {
        this.r = r;
    }
    public double getArea() {
        return Math.PI * r * r;
    }

    public double getPerimeter() {
        return 2.0 * Math.PI * r;
    }
}

2.计算正五边形面积

从下列的抽象类shape类扩展出一个正五边形(regular pentagon)类RPentagon,这个类将正五边形的边长作为私有成员,类中包含初始化这个值的构造方法。

public abstract class shape {// 抽象类
public abstract double getArea();// 求面积
public abstract double getPerimeter(); // 求周长
}

计算正五边形的面积公式为:
答案:

class RPentagon extends shape{
    double side;
    RPentagon(double side) {
        this.side = side;
    }

    public double getArea() {
        return side * side * Math.sqrt(25 + 10 * Math.sqrt(5)) / 4;
    }

    public double getPerimeter() {
        return 5 * side;
    }
}

3.求解正六边形的类实现

创建一个正六边形(regular hexagon)RHexagon类,实现下列接口IShape。RHexagon类将正六边形的边长作为私有成员,类中包含初始化这个值的构造方法。
interface IShape {// 接口
double getArea(); // 求面积
double getPerimeter();// 求周长
}
请编程从键盘输入正六边形的边长值,创建一个正六边形对象,然后输出正六边形的面积和周长。保留4位小数。

答案:

class RHexagon implements IShape {
    double a;
    RHexagon(double a) {
        this.a = a;
    }
    public double getArea() {
        return 3 * Math.sqrt(3) * a * a / 2;
    }
    public double getPerimeter() {
        return 6 * a;
    }
}

4.设计一个矩形类Rectangle

设计一个名为Rectangle的类表示矩形。这个类包括: 两个名为width和height的double型数据域,它们分别表示矩形的宽和高。width和height的默认值都为1. 一个无参构造方法。 一个为width和height指定值的矩形构造方法。 一个名为getArea()的方法返回这个矩形的面积。 一个名为getPerimeter()的方法返回这个矩形的周长。
答案:

class Rectangle {
    double w, h;
    Rectangle(double w, double h) {
        this.w = w;
        this.h = h;
    }
    double getArea() {
        return w*h;
    }
    double getPerimeter() {
        return 2*(w+h);
    }
}

5.创建一个直角三角形类实现IShape接口

创建一个直角三角形类(regular triangle)RTriangle类,实现下列接口IShape。两条直角边长作为RTriangle类的私有成员,类中包含参数为直角边的构造方法。 interface IShape {// 接口 public abstract double getArea(); // 抽象方法 求面积 public abstract double getPerimeter(); // 抽象方法 求周长 }

答案:

class RTriangle implements IShape {
    double a, b, r;
    RTriangle(double a, double b) {
        this.a = a; this.b = b;
    }
    public double getArea() {
        return a*b/2;
    }
    public double getPerimeter() {
        return a+b+Math.sqrt(a*a+b*b);
    }
}

6.使用抽象类求解Circle的相关信息

请从下列的抽象类shape类扩展出一个圆形类Circle,这个类圆形的半径radius作为私有成员,类中应包含初始化半径的构造方法。
public abstract class shape {// 抽象类
public abstract double getArea();// 求面积
public abstract double getPerimeter(); // 求周长
}
主类从键盘输入圆形的半径值,创建一个圆形对象,然后输出圆形的面积和周长。保留4位小数。

答案:

class Circle extends shape {
    double r;
    Circle (double r) {
        this.r = r;
    }
    public double getArea() {
        return Math.PI * r * r;
    }

    public double getPerimeter() {
        return 2.0 * Math.PI * r;
    }
}

编程题

1.找出最大的对象

(找出最大的对象)编写一个方法,返回对象数组中最大的对象。方法签名如下:
public static Object max(Comparable[] a) public static Object max(Comparable[] a)
import java.util.; public class Main{ public static Object max(Comparable[] a) { /// 请填写此部分内容 }
答案:
import java.util.
;

public class Main{
public static Object max(Comparable[] a) {
Arrays.sort(a);
return a[4];
}
public static void main(String[] args){
String[] sArray = new String[5];
Integer[] intArray = new Integer[5];
Scanner input = new Scanner(System.in);
for(int i=0;i<sArray.length;i++) {
sArray[i] = input.next();
}

    for(int i=0;i<intArray.length;i++)  {
        intArray[i] = new Integer(input.nextInt());
    }

    System.out.println("Max string is " +(String)max(sArray));
    System.out.println("Max integer is " + (Integer)max(intArray));
}

}

2.给定一元二次方程的系数,求一元二次方程的根

给定一元二次方程的系数,求一元二次方程的根。简便起见,不要求是复根,而且相等的根只输出一个解。注意判断浮点数为零与否用|x|<10e-6来判断。要求可以重复输入输出。要求结果保留小数点后两位数字。 输入输出形式范例: 输入样例1: 1 2 1 输出样例1:The root is:-1.00. 输入样例2: 1 2 -1 输出样例2: The roots are 0.41 and -2.41. 输入样例3: 1 2 2 输出样例3: The equation has no real roots.
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double eps = 1e-6;
double a, b, c, delta;
double x1, x2;
a = in.nextDouble();
b = in.nextDouble();
c = in.nextDouble();
delta = bb-4.0ac;
if (Math.abs(delta) < eps) {
x1 = (-b)/(2.0
a);
System.out.printf(“The root is:%.2f.\n”, x1);
} else if (delta < 0) {
System.out.printf(“The equation has no real roots.\n”);
} else {
x1 = (-b+Math.sqrt(delta))/(2.0a);
x2 = (-b-Math.sqrt(delta))/(2.0
a);
System.out.printf(“The roots are %.2f and %.2f.\n”, x1, x2);
}
}
}

3.直角三角形类

创建一个直角三角形类(regular triangle)RTriangle类,实现下列接口IShape。两条直角边长作为RTriangle类的私有成员,类中包含参数为直角边的构造方法。 interface IShape {// 接口 // 抽象方法 求面积 public abstract double getArea(); // 抽象方法 求周长 public abstract double getPerimeter(); } 请编程从键盘输入两条直角边长值,创建一个直角三角形对象,然后输出直角三角形的面积和其周长。保留4位小数。
答案:
import java.util.Scanner;

interface IShape {
public abstract double getArea();
public abstract double getPerimeter();
}

class RTriangle implements IShape {
double a, b;
RTriangle(double a, double b) {
this.a = a; this.b =b;
}

public double getArea() {
    return a * b / 2;
}

public double getPerimeter() {
    return a + b + Math.sqrt(a * a + b * b);
}

}

public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double a, b;
a = in.nextDouble();
b = in.nextDouble();
RTriangle r = new RTriangle(a, b);
java.text.DecimalFormat df=new java.text.DecimalFormat(“0.####”);
System.out.println(df.format(r.getArea()));
System.out.println(df.format(r.getPerimeter()));
}
}

4.查找成绩并折算后输出

文件:期中考试成绩.txt中有若干学生的姓名和数学期中考试成绩。 Smith 67 Anderson 75 Lewis 83 Cook 58 David 96
请你编写一个简单的查询成绩程序,当从键盘输入一个姓名时查找到他的数学期中考试分数并按照21%折算后输出。
如果没找到则显示Not found. 由于目前的OJ系统暂时不能支持用户读入文件,我们编写程序从键盘输入文件中的姓名和成绩,
当输入的名字为noname时,表示结束。noname后面有一个名字,需要查找其成绩。
答案:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Map<String, Double> M = new HashMap<String, Double>();
String name;
double scroe;
while(in.hasNext()) {
name = in.next();//
if (name.equals(“noname”)) {
break;
}
scroe = in.nextDouble();
M.put(name, scroe);
}
name = in.next();
if (M.containsKey(name)) {
System.out.println(String.format("%.2f", M.get(name) * 0.21));
} else {
System.out.println(“Not found.”) ;
}
}
}

5.给定三角形的三边,求解三角形的面积

给定三角形的三边,求解三角形的面积。如果给定的三条边的数值不能为构成三角形,要给出It can not create a triangle.
答案:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        double a, b, c, t, area, p;
        a = in.nextDouble();
        b = in.nextDouble();
        c = in.nextDouble();
        if (a < b) {t = a; a = b; b = t;}
        if (a < c) {t = a; a = c; c = t;}
        p = (a + b + c) / 2.0;
        area = Math.sqrt(p * (p - a) * (p - b) * (p - c));
        if (b + c > a) {
            System.out.printf("The area is: %.3f.", area);
        } else {
            System.out.println("It can not be created a triangle.");
        }
    }
}

6.给定一个字符串,判定是否是数字

如果是数字就输出true , 不是数字就输出false.
答案:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s;
        s = in.next();
        boolean isNum = true;
        int PointNum = 0;
        for (int i=0; i<s.length(); i++) {
            if (s.charAt(i)=='.') PointNum++;
            else if (!('0'<=s.charAt(i) && s.charAt(i)<='9'))
                isNum = false;
        }
        if (PointNum > 1) isNum = false;
        System.out.println(isNum);
    }
}

7.找素数

请编写程序,从键盘输入两个整数m,n,找出等于或大于m的前n个素数。
答案:

import java.math.BigInteger;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        BigInteger m, n;
        m = in.nextBigInteger();
        n = in.nextBigInteger();
        for (BigInteger i = BigInteger.ONE; i.compareTo(n)<=0; i = i.add(BigInteger.ONE)) {
            while (true) {
                if (m.isProbablePrime(100)) {
                    System.out.println(m);
                    m = m.add(BigInteger.ONE);
                    break;
                }
                m = m.add(BigInteger.ONE);
            }
        }
    }
}

8. 找出一个给定字符串某个字符出现的次数

编写一个类,类中有如下的方法,找出一个在给定字符串的某个字符的出现的次数,
方法的声明如下: public static int count(String str, char a)
例如, count(“Welcome”, ‘e’) returns 2.
编写一个测试程序,特使用户输入字符串和一个字符,按照提示输出其出现的次数。 下面是输入和输出的样例,请严格按照输入输出格式进行。
答案:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s, t;
        int ans = 0;
        s = in.next();
        t = in.next();
        for (int i=0; i<s.length(); i++) {
            if (s.charAt(i) == t.charAt(0)) {
                ans++;
            }
        }
        System.out.printf("The number of occurrences is %d.\n", ans);
    }
}

9.求解给定两个字符串的后缀

给定两个字符串,求解给定字符串的后缀。按照如下的格式进行输出
答案:

import java.util.*;
import static java.lang.Integer.min;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s, t, ans="-";
        s = in.next();
        t = in.next();
        int lens = s.length();
        int lent = t.length();
        for (int i=0; i<min(lens, lent); i++) {
            int ps = lens - i - 1;
            int pt = lent - i - 1;
            if (s.substring(ps, lens).equals(t.substring(pt, lent))) {
                ans = s.substring(ps, lens);
            }
        }
        if (!ans.equals("-"))
            System.out.println("The common suffix is " + ans + ".");
        else
            System.out.println("No common suffix.");
    }
}

10.简单的计算器

编程实现一个简单的计算器,实现两个整数的加、减、乘、除。 注意:输入的数字为整数,可能大于Long.MAX_VALUE (即: 9223372036854775807)
答案:

import java.math.BigInteger;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s;
        BigInteger a, b, ans = BigInteger.ZERO;
        //a = in.nextBigInteger();
        s = in.next();
        //b = in.nextBigInteger();
        if ((s.indexOf('+') != -1)) {
            String[] ob = s.split("\\+", 0);
            a = new BigInteger(ob[0]);
            b = new BigInteger(ob[1]);
            ans = a.add(b);
        } else if ((s.indexOf('-') != -1)) {
            String[] ob = s.split("\\-", 0);
            a = new BigInteger(ob[0]);
            b = new BigInteger(ob[1]);
            ans = a.subtract(b);
        } else if ((s.indexOf('*') != -1)) {
            String[] ob = s.split("\\*", 0);
            a = new BigInteger(ob[0]);
            b = new BigInteger(ob[1]);
            ans = a.multiply(b);
        } else if ((s.indexOf('/') != -1)) {
            String[] ob = s.split("\\/", 0);
            a = new BigInteger(ob[0]);
            b = new BigInteger(ob[1]);
            ans = a.divide(b);
        }
        System.out.println(ans);
    }
}

11.编程实现一个简单的计算器,实现两个整数的加、减、乘、除

编程实现一个简单的计算器,实现两个整数的加、减、乘、除。 注意:输入的数字为整数,可能大于Long.MAX_VALUE (即: 9223372036854775807)

答案:

import java.math.BigInteger;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s;
        BigInteger a, b, ans = BigInteger.ZERO;
        //a = in.nextBigInteger();
        s = in.next();
        //b = in.nextBigInteger();
        if ((s.indexOf('+') != -1)) {
            String[] ob = s.split("\\+", 0);
            a = new BigInteger(ob[0]);
            b = new BigInteger(ob[1]);
            ans = a.add(b);
        } else if ((s.indexOf('-') != -1)) {
            String[] ob = s.split("\\-", 0);
            a = new BigInteger(ob[0]);
            b = new BigInteger(ob[1]);
            ans = a.subtract(b);
        } else if ((s.indexOf('*') != -1)) {
            String[] ob = s.split("\\*", 0);
            a = new BigInteger(ob[0]);
            b = new BigInteger(ob[1]);
            ans = a.multiply(b);
        } else if ((s.indexOf('/') != -1)) {
            String[] ob = s.split("\\/", 0);
            a = new BigInteger(ob[0]);
            b = new BigInteger(ob[1]);
            ans = a.divide(b);
        }
        System.out.println(ans);
    }
}
原创文章 159 获赞 4 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44769592/article/details/103826335