我的作业有一个问题,我需要写一个代码,应该检查两个输入的数字,看看它们是腿还是斜边,然后使用勾股定理找到第三条边。
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String check1;
String check2;
String leg = "leg";
int first;
int second;
int leg2;
int leg1;
int hypo;
first = kb.nextInt();//check the first value
check1 = kb.next();
if (check1.equals(leg)){//check if it is a leg or hypotenuse
leg1 = first;}
else{hypo = first;};
second = kb.nextInt();
check2 = kb.next();
if (check2.equals(leg)){
leg2 = second;}
else{hypo = second;};
if (Objects.equals(check1, check2)){//if both are legs, then find a square of hypotenuse
int hyposq = (int)(leg1*leg1) + (int)(leg2*leg2);
(hypo*hypo) = hyposq;
System.out.println(hypo + " Hypotenuse");}//the value of hypotenuse
else{
int legsq = (int)(hypo*hypo) - (int)(leg1*leg1);
(leg2*leg2) =legsq;
System.out.println(leg2 + " leg");}}}
经过多次尝试使方法工作,重写和替换代码块,我终于能够修复许多编译错误,只留下这两个:
Solution.java:41: error: unexpected type
(hypo*hypo) = hyposq;
^
required: variable
found: value
Solution.java:47: error: unexpected type
(leg2*leg2) =legsq;
^
required: variable
found: value
我不知道如何解决这两个问题,谷歌也没有多大帮助。
在定义变量时请记住:
data_type variable_name = value;
VALUE应该放在等号的右边,数据类型和变量名应该放在左边。
既然,我假设,你正在试图找到斜边的值,我们可以做一些简单的代数:
如果hypo * hypo = hypq,则hypo = hypq的平方根:
hypo = (int)(Math.sqrt(hyposq))
同样适用于leg2
:
leg2 = (int)(Math.sqrt(leg2))
编辑:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String check1;
String check2;
int first;
int second;
int leg1 = 0;
int leg2 = 0;
int hypo = 0;
// System.out.println(leg1);
first = kb.nextInt();//check the first value
check1 = kb.next();
if (check1.equals("leg")){//check if it is a leg or hypotenuse
leg1 = first;
}
else{
hypo = first;
}
second = kb.nextInt();
check2 = kb.next();
if (check2.equals("leg")){
leg2 = second;
}
else{
hypo = second;
}
if (check1.equals(check2)){//if both are legs, then find a square of hypotenuse
int hyposq = (int)(leg1*leg1) + (int)(leg2*leg2);
hypo = (int)(Math.sqrt(hyposq));
System.out.println(hypo + " Hypotenuse");//the value of hypotenuse
}
else{ //if one leg is missing
int legsq;
if(leg2 == 0){ //if leg2 is the missing side (is still default value)
legsq = (int)(hypo*hypo) - (int)(leg1*leg1);
}
else{ //if leg1 is missing side (is still default value)
legsq = (int)(hypo*hypo) - (int)(leg2*leg2);
}
int lastLeg = (int)(Math.sqrt(legsq));
System.out.println(lastLeg);
}
}
}
基本上只是润色了你的代码并编辑了最后一部分。需要注意的一点是,你的代码将只接收和输出INTEGER值,所以如果你想让你的代码对double工作,基本上只要把它说int的地方改成double。
如果你需要任何进一步的帮助或澄清,请告诉我:)