誰でも私が抱えている2つのJavaの問題を解決できますか。 1はtry catch 2はコードを置く場所

StackOverflow https://stackoverflow.com/questions/1633763

  •  06-07-2019
  •  | 
  •  

質問

私はuniの割り当てのために取り組んでいるコーディングの一部を持っています。実際、私はJavaにはそれほど向いていませんが、試しました。私は自分のtry catchを動作させようとしていますが、それがサポートすることをするようには見えません。私は例外が間違っていると思いますが、文字の入力と数字だけを停止しようとしているので、どの例外を問題に使用するのかわかりません。

私が抱えている最後の問題は、このコーディングをどこに置くべきかわからないことです:

 {
                   while (true)
        {
            cancel();
        }
 } 

どの部分に進むべきかわからない。

どのヘルプも大いに助かります。

これは私のコードです。少し面倒だとすみません。 コーディング

役に立ちましたか?

解決

あなたのコードは非常に冗長です-ほとんどのコメントは不要です(それらを含めるように促されるかもしれませんが)ので、代わりに:

minutesfromhours = 60*minutes;
                //To change the hours into minutes by diving the hour by 60 for departure.

次のように書くことができます:

public final static int MINUTES_PER_HOUR = 60;
//...

minutes = MINUTES_PER_HOUR * hours;

コードを整理すると、ロジックが見やすくなります。

他のヒント

IDEのデバッガーの使用方法を学ぶことをお勧めします。すばらしい無料のチュートリアルビデオがいくつかありますこちら

デバッガを使用すると、コード全体に println ステートメントを配置する必要がなくなります。

本当に時間がかかる。

あなたのtry / catchはおそらく動作しますします

 try
 {
    depart= Double.parseDouble(departtime);
    System.out.println(depart);
 }
 catch (NumberFormatException e)
 {
     System.out.println(e.getMessage());
 }
 System.out.println("Time accepted");

しかし、入力に関係なく 入力を処理するコードに落ちます。 catch ブロックでサブルーチンを終了し、 try ブロックで有効な入力を処理する必要があります。例:

try
 {
    depart= Double.parseDouble(departtime);
    System.out.println(depart);
    System.out.println("Time accepted");
    // do further processing here
 }
 catch (NumberFormatException e)
 {
     System.out.println(e.getMessage());
     // exit here
 }

ここに修正があります。真剣に、最初に私はあなたが働かないと思った。しかし、IDEでフォーマットし、cancel()メソッドを呼び出すメインメソッドを追加しました。うまくいきました。

import javax.swing.JOptionPane;

public class Time
{
   public int difference =0;
// Stores the difference of departure and arrival time.

   public static void main(String args [])
   {
       Time obj=new Time();

            while (true)

              obj.cancel();

   }

public Time()
    {
      String departtime = JOptionPane.showInputDialog("Enter Depart Time in 24 hour time:");
// Allows the user to input their departure time into a JOptionPane.
      String arrivaltime = JOptionPane.showInputDialog("Enter Arrival Time in 24 hour time:");
// Allows the user to input their arrival time into a JOptionPane.

      double depart = 0;
// Store the time the user first inputs as a double.
      double arrival = 0;
// Store the time the user inputs secondly as a double.

      int minutes = 0;
// To store the hours for departure.

      int minutes2 = 0;
// To store the minutes of departure.

      int totalminutesfordeparture = 0;
// To store the full time for departure as minutes.

      int minutesfromhours = 0;
// To store the hours as minutes for depature

     int arrivals = 0;
// To store the hours arrival.

     int arrival2 = 0;
// To store the minutes for arrival.

      int arrivalhoursasminutes = 0;
// To store the arrival hours as minutes.

      int totalminutesforarrival = 0;
// To store the full time for departure in minutes.

     int actualtimehours= 0;
// The number of hours it will take on the journey.

     int actualtimeminutes=0;
// The number of minutes it will take on the journey.






// **Start of removing the decimal for time 1 and time 2**\\
     {
         // Doesn't work
         try
         {
         depart= Double.parseDouble(departtime);
         System.out.println(depart);
         }
         catch (NumberFormatException e)
         {
             System.out.println(e.getMessage());
         }
         System.out.println("Time accepted");

         arrival= Double.parseDouble(arrivaltime);



         int time = (int)(depart*100);
            // Gets rid of the decimal point in the departure time.

         System.out.println ("Time with no decimal point "+ time);
             // Check the decimal is being removed.

         int time2=(int)(arrival*100);
             // Gets rid of the decimal point in arrival time.

         System.out.println ("Time with no decimal point "+ time2);
             // Check the decimal is being removed in arrival.

// **End of removing the decimal in the times**\\

// **Start of seperating the hours and minutes in departure time**\\
         {

             minutes2=time%100;
                 // To separate the minutes from the hours for departure.

            minutes=time/100;
                 // To seperate the hours ready to change them into minutes.

            System.out.println("Hours of departure "+ minutes);
                 // Check that the hours are seperating from the minutes for
                    // departure.

            System.out.println("Minutes of departure "+ minutes2);
                // Check that the minutes are seperating from the hour for
                // departure.

           arrival2=time2%100;
                 // To separate the minutes from the hours.

            arrivals=time2/100;
                 // To seperate the hours ready to change them into minutes.

            System.out.println("Hours of arrival "+ arrivals);
                // Check that the hours are seperating from the minutes for
                // arrivals.

            System.out.println("Minutes of arrival "+ arrival2);
                // Check that the minutes are seperating from the hour for
                // arrivals.
         }
// **End of seperating the hours and minutes in departure time**\\

// **Start of hours being changed to minutes and adding it all up**\\
         {
             minutesfromhours = 60*minutes;
                // To change the hours into minutes by diving the hour by 60 for
                // departure.

             System.out.println("Hours into minutes "+ minutesfromhours);
                // Checks that the hours are being turned into minutes for
                // departure.

             totalminutesfordeparture= minutesfromhours+minutes2;
                // To add together the hour minutes and the minutes from the
                // time to give the total time in minutes for departure.

             System.out.println("Total Departure time in minutes "+ totalminutesfordeparture);
                // Checks that the hours as minutes are being added up with the
                // minutes of the time for departure.


             arrivalhoursasminutes = 60*arrivals;
                // To change the hours into minutes for arrivals by diving the
                // hours by 60 for arrivals.

             System.out.println("Hours into minutes for arrival "+ arrivalhoursasminutes);
                // Check that it is adding up the hour minutes and the minutes
                // for departure.

             totalminutesforarrival= arrivalhoursasminutes+arrival2;
                // To add together the hour minutes and the minutes from the
                // arrivals.

             System.out.println("Total arrival time in minutes "+ totalminutesforarrival);
                // Check that it is adding up the hour minutes and the minutes
                // for arrivals
         }

// **End of hours being changed to minutes and adding up**\\

// **Start of Finding the difference in minutes**\\
         {

             difference=totalminutesforarrival-totalminutesfordeparture;
                // Works out the difference of minutes by taking arrival time in
                // minutes away from the departure time in minutes.
             System.out.println("Difference "+ difference);
                // Check to see that it is taking arrival from departure.

             JOptionPane.showMessageDialog(null, "It will take " + difference);
         }
            // **End of finding the difference in minutes**\\

         // **start of not working changing minutes back to hours.**\\

         {
             actualtimehours= difference/60;
             actualtimeminutes= difference/60;

             System.out.println("It will take "+ actualtimehours);
             System.out.println("It will take "+ actualtimeminutes);


         }

     }

    }

// ** Method incase cancel button is pressed **\\
        public void cancel()
    {
        String input=JOptionPane.showInputDialog("Cancel button was pressed");
        if (input==null)
        {
                System.exit(0);
        }
        }
}

一般的なコメント。

このコードのほとんどをTime()コンストラクターからメインメソッドに移動する必要があります。このコードは、時間オブジェクトのインスタンス化とは関係ありません。

whileループは、繰り返したいものすべてを囲む必要があります。この場合、出発時間、到着時間をユーザーに尋ね、差を計算します。

コードを複製しました。ユーザーに時間文字列を入力して解析するように要求するメソッドがないのはなぜですか。次のようなもの

public class Time {
    private int hours;
    private int minutes;
    etc...
}    

// in main
while (true) {
    Time departTime = askUser("depart");
    Time arriveTime = askUser("arrive");
    calculateDifference(departTime, arriveTime);
}

// elsewhere
public Time askUser(String name) {
    String theTime = JOptionPane.showInputDialog(
        String.format("Enter %s Time in 24 hour time:", name));
    Time result = parseTime(theTime, name);
    return result;
}

わかりました。今、少し眠り、早朝に、そして慎重に考えてから。)

まず、多くの重要なことをメソッドに入れて、コンストラクター領域を解放して、多くの人がそうするように言ったので、今何が起こっているかを見るのがはるかに簡単です。

try catch問題を解決するには。今朝、私はそれを間違った場所に置いていて、それが私がそれを試して欲しかったことを試していなかったことに気付きましたヒットすると終了します。終了する代わりにループバックする方法を見つける必要があります。

キャンセルボタンである他の問題を解決するために、while(true)ステートメントを使用し、キャンセルを押すことができる唯一の2つの場所であるJOptionPaneも配置しました...それが正しいかどうかを知っているので、誰かがそれが正しいかどうかを私に伝えることができれば(あるいは、それらの場所でコメントアウトすることをお勧めします)

これが動作中のコードです。ランダムな時間を入れることができるように、hh.mmに制限する方法を見つける必要があるなど、まだいくつかのバグがあります。現時点ではまったく処理されないため、00時間で24時間を処理する方法を試してみてください。また、-9またはそれがうまくいったもののいずれかに12.00と3.00を入れても気に入らない繰り返しになりますが、これは24時間の管理に関するものであり、最後に間違っているのは、エラーを起こした場合、今すぐ整理しようとしているループではなく、閉じることです。

コーディング

昨夜はみんな助けてくれてありがとう、みんな助けてくれた

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top