我正在尝试修复我写的脚本:
import java.util.Scanner;
public class Line2
{
public static void main (String [] args)
{
Scanner scan = new Scanner (System.in);
System.out.println ("Please enter 4 integers");
int x1 = scan.nextInt();
int y1 = scan.nextInt();
int x2 = scan.nextInt ();
int y2 = scan.nextInt ();
double distance;
//Asking the user to insert coordinates of both points and setting double
// on distance in order to properly calculate the square root
distance = Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
System.out.print( "the length of the line between the points" (int x1, int x2) "and" (int y1, int y2) "is" distance);
//Telling the program to calculate the distance of two points given by user
}//end of method main
}
我正试图让x1
x2
y1
和y2
出现在里面,但它不允许我 - 给出Y(某种)预期的...... 。
无论int
是什么,我能做什么才能让它出现? (除了那个程序运行得很好,我认为..)
谢谢
答案 0 :(得分:6)
试试这个:
System.out.printf(
"The length of the line between the points (%d, %d) and (%d, %d) is %f%n",
x1, x2, y1, y2, distance);
这些情况最简单的解决方案是使用格式化字符串,如上面的代码所示。在documentation中查看字符串语法的更多详细信息。
在上面的代码片段中,%
后面的每个字符都表示必须相应地格式化该位置(字符串之后,从左到右的顺序)中的相应参数。特别是:
int
s x1, y1, x2, y2
double
distance
printf
方法负责用相应的参数值替换每个格式字符,按预期创建和打印String
。这比使用+
运算符连接字符串部分更简单,更不容易出错,并且散布了所需的变量。
答案 1 :(得分:1)
要打印多个值组合,您可以使用加法运算符将值的字符串表示附加在一起。
System.out.print("here is a point(" + x1 + ", " + x2 + " )");
答案 2 :(得分:0)
使用“+”连接字符串。
System.out.print("the length of the line between the points (int"
+ x1 + ", int " + x2 + ") and (int " + y1 + ", int " + y2 + ") is " + distance);
答案 3 :(得分:0)
要将整数与字符串组合,您可以执行以下操作:
x = 5;
y = 6;
System.out.println("This script exists to print the point ("+x+","+y+")");