我是一个Java新手,我试图让这段代码运行,但似乎总是给我带来错误。我也试过使用sum和其他函数。我做错了什么?
这里是我正在练习的问题-
求线的总长度之和。一条线被定义为数字线上的两个点A和B。例如,如果A= -3,B= 10,线的长度是13。这是因为数字线上的-3到10之间的距离是13个单位(10 -(-3) = 13)。同样地,如果A=9,B=5时,线的长度应该是4个单位,而数字线上的距离是4个单位(9-5= 4)。
输入-将有2行,每一行将有数字A&B整数分隔的空间。
输出-这应该返回由用户输入的2行的长度之和。
样本输入:
5 9
-10 3预期产出:
17说明:第一行代表第一行坐标,即A= 5,B= 9。第二线代表第二线坐标,即A= -10,B= 3。
第一行的长度= 4,第二线的长度是13,因此输出为17。
我的代码-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Source{
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] firstLineCoordinates = br.readLine().split(" ");
int a1 = Integer.parseInt(firstLineCoordinates[0]);
int b1 = Integer.parseInt(firstLineCoordinates[1]);
String[] secondLineCoordinates = br.readLine().split(" ");
int a2 = Integer.parseInt(secondLineCoordinates[0]);
int b2 = Integer.parseInt(secondLineCoordinates[1]);
Line firstLine = new Line(a1, b1);
Line secondLine = new Line(a2, b2);
int totalSumOfLines = getTotalSumOfLines(firstLine, secondLine);
System.out.println(totalSumOfLines);
br.close();
}
private static int getTotalSumOfLines(Line firstLine, Line secondLine) {
int sum = totalSumOfLines;
return sum((b2 - a2) + (b1 - a1));
// ERROR IN THIS METHOD
}
public static class Line {
private int a;
private int b;
public Line(int a, int b) {
this.a = a;
this.b = b;
}
public int getA() {
return a;
}
public int getB() {
return b;
}
}
}编译时间错误-
Source.java:29: error: cannot find symbol
int sum = totalSumOfLines;
^
symbol: variable totalSumOfLines
location: class Source
Source.java:30: error: cannot find symbol
return sum((b2 - a2) + (b1 - a1));
^
symbol: variable b2
location: class Source
Source.java:30: error: cannot find symbol
return sum((b2 - a2) + (b1 - a1));
^
symbol: variable a2
location: class Source
Source.java:30: error: cannot find symbol
return sum((b2 - a2) + (b1 - a1));
^
symbol: variable b1
location: class Source
Source.java:30: error: cannot find symbol
return sum((b2 - a2) + (b1 - a1));
^
symbol: variable a1
location: class Source
5 errors发布于 2021-07-19 06:21:10
尝尝这个
private static int getTotalSumOfLines(Line firstLine, Line secondLine) {
int sum = 0;
if(firstLine.getA() > firstLine.getB())
sum = sum + (firstLine.getA() - firstLine.getB());
else
sum = sum + (firstLine.getB() - firstLine.getA());
if(SecondLine.getA() > secondLine.getB())
sum = sum + (SecondLine.getA() - secondLine.getB());
else
sum = sum + (secondLine.getB() - SecondLine.getA());
return sum;
}发布于 2021-07-25 14:24:32
私有静态int getTotalSumOfLines(Line firstLine,Line secondLine) {
// take this to getTotalSumOfLines
int sum1= Math.abs((firstLine.getA() - firstLine.getB()));
int sum2= Math.abs((secondLine.getA() - secondLine.getB()));
return sum1+sum2;}
https://stackoverflow.com/questions/68435623
复制相似问题