我几乎完成了这个项目,涉及在Celsius,Fahrenheit和Kelvin之间转换,我最后需要的是找出克隆方法.任务是"clone,它不接受任何形式参数,并返回对新创建的Temperature对象的引用,该对象具有与其作为克隆的对象相同的值和比例".我的代码编译,但在客户端程序中运行时,我在Temperature.clone(Temperature.java:134)收到java.lang.StackOverflowError的错误
public class Temperature {
private double value;
private String scale;
public Temperature() { // default constructor
this.value = 0;
this.scale = "C";
}
public Temperature(double value, String scale) {
this.value = value;
this.scale = scale;
}
public double getValue() {
return this.value;
}
public String getScale() {
return this.scale;
}
public double getCelsius() {
if (scale.equalsIgnoreCase("C")) {
return this.value;
} else if (scale.equalsIgnoreCase("F")) {
double faren = ((this.value - 32) * (5 / …Run Code Online (Sandbox Code Playgroud) 以下问题来自我几周前的测验并且不正确,但没有提供答案:
请考虑以下代码,其中不包含编译错误:
Run Code Online (Sandbox Code Playgroud)String secret = "Ellie"; Scanner kb = new Scanner(System.in); System.out.println("Guess which name I'm thinking of:"); String guess = kb.next(); if (guess == secret) { System.out.println("Wow! You're smart!"); } else { System.out.println("Wrong!"); System.out.println("You guessed: " + guess); System.out.println("The correct answer was: " + secret); }假设用户在提示符处输入"Ellie".会产生什么输出,为什么输出而不是其他输出?
这是我错误的答案:
输出将是else语句"错误!" 因为字母'E'的大写.对此的解决方案是将String secret更改为"ellie"以及用户的猜测,或者可以将ignoreCase关键字写入String secret.
该程序实际输出"错误",我测试了它.
除了简单地知道答案之外,有人可以向我解释这个问题,以便我能更好地理解这个概念吗?
所以我在递归的最后一部分上遇到了一些麻烦.该方法需要使用递归来返回一个字符串,该字符串由"编织"在一起形成两个作为参数的字符串.例如:
weave("aaaa", "bbbb") // should return the string "abababab"
weave("hello", "world") // should return the string "hweolrllod"
weave("recurse", "NOW") // should return the string "rNeOcWurse"
Run Code Online (Sandbox Code Playgroud)
请注意,第一个字符串中的额外字符 - "urse"中的字符 - 在编织在一起的字符之后.
重要的(也是令人讨厌的)是我不允许使用任何迭代循环(for,while,do while).
这是我到目前为止的代码:
public static String weave(String str1, String str2)
{
String word = str1 + str2;
if(str1 == null || str1.equals("") || str2 == null || str2.equals(""))
{
return word;
}
String word1 = weave(str1.substring(0, str1.length() - 1), str2.substring(0, str2.length() - 1));
System.out.println(word1);
return word;
}
Run Code Online (Sandbox Code Playgroud)
对于(Hello,World),我的输出是:
HW
HeWo …Run Code Online (Sandbox Code Playgroud) 好的,所以我的程序编译并运行得很好,但目的是在摄氏,fahernheit和Kelvin之间进行转换,当程序与客户端一起运行时,它显示正确的单位(F,C,K),但给出的值为所有温度都为50.我该如何解决?
public class Temperature
{
private double value;
private String scale;
public Temperature() // default constructor
{
this.value = 0;
this.scale = "C";
}
public Temperature(double value, String scale)
{
this.value = value;
this.scale = scale;
}
public double getValue()
{
return this.value;
}
public String getScale()
{
return this.scale;
}
public double getCelsius()
{
if (scale.equalsIgnoreCase ("C"))
{
return this.value;
}
else if (scale.equalsIgnoreCase("F"))
{
double faren = ((this.value - 32) * (5/9));
return faren;
}
else
{
double …Run Code Online (Sandbox Code Playgroud)