【发布时间】:2016-11-10 20:02:15
【问题描述】:
我是 java 新手,我被要求编写一个程序,使用三种不同的方法进行三种不同类型的计算。出于这个问题的目的,我将提供两个比较示例。对于我坚持的方法,必须适用以下规则:
- 必须测试 x("12 [ 3") 返回 null,因为 [ 不是有效的运算符。
-
必须使用以下参数编写:
Double x; /* * Chops up input on ' ' then decides whether to add or multiply. * If the string does not contain a valid format returns null. */ public Double x(String x){ return new Double(0); }
这是我目前所拥有的,以及另一个运行良好的计算示例:
TestCalculator 类
public class TestCalculator {
Double x;
String string = "b";
Double doubleObject = 1.0;
double doublePrimitive = 2;
public void testParsing() {
if (multiplyx(12.0) == 60) {
System.out.println("Multiplying Success");}
else {
System.out.println("Multiplying Fail");
}
if (x("12") == null) {
System.out.println("Ovalid operator Success");}
else {
System.out.println("Invalid operator Fail");
}
}
/*
* Chops up input on ' ' then decides whether to add or multiply.
* If the string does not contain a valid format returns null.
*/
public Double x(String x){
return new Double(x) + ("[ 3");
}
/*
* Multiplies the parameter x by instance variable x and return the value as a Double.
*/
public Double multiplyx(double x){
System.out.println("== Multiplying ==");
this.x = x;
return new Double(x * 5);
}
}
主类
public class Main {
public static void main(String[] args) {
TestCalculator call = new TestCalculator();
call.testParsing();
}
}
我的主要问题是:
- 如何让使用 String 作为参数的方法返回新的 Double 值?
- 既然任何东西都可以放入字符串中,只要它们在引号内,我会让 java 将“[”识别为无效运算符吗?
对于这些问题的任何帮助将不胜感激,谢谢。
【问题讨论】:
-
This: public Double x(String x) 已经获取字符串并返回双精度,所以我无法弄清楚你的第一个问题。请说清楚。关于你的第二个问题,你必须指定你接受的格式(我猜只有“x*y”和“x+y”,但我可能错了)。
-
对于我的第一个问题,我收到错误“字符串无法转换为 Double”,所以我认为我没有正确转换它或者我需要做一些事情。对于第二个问题,我认为这些是唯一可以接受的格式,但我认为我没有正确格式化代码以提供正确的输出,由于“[”是无效的运算符,因此输出将为空。
标签: java string type-conversion