누구든지 내가 가진 2 개의 Java 문제를 도울 수 있습니까? 1은 Catch 2가 Catch 2를 넣을 위치입니다.

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

  •  06-07-2019
  •  | 
  •  

문제

나는 Uni에 대한 과제를 위해 노력하고있는 코딩 조각을 가지고 있으며 실제로 Java와 그다지 좋지는 않지만 시도했습니다. 나는 내 시도를 잡아려고 노력하고 있지만, 그것은 결코 서독하는 일을하지 않는 것 같습니다. 나는 예외가 잘못되었다고 생각하지만 문자를 입력하는 문자와 숫자 만 막으려 고 할 때 문제에 어떤 예외를 사용할 것인지 잘 모르겠습니다.

내가 가진 마지막 문제는이 코딩을 어디에 두어야하는지 모르겠다는 것입니다.

 {
                   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
 {
    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에서 포맷하고 컨트롤 () 메소드를 호출하는 기본 메소드를 추가했습니다. 그것은 효과가있었습니다.

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;
}

좋아, 나는 지금 그것을 알아 낸다 :) 약간의 수면과 이른 아침에 신중하게 생각한 후.

먼저 나는 많은 중요한 일을 방법에 넣었습니다. 많은 사람들이 저에게 말한 것처럼 내 생성자 영역을 풀어주었습니다. 예, 지금 무슨 일이 일어나고 있는지 알기가 훨씬 쉽다는 데 동의합니다.

시도 캐치 문제를 해결합니다. 나는 오늘 아침에 내가 잘못된 장소에 넣고 있다는 것을 깨달았고, 내가 시도하고 싶었던 것을 시도하지 않았고, 내가 시도하고 싶었던 메인 라인은 다른 코딩을 내부에 넣어야한다는 것을 의미했다. 이제 맞으면 끝납니다. 나는 결말 대신 다시 반복하는 방법을 찾아야합니다.

취소 버튼 인 다른 문제를 해결하기 위해 while (true) 문을 사용하고 Joptionpane이 어디에 있던 곳에 도착했을 때, 취소를 누를 수있는 유일한 장소였습니다. 하나는 옳기 때문에 누군가가 그것이 그것이 있는지 말해 줄 수 있다면 (또는 더 나은 곳에서 나는 그 장소에서 그것을 언급 할 것입니다)

그래서 여기에 작업 코드가 있습니다. 임의의 시간을 넣을 수있는 순간에 HH.mm으로 제한하는 방법을 찾아야하는 것처럼 여전히 몇 가지 버그가 있습니다. 또한 방법을 찾아야합니다. 현재 처리하지 않기 때문에 00 시간으로 24 시간을 다루고 있습니다. 12.00과 3.00을 -9로 올리거나 작동했던 것이 무엇이든간에 마음에 들지 않습니다. 다시 한 번 그것은 24 시간을 관리하는 것에 관한 것입니다. 그리고 그것이 잘못된 마지막 작은 것은 오류가 발생하면 지금 정리하려는 루프 대신 닫히게된다는 것입니다.

코딩

어젯밤에 여러분 모두가 도와 주셔서 감사합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top