Java – enter int in print

I'm trying to fix the script I wrote:

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

}

I tried to make x1, X2, Y1 and Y2 appear in it, but it doesn't allow me to - give y (a little) expectation... Whatever int is, what can I do to make it appear? (except that the program works well, I think...) thank you

Solution

Try this:

System.out.printf(
    "The length of the line between the points (%d,%d) and (%d,%d) is %f%n",x1,x2,y1,y2,distance);

The simplest solution to these situations is to use a formatted string, as shown in the code above View more details about syntax such as strings in documentation

In the code snippet above, each character after% means that the corresponding parameter in that position must be formatted accordingly (in left to right order after the string) especially:

>%d: This will be an integer The first four arguments are integers x1, Y2 >% F: this will be a decimal number The fifth parameter is double called distance >% n: this will be a platform specific newline character

The printf method is responsible for replacing each format character with the corresponding parameter value, and creating and printing the string as expected This is easier and less error prone than concatenating string parts with operators, spreading the required variables

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>