0

カーペットに関するユーザー入力データを取得し、文字列を必要な情報に解析して、形状に基づいてカーペットオブジェクトを作成できるプログラムをコーディングしようとしています。私のコードは

    public class CarpetParser{

    public static Carpet parseStringToCarpet(String lineToParse)
    {
        String delims = "[/]";
        String[] info = lineToParse.split(delims);
        if(info[0].equalsIgnoreCase("rectangle")){
            double priceFor = Double.parseDouble(info[2]);
            int height = Integer.parseInt(info[3]);
            int width = Integer.parseInt(info[4]);
            RectangleCarpet theCarpet = new RectangleCarpet(info[1], priceFor, height, width);
            return theCarpet;

        }else if(info[0].equalsIgnoreCase("circle")){
            double priceFor = Double.parseDouble(info[2]);
            int radius = Integer.parseInt(info[3]);
            CircleCarpet theCarpet = new CircleCarpet(info[1], priceFor, radius);
            return theCarpet;

        }

    }
}

パーサーの場合、

    public abstract class Carpet{

    protected int area = 0;
    protected double unitPrice = 0;
    protected double totalPrice = 0.0;
    protected String carpetID;

    public Carpet(String ID, double thisPrice){
        carpetID = ID;
        unitPrice = thisPrice;
    }

    public String getCarpetId(){
        return carpetID;
    }

    public String toString(){
        String carpet = new String("\n" + "The CarpetId:\t\t" + getCarpetId() + "\nThe Area:\t\t" + area + "\nThe Unit Price\t\t" + unitPrice + "\nThe Total Price\t" + totalPrice + "\n\n");
        return carpet;
    }

    public abstract void computeTotalPrice();

}

カーペット用、

    public class RectangleCarpet extends Carpet{

    private int height;
    private int width;

    public RectangleCarpet(String ID, double priceOf, int h, int w){
        super(ID, priceOf);
        height = h;
        width = w;
        computeTotalPrice();
    }

    public void computeTotalPrice(){
        super.area = height * width;
        super.totalPrice = unitPrice * area;
    }

    public String toString(){
        String forThis = new String("\nThe Carpet Shape:\tRectangle\nThe Height:\t\t" + height + "\nThe Width:\t\t" + width +"\n");
        return forThis + super.toString();

    }

}

カーペットの形の1つと

    public class CircleCarpet extends Carpet{

    private int radius;

    public CircleCarpet(String ID, double priceOf, int rad){
        super(ID, priceOf);
        radius = rad;
        computeTotalPrice();

    }

    public void computeTotalPrice(){
        super.area = radius * radius * 3;
        super.totalPrice = area * unitPrice;
    }


    public String toString(){
        String forThis = new String("\nThe Carpet Shape:\tCircle\nThe radius:\t\t" + radius + "\n");
        return forThis + super.toString();
    }

}

他の形のために。問題はparseStringToCarpet、戻り値が欠落していることです。返そうとtheCarpetすると、タイプが間違っていると表示されるため、何を返す必要があるのか​​わかりません。

呼び出し元のクラスは

`import java.io.*;         //to use InputStreamReader and BufferedReader
import java.util.*;       //to use ArrayList

public class Menu
 {
  public static void main (String[] args)
   {
     char input1;
     String inputInfo = new String();
     String line = new String();
     boolean found;

     // ArrayList object is used to store carpet objects
     ArrayList carpetList = new ArrayList();

     try
      {
       printMenu();     // print out menu

       // create a BufferedReader object to read input from a keyboard
       InputStreamReader isr = new InputStreamReader (System.in);
       BufferedReader stdin = new BufferedReader (isr);

       do
        {
         System.out.println("What action would you like to perform?");
         line = stdin.readLine().trim();
         input1 = line.charAt(0);
         input1 = Character.toUpperCase(input1);

         if (line.length() == 1)
          {
           switch (input1)
            {
             case 'A':   //Add Carpet
               System.out.print("Please enter a carpet information to add:\n");
               inputInfo = stdin.readLine().trim();
               carpetList.add(CarpetParser.parseStringToCarpet(inputInfo));
               break;
             case 'C':   //Compute Total Price For Each Carpet
               for (int i=0; i<carpetList.size();i++)
                     ((Carpet) carpetList.get(i)).computeTotalPrice();
               System.out.print("total prices computed\n");
               break;
             case 'D':   //Search for Carpet
               System.out.print("Please enter a carpetID to search:\n");
               inputInfo = stdin.readLine().trim();
               found = false;
               for (int i=0; i<carpetList.size();i++)
                {
                 if (inputInfo.equals(((Carpet)carpetList.get(i)).getCarpetId()))
                  {
                   found = true;
                  }
                }
                if (found == true)
                 System.out.print("carpet found\n");
                else
                 System.out.print("carpet not found\n");
               break;
             case 'L':   //List Carpets
               if (carpetList.isEmpty())
                System.out.print("no carpet\n");
               else
                for (int i=0; i < carpetList.size(); i++)
                  System.out.print(carpetList.get(i).toString());
               break;
             case 'Q':   //Quit
               break;
             case '?':   //Display Menu
               printMenu();
               break;
             default:
               System.out.print("Unknown action\n");
               break;
            }
         }
        else
         {
           System.out.print("Unknown action\n");
          }
        } while (input1 != 'Q'); // stop the loop when Q is read
      }
     catch (IOException exception)
      {
        System.out.println("IO Exception");
      }
  }

  /** The method printMenu displays the menu to a use **/
  public static void printMenu()
   {
     System.out.print("Choice\t\tAction\n" +
                      "------\t\t------\n" +
                      "A\t\tAdd Carpet\n" +
                      "C\t\tCompute Total Price For Each Carpet\n" +
                      "D\t\tSearch for Carpet\n" +
                      "L\t\tList Carpets\n" +
                      "Q\t\tQuit\n" +
                      "?\t\tDisplay Help\n\n");
  }
}

`呼び出し元のクラスのコードを編集することは許可されていません。

4

3 に答える 3

0

戻り値を持つメソッドのすべてのパスに、return例外が含まれていることを常に確認する必要があります。この場合、次を追加できます。

 else {
            return null;
        }

メソッドの最後の部分に移動するparseStringToCarpetか、メソッドの最後に書き込みreturn nullます。

返される問題nullは、この関数を呼び出すメソッドが返される可能性があることを認識している必要があるnullため、文書化する必要があることです。

于 2013-02-01T15:41:25.760 に答える
0

最後にnullオブジェクトを返します。これは、if-else条件が満たされない場合に呼び出されますが、これを呼び出すときはnull以外のチェックを行うようにしてください。

パブリッククラスCarpetParser{

public static Carpet parseStringToCarpet(String lineToParse)
{
    String delims = "[/]";
    String[] info = lineToParse.split(delims);
    if(info[0].equalsIgnoreCase("rectangle")){
        double priceFor = Double.parseDouble(info[2]);
        int height = Integer.parseInt(info[3]);
        int width = Integer.parseInt(info[4]);
        RectangleCarpet theCarpet = new RectangleCarpet(info[1], priceFor, height, width);
        return theCarpet;

    }else if(info[0].equalsIgnoreCase("circle")){
        double priceFor = Double.parseDouble(info[2]);
        int radius = Integer.parseInt(info[3]);
        CircleCarpet theCarpet = new CircleCarpet(info[1], priceFor, radius);
        return theCarpet;

    }

    return null;
  }
于 2013-02-01T15:42:38.290 に答える
0

関数がを返すものとして宣言したCarpetので、クラスは(であっても)を返す必要があります。Carpetnull

info[0]がどちらcircleでもない場合rectangle、関数は何も返しません。

簡単な修正は、最後にを追加するかreturn null;、例外をスローする(つまり、create InvalidArgumentException)ことです。

2番目のケースでは、呼び出し元のクラスを編集して例外を処理するか、スタックのさらに上にスローする必要があります。

于 2013-02-01T15:43:19.693 に答える