use*_*619 3 java string formatting printf println
我正在尝试修复我写的脚本:
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
}
Run Code Online (Sandbox Code Playgroud)
我试图制作x1 x2 y1并y2出现在里面,但它不允许我 - 给Y(某种)预期......我能做什么才能使它出现,无论它int是什么?(除了那个程序运行得很好,我想..)谢谢
试试这个:
System.out.printf(
"The length of the line between the points (%d, %d) and (%d, %d) is %f%n",
x1, x2, y1, y2, distance);
Run Code Online (Sandbox Code Playgroud)
对于这些情况下,最简单的解决方案是使用一个格式化的字符串,如图上面的代码.请参阅文档中有关字符串等语法的更多详细信息.
在上面的代码片段中,a之后的每个字符%表示必须相应地格式化该位置中的相应参数(在字符串之后,从左到右的顺序).特别是:
intsx1, y1, x2, y2double调用的distance该printf方法负责用相应的参数值替换每个格式字符,String按预期创建和打印a .这比将字符串部分与+运算符连接起来更容易,更不容易出错,散布所需的变量.