有些难度的java编程题

有些难度的java编程题,第1张

 

 

StringBuilder 结合了字符数组和字符串的好些优点,所以实现大整数类的时候如果利用 StringBuilder 可以省掉不少功夫,比如:

import java.util.*

class SPBI {    // SimplePositiveBigInteger 的缩略

    public static void main(String[] args) {

        try {

            System.out.println("输入两个 30 位数以内的正整数和一个符号('+' 或 '*'):")

            Scanner scn = new Scanner(System.in)

            SPBI a = new SPBI(scn.nextLine().trim()),

          轮银       b = new SPBI(scn.nextLine().trim())

            String operator = scn.nextLine().trim()

            if (a.toString().length() >30 || b.toString().length() >30)

                throw new Exception("至少有一个整数超过 30 位数")

            if ( ! operator.matches("\\+|\\*"))

                throw new Exception("此程序不支持的符号:" + operator)

            System.out.println(

                    "\n\n" +

                    a.toStringWithDigitGrouping() + operator + "\n" +

                    b.toStringWithDigitGrouping() + "\n" +

                    "------------------------------ \n")

            if (operator.equals("+"))

                System.out.println(a.add(b).toStringWithDigitGrouping())

            else

                System.out.println(a.multiply(b).toStringWithDigitGrouping())

        } catch (Exception ex) {

            System.out.println("错误:" + ex.getMessage() + "。请重试。")

        }

    }

    // 此 SBPI 所代表的整数(注:个位数在左端)

    private StringBuilder reversedDigits

    // 唯一的构造器

    public SPBI(String spbi) {

        if ( ! spbi.matches("\\d+"))

            throw new IllegalArgumentException(spbi + " 不符合正整数格式")

        reversedDigits = new StringBuilder(spbi).reverse()

        normalize()

    }

    // 去掉这个 SPBI 中多腊禅宴余的前导零(全在 reversedDigits 的右端)

    private void normalize() {

        reversedDigits = new StringBuilder(reversedDigits.toString().replaceAll("(?<!^)0+$", ""))

    }

    public String toString() {

        return "" + new StringBuilder(reversedDigits).reverse()

    }

    // 除了在返回的字符串中加入了袭兄千位分组符外,跟 toString() 没差别

    public String toStringWithDigitGrouping() {

        return "" + new StringBuilder(reversedDigits.toString().replaceAll(".{3}(?!$)", "$0,")).reverse()

    }

    // 加法 *** 作(等于 this += that 然后返回 this)

    public SPBI add(SPBI that) {

        int maxLength = Math.max(reversedDigits.length(), that.reversedDigits.length())

        reversedDigits.setLength(maxLength)    // 可能造成 reversedDigits 的右端被填入 '\0'

        int carry = 0

        for (int i = 0i <reversedDigits.length()i++) {

            int digitOfThis = reversedDigits.charAt(i) != '\0' ? reversedDigits.charAt(i) - '0' : 0,

                digitOfThat = i <that.reversedDigits.length() ? that.reversedDigits.charAt(i) - '0' : 0,

                sum         = digitOfThis + digitOfThat + carry

            carry = sum >9 ? 1 : 0

            reversedDigits.setCharAt(i, (char) (sum % 10 + '0'))

        }

        reversedDigits.append(carry)

        normalize()

        return this

    }

    // 乘法 *** 作(等于 this *= that 然后返回 this)

    public SPBI multiply(SPBI that) {

        SPBI multiplesOfTenOfOriginalThis = new SPBI(toString())

        reversedDigits = new StringBuilder("0")    // this 归零

        for (int iThat = 0iThat <that.reversedDigits.length()iThat++) {

            for (int addCount = 0addCount <that.reversedDigits.charAt(iThat) - '0'addCount++)

                add(multiplesOfTenOfOriginalThis)

            multiplesOfTenOfOriginalThis.reversedDigits.insert(0, 0)    // 乘 10

        }

        return this

    }

}

 

 

 

import java.io.*

public class Test {

static String lineTmp

static String lineEle[]

static float a, b, c

static int indexOfEqual

String getInputName() {return getClass().getResource("input.txt").getPath()}

String getOutputName() {return getClass().getResource("input.txt").getPath().replace("input.txt", "result.txt")}

public static void main(String[] args) throws IOException {

Test test = new Test()

FileReader fr = new FileReader(test.getInputName())

BufferedReader br = new BufferedReader(fr)

FileOutputStream fo = new FileOutputStream(new File(test.getOutputName()))

while((lineTmp = br.readLine()) != null) {

lineEle = lineTmp.split(" ")

a = b = c = 0

for(int i = 0i <lineEle.length++i)

if(lineEle[i].equals("=")) indexOfEqual = i

try {

for(int i = 0i <lineEle.length++i) {

if(lineEle[i].contains("x^2")&&!lineEle[i].contains("+"))

a = Integer.parseInt(lineEle[i].substring(0, lineEle[i].indexOf('x')))

else if(lineEle[i].contains("x")&&!lineEle[i].contains("+"))

b = Integer.parseInt(lineEle[i].substring(0 ,lineEle[i].indexOf('x')))

else if(!lineEle[i].contains("=")&&!lineEle[i].contains("+")&&i<indexOfEqual)

c = Integer.parseInt(lineEle[i])

}

} catch (NumberFormatException e) {fo.write("error\r\n".getBytes())continue}

if(a == 0) {

if (b == 0 &&c != 0) fo.write("猜差芦x 没有实数根\r\n".getBytes())

else if (b == 0 &&c== 0) fo.write("R\r\n".getBytes())

else if (b != 0) fo.write(("一个实庆知根:x = " + (-c/b) + "\r\n"穗带).getBytes())

} else {

double tmp = Math.pow(b, 2) - 4 * a * c

if (tmp >0) fo.write(("两实根:x = " + ((-b + Math.sqrt(tmp))/(2 * a)) + ", " +

((-b - Math.sqrt(tmp))/(2 * a)) + "\r\n").getBytes())

else if (tmp == 0) fo.write(("一个实根:x = " + (-b/(2 * a)) + "\r\n").getBytes())

else {

String resultTmp = a >0 ? String.valueOf(Math.sqrt(-tmp)/(2 * a)) : String.valueOf(-Math.sqrt(-tmp)/(2 * a))

fo.write(("两个虚根:x = " + -b/(2 * a) + " + " + resultTmp + "i" + ", " +

-b/(2 * a) + " - " + resultTmp + "i"+ "\r\n").getBytes())

}

}

}

}

}

测试没有问题,输入在input.txt下,放在工程目录src文件夹中即可,输出到同目录下的result.txt中,上面的输入会得到如下输出:

两实根:x = -0.21922359359558485, -2.2807764064044154

两个虚根:x = 0.375 + 1.4523687548277813i, 0.375 - 1.4523687548277813i

R

一个实根:x = -0.75

x 没有实数根

error

不过不知道你是不是要求计算出来,还是写表达式?

/** 抽象类 */

public abstract class Area {

public double area()

}

/** 圆类继承抽象类Area */

public class RoundArea implements Area {

public RoundArea(double r){

this.r = r

}

double r//半径

public double area(){

return 3.14 * r

}

}

/** 矩形类继承嫌迹抽象类 */

public class RectArea implements Area {

double length

double width

public RectArea (double length,double width){

this.length = length

this.width = width

}

public double area(double length,double width){

return width * length

}

}

这是我自己手直接敲上去的代码,也没有测试过,可能出错。但是其中的原理都给你写清楚了。然后你蠢脊自带者渗己再定义ImpleArea类,写一个主函数,然后直接调用就行了。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12538582.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-26
下一篇 2023-05-26

发表评论

登录后才能评论

评论列表(0条)

保存