我目前正在处理一个项目,在该项目中,我需要获取用户输入,然后使用该输入计算三角形的质心。三角形的长度来自用户的输入。由于某些原因,公式不接受用户输入。
import java.util.Scanner;
public class Centroid {
public static void main(String[] args) {
// coordinate of the vertices
Scanner bucky = new Scanner(System.in);
System.out.println("Please enter variables for x1:");
String x1 = bucky.nextLine();
System.out.println("Please enter variables for x2:");
String x2 = bucky.nextLine();
System.out.println("Please enter variables for x3:");
String x3 = bucky.nextLine();
System.out.println("Please enter variables for y1:");
String y1 = bucky.nextLine();
System.out.println("Please enter variables for y2:");
String y2 = bucky.nextLine();
System.out.println("Please enter variables for y3:");
String y3 = bucky.nextLine();
// Formula to calculate centroid
float x = (x1 + x2 + x3) / 3;
float y = (y1 + y2 + y3) / 3;
System.out.println("Centroid = "
+ "(" + x + ", " + y + ")");
}
}发布于 2021-02-16 05:31:19
您使用字符串作为质心值,应使用浮点型、整型、双精度或短整型等数值变量,这就是公式不起作用的原因
尝试浮点变量
public class Centroid {
public static void main(String[] args) {
// coordinate of the vertices
Scanner bucky = new Scanner(System.in);
System.out.println("Please enter variables for x1:");
float x1 = bucky.nextFloat();
System.out.println("Please enter variables for x2:");
float x2 = bucky.nextFloat();
System.out.println("Please enter variables for x3:");
float x3 = bucky.nextFloat();
System.out.println("Please enter variables for y1:");
float y1 = bucky.nextFloat();
System.out.println("Please enter variables for y2:");
float y2 = bucky.nextFloat();
System.out.println("Please enter variables for y3:");
float y3 = bucky.nextFloat();
// Formula to calculate centroid
float x = (x1 + x2 + x3) / 3;
float y = (y1 + y2 + y3) / 3;
System.out.println("Centroid = "
+ "(" + x + ", " + y + ")");
}
} 发布于 2021-02-16 05:37:48
您正在尝试除以字符串的和解决方案是使变量( x1,x2,x3等)浮动;将:“strings.The x1 = bucky.nextLine();”改为:"float x1= bucky.nextFloat();“。
public class Centroid{
public static void main(String[] args) {
// coordinate of the vertices
Scanner bucky = new Scanner(System.in);
System.out.println("Please enter variables for x1:");
float x1 = bucky.nextFloat();
System.out.println("Please enter variables for x2:");
float x2 = bucky.nextFloat();
System.out.println("Please enter variables for x3:");
float x3 = bucky.nextFloat();
System.out.println("Please enter variables for y1:");
float y1 = bucky.nextFloat();
System.out.println("Please enter variables for y2:");
float y2 = bucky.nextFloat();
System.out.println("Please enter variables for y3:");
float y3 = bucky.nextFloat();
// Formula to calculate centroid
float x = (x1 + x2 + x3)/ 3;
float y = (y1 + y2 + y3)/ 3;
System.out.println("Centroid = "
+ "(" + x + ", " + y + ")");
}
}https://stackoverflow.com/questions/66215182
复制相似问题