我如何向用户询问字符串输入? (如果他们想输入中心和半径,或直径的端点?)(读取输入)

How do I ask the user for String inputs ? (if they want to enter center and radius, or endpoints of diameter?) (Read an input)

//这是驱动,还有资源类called/used

忽略此行
忽略这一行 ignorethislineofwriting
忽略此行

    import java.util.Scanner;
    public class KI23CriclesDriver
    {
       public static void main (String[] args)
       {
          //Declare Variables
          int x1, y1, x2, y2;
          String print;
          double center;
          double center2;
          String radius;
          int validLength = 1;
          int validLength2 = 2;

          //Instantiate Objects
          KI23GetC gc = new KI23GetC();
          KI23GetCircles gs = new KI23GetCircles();
          KI23PrintC p = new KI23PrintC();
          System.out.println("Do you want to enter (Option 1) center and radius or (Option 2) end points of diameter?");
          x1 = 0;
          y1 = 0;
          x2 = 0;
          y2 = 0;
          Scanner scanner = new Scanner(System.in);
          radius = scanner.nextLine();
          if( radius.length() == validLength )
          {
             System.out.println("Please enter the center and radius");
             x2 = gc.getX();
             y2 = gc.getY();
             x1 = gc.getX();
             y1 = gc.getY();
             center = gs.getCenter(x1, y1, x2, y2);
             center2 = gs.getCenter2(x1, y1, x2, y2);  
             p.print(x1, y1, x2, y2, center, center2);
          }

          if( radius.length() == validLength2) // doesnt work since validlength2 is the same as validlength
          {
             System.out.println("Please enter the end points of diameter");
             x1 = gc.getX();
             y1 = gc.getY();
             x2 = gc.getX();
             y2 = gc.getY();
             center = gs.getCenter(x1, y1, x2, y2);
             center2 = gs.getCenter2(x1, y1, x2, y2);  
             p.print(x1, y1, x2, y2, center, center2);

          }
          else
          {
             System.out.println("Please enter 1 or 2");
             x1 = 0;
             y1 = 0;
             x2 = 0;
             y2 = 0;
             radius = scanner.nextLine();  
          }
    // 

//我想要一种更好的方式来接受输入并据此做出不同的决定和计算 } }

您显然没有显示此代码和其他 classes 的所有代码,因此下面的示例代码在某种程度上基本上利用了您提供的内容。提示被分解并在特定的 class 方法中提供。 main() 方法只调用另一个实际开始滚动的方法(可以这么说)。这样做是为了避免需要静力学。

startApp() 方法调用 mainMenu() 方法,该方法依次显示此控制台应用程序的主菜单。菜单包含在一个循环中,以确保用户完成正确的输入。

从主菜单中选择的选项作为整数值从 mainMenu() 方法返回,然后落入 [=112 的控制=] 块依次确定是提供中心和半径(菜单项 1)还是圆终点(菜单项 2) 将被提供。

如果要提供中心和半径,则调用 getCenterAndRadius() 方法,提示用户提供中心值和半径值。

如果要提供圆端点,则调用 getCircleEndPoints() 方法,提示用户提供所有四个值(x1、y1、x2、y2)组成圆所需的两个端点。

另外一个名为 getCenterAndRadius_2() 的方法也可用,它演示了另一种允许用户提供端点值的方法。使用最适合您的方法,或者根据代码中给出的一些想法创建您自己的方法。

使用 Regular Expressions are used within the provided code. The String#matches(), String#split(), and the String#replaceAll() 方法利用这些正则表达式。

import java.util.Scanner;

public class KI23CriclesDriver {

    // KI23GetC gc = new KI23GetC();
    // KI23GetCircles gs = new KI23GetCircles();
    // KI23PrintC p = new KI23PrintC();

    private final Scanner userInput = new Scanner(System.in);
    private final String ls = System.lineSeparator();
    private int x1 = 0, y1 = 0, x2 = 0, y2 = 0;

    public static void main(String[] args) {
        // Done this way to avoid statics
        new KI23CriclesDriver().startApp(args);
    }

    private void startApp(String[] args) {
        int menuOption = mainMenu();
        switch (menuOption) {
            case 1:
                getCenterAndRadius();
                break;
            case 2:
                getCircleEndPoints();
                // getCircleEndPoints_2();
                break;
        }
    }

    private int mainMenu() {
        int menuChoice = 0;
        while (menuChoice == 0) {
            System.out.println("Supply a circle creation option:");
            System.out.println("  1) Based on Center and Radius." + ls
                             + "  2) Based on Diameter End Points.");
            System.out.print("Choice: --> ");
            String choice = userInput.nextLine().trim();
            if (choice.toLowerCase().startsWith("q")) {
                // Quit appplication
                System.exit(0);
            }
            if (!choice.matches("[12]")) {
                System.err.println("Invalid menu choice! Try again..." + ls);
                continue;
            }
            menuChoice = Integer.parseInt(choice);
        }
        return menuChoice;
    }

    private void getCenterAndRadius() {
        System.out.println("Please enter the Center and Radius:");
        String center = "", radius = "";
        // Center
        while (center.equals("")) {
            System.out.print("Center Value: --> ");
            center = userInput.nextLine();
            if (!center.matches("\d+")) {
                System.err.println("Invalid entry for CENTER! Try again...");
                center = "";
            }
        }
        // Radius
        while (radius.equals("")) {
            System.out.print("Radius Value: --> ");
            radius = userInput.nextLine();
            if (!radius.matches("\d+")) {
                System.err.println("Invalid entry for RADIUS! Try again...");
                radius = "";
            }
        }

        System.out.println(new StringBuffer("").append("Center = ").append(center)
                           .append("  |  Radius = ").append(radius));

        /* Do what you want here with the numerical values
           contained within the String variables center and 
           radius. 
        */
    }

    private void getCircleEndPoints() {
        System.out.println("Please enter the Circle End Points:");
        String xx1 = "", yy1 = "", xx2 = "", yy2 = "";
        // x1
        while (xx1.equals("")) {
            System.out.print("x1 Value: --> ");
            xx1 = userInput.nextLine();
            if (!xx1.matches("\d+")) {
                System.err.println("Invalid entry for x1! Try again...");
                xx1 = "";
            }
        }
        // y1
        while (yy1.equals("")) {
            System.out.print("y1 Value: --> ");
            yy1 = userInput.nextLine();
            if (!yy1.matches("\d+")) {
                System.err.println("Invalid entry for y1! Try again...");
                yy1 = "";
            }
        }
        // x2
        while (xx2.equals("")) {
            System.out.print("x2 Value: --> ");
            xx2 = userInput.nextLine();
            if (!xx2.matches("\d+")) {
                System.err.println("Invalid entry for x2! Try again...");
                xx2 = "";
            }
        }
        // y2
        while (yy2.equals("")) {
            System.out.print("y2 Value: --> ");
            yy2 = userInput.nextLine();
            if (!yy2.matches("\d+")) {
                System.err.println("Invalid entry for y2! Try again...");
                yy2 = "";
           }
        }

        System.out.println(new StringBuffer("").append("Circle End Points Suplied: (")
                           .append(xx1).append(",").append(yy1).append("), (")
                           .append(xx2).append(",").append(yy2).append(")"));

        /* Do what you want here with the numerical values
           contained within the String variables xx1, yy1, 
           xx2, and yy2.
        */
    }

    private void getCircleEndPoints_2() {
        System.out.println("Please enter the Circle End Points:" + ls
                         + "Example Entries: 50 50 65 72 or" + ls
                         + "                 50,50,65,72 or" + ls
                         + "                 50, 50, 65, 72");

        int xx1, yy1, xx2, yy2;
        String endPoints = "";
        while (endPoints.equals("")) {
            System.out.print("End Points: --> ");
            endPoints = userInput.nextLine();
            if (!endPoints.replaceAll("[ ,]","").matches("\d+") || 
                            endPoints.contains(",") ? endPoints.split("\s{0,},\s{0,}").length != 4 
                            : endPoints.split("\s+").length != 4) {
                System.err.println("Invalid End Points Entry! Try again...");
                endPoints = "";
            }
        }
        String[] points = endPoints.contains(",") ? 
                          endPoints.split("\s{0,},\s{0,}") : 
                          endPoints.split("\s+");
        xx1 = Integer.parseInt(points[0]);
        yy1 = Integer.parseInt(points[1]);
        xx2= Integer.parseInt(points[2]);
        yy2 = Integer.parseInt(points[3]);

        System.out.println(new StringBuffer("").append("Circle End Points Suplied: (")
                           .append(xx1).append(",").append(yy1).append("), (")
                           .append(xx2).append(",").append(yy2).append(")"));

        /* Do what you want here with the numerical values
           contained within the int type variables xx1, yy1, 
           xx2, and yy2.
        */
    }
}

Regular Expressions Used In Code:

if (!choice.matches("[12]")) {

matches() 条件的 matches() 方法中包含的 "[12]" 表达式基本上意味着:如果choice 变量中包含的提供的字符串是 not“1”或“2”,然后输入 if代码块。


if (!center.matches("\d+")) {

if 条件的 matches() 方法中包含的 "\d+" 表达式基本上意味着:如果center 变量中包含的提供的字符串是 而不是 一个或多个数字(0 到 9)的字符串表示,然后输入 if 代码块。

您可以在多处看到这个表达方式。


endPoints.replaceAll("[ ,]", "")

此处包含在 replaceAll() 方法中的 "[ ,]" 表达式表示替换 all 空格 (" ") 和逗号(,) 来自包含在 endPoints 字符串变量中的字符串。


endPoints.split("\s+") 

split() 方法中包含的 "\s+" 表达式表示:拆分包含在 endPoints 变量中的字符串基于一个或多个空格 (" ") 分隔符

的字符串数组
endPoints.split("\s{0,},\s{0,}")

split() 方法中包含的 "\s{0,},\s{0,}" 表达式表示:拆分包含在 endPoints 变量中的字符串基于逗号 (",") 分隔符或 any comma/whitespace 组合分隔符(例如:"," 或 ", " 或 " ," 或 " , " ) 不管逗号两边的空格数(如果有的话)。它基本上涵盖了逗号分隔符用法的所有基础。


根据需要修改代码。