簡體   English   中英

我如何向用戶詢問字符串輸入? (如果他們想輸入中心和半徑,或直徑的端點?)(閱讀輸入)

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

// 這是驅動程序,有調用/使用的資源類

忽略這條線
忽略這條線 忽略這條線
忽略這條線

    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();  
          }
    // 

//我想要一種更好的方式來接受輸入並對其進行不同的決策和計算 } }

你顯然沒有展示你所有的這個類和其他類的代碼,因此下面的示例代碼基本上利用了你提供的......在某種程度上。 提示被分解並在特定的類方法中提供。 main()方法只調用另一個實際開始滾動的方法(可以這么說)。 這樣做是為了避免對靜力學的需要。

startApp()方法調用mainMenu()方法,該方法依次顯示此控制台應用程序的主菜單。 菜單包含在循環中以確保用戶完成正確的輸入。

從 Main Menu ()方法中選擇的選項作為整數值從mainMenu()方法返回,然后落入switch/case塊的控制,該塊又決定是提供中心和半徑(菜單項1 )還是將提供圓終點(菜單項2 )。

如果要提供中心和半徑,則調用getCenterAndRadius()方法,提示用戶提供中心值和半徑值。

如果要提供圓端點,則調用getCircleEndPoints()方法,該方法提示用戶提供所有四個值(x1、y1、x2、y2)以構成圓所需的兩個端點。

另一個名為getCenterAndRadius_2() 的方法也可用,它演示了另一種允許用戶提供端點值的方法。 使用最適合您的方法,或者根據代碼中給出的一些想法創建自己的方法。

在提供的代碼中使用了正則表達式 String#matches()String#split()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.
        */
    }
}

代碼中使用的正則表達式:

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

此處包含在此if條件的matches()方法中的"[12]"表達式基本上意味着:如果包含在選擇變量中的提供的字符串不是“1”或“2”,則輸入if代碼塊。


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

此處包含在此if條件的matches()方法中的"\\\\d+"表達式基本上意味着:如果包含在center變量中的提供的字符串不是一個或多個數字(0 到 9)的字符串表示,則輸入if代碼塊。

您可以在多個地方看到此表達式的使用。


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

此處包含在replaceAll()方法中的"[ ,]"表達式意味着替換endPoints字符串變量中包含的字符串中的所有空格 (" ") 和逗號 (,)。


endPoints.split("\\s+") 

這里包含在split()方法中的"\\\\s+"表達式意味着:根據一個或多個空格 (" ") 分隔符將endPoints變量中包含的字符串拆分為一個字符串數組


endPoints.split("\\s{0,},\\s{0,}")

split()方法中包含的"\\\\s{0,},\\\\s{0,}"表達式意味着:將包含在endPoints變量中的字符串基於逗號 (",") 分隔符拆分為字符串數組或任何逗號/空格組合分隔符(例如:“,”或“,”或“,”或“,”),而不管逗號兩側的空格數(如果有的話)。 它基本上涵蓋了逗號分隔符使用的所有基礎。


根據您的需要修改代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM