表达评估员

时间:2016-09-09 04:24:36

标签: java indexof string-length

我必须编写一个程序来执行以下操作:

  

为x的任何值计算以下表达式,并将结果保存为double类型的变量。

     

接下来,确定未格式化结果中小数点左侧和右侧的位数。

     

[提示:您应该考虑使用静态方法Double.toString(result)将类型double结果转换为String并将其存储到String变量中。然后,在此String变量上,使用String类中的indexOf()方法查找句点的位置,并使用length()方法查找长度。知道小数点的位置和长度,你应该能够确定小数点每一边的位数。]

     

最后,应使用类java.text.DecimalFormat打印结果,以便在小数点右侧最多有四位数字,在小数点左侧,每组三位数用逗号分隔传统的方式。此外,小数点的每一边应至少有一位数字。

我知道我没有显示我必须为x计算的表达式,但我有一部分程序在运行。

我一直试图找出小数点两边的位数。

输出应如下所示:

  

输入x:1的值   结果:1.6528916502810695
  小数点左边的数字:1
  小数点右边的数字:16
  格式化结果:1.6529

我尝试使用indexOf()length()方法 我一直收到错误。

这是我的代码:

    import java.util.Scanner; 
    import java.text.DecimalFormat;

 public class ExpressionEvaluator 
 {
      public static void main (String[] args)
      { 
       Scanner userInput = new Scanner(System.in);
       double x,part1,part2,part3,part4,result;
       String value = "";


       System.out.print("Enter a value for x: ");
       x = userInput.nextDouble();

       part1 = (5 * Math.pow(x,7));
       part2 = (4 * Math.pow(x,6));
       part3 = (Math.pow((part1 - part2),2));
       part4 = (Math.sqrt(Math.abs(3 * Math.pow(x,5))));
       result = (Math.sqrt(part3 + part4));

       System.out.print("Result: " + result);

       value = Double.toString(result);
      }
   }

2 个答案:

答案 0 :(得分:1)

使用索引从零开始的事实。

以字符串1.6528916502810695为例。

.在哪里?在字符串的第二个位置,这是第一个索引。找到.需要左边多少个字符?只有一个。

因此,int left = value.indexOf(".");

这满足了问题陈述

  

使用String类中的indexOf()方法来查找句点的位置

现在,.右边有多少个字符?嗯,这只是字符串的全长 - (.及其左边的所有内容)。您已经计算了.

左侧有多少个字符

换句话说,int right = value.length() - (1 + left);

这涵盖了提示的其余部分

  

找到长度的length()方法。知道小数点的位置和长度,你应该能够确定小数点每一边的位数。

答案 1 :(得分:0)

您可以使用这些方法向右和向左获取小数位数。

import java.util.Scanner;    
import static java.lang.StrictMath.log10;

public class Main {
    public static void main(String[] args) {
        Scanner userInput = new Scanner(System.in);
        String x1;
        System.out.print("Enter a value for x: ");
        x1 = userInput.next();
        int length = x1.length();
        double x = Double.parseDouble(x1);
        System.out.println("Digits to the left of the decimal point:" + (int) Math.ceil(log10(x)));
        System.out.println("Digits to the right of the decimal point:" + (length - 1- (int) Math.ceil(log10(x))));
    }
}

测试

Enter a value for x: 123456.78
Digits to the left of the decimal point:6
Digits to the right of the decimal point:2