有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在输入q时退出循环

我正在创建一个循环java程序,它获取用户输入的两个点,并找到点之间的距离,当用户输入q时退出循环。现在我有了它,所以当输入q时退出,但现在我输入数字时出错

import java.util.Scanner;

public class Bonus1 {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        while(true) {
            System.out.print("Enter the x and y coordinates for point 1: ");
            String x1 = input.nextLine();

            if (quit(x1))
                break;

            double x1_d = Double.parseDouble(x1);
            String y1 = input.nextLine();

            if (quit(y1))
                break;

            double y1_d = Double.parseDouble(y1);

            System.out.print("Enter the x and y coordinates for point 2: ");
            String x2 = input.nextLine();

            if (quit(x2))
                break;

            double x2_d = Double.parseDouble(x2);

            String y2 = input.nextLine();
            if (quit(y2))
                break;

            double y2_d = Double.parseDouble(y2);
            double distance = Math.sqrt(((x2_d - x1_d) *
                                       (x2_d - x1_d) + 
                                       (y2_d - y1_d)*(y2_d - y1_d)));

            System.out.printf("The distance of the two points is: %.2f \n" , distance);
        } 
    } // main()

    public static boolean quit(String input) {
        return input.equalsIgnoreCase("q");
    }
} // Bonus1

共 (1) 个答案

  1. # 1 楼答案

    我认为你最好使用输入法。nextDouble()而不是输入。nextLine()以便您可以直接访问双变量,并确保这是一个java程序,p不能使用printf语句,并将其设置为print或println并检查语法