2017-10-09 12 views
0

이것이 첫 번째 질문입니다!자바 Do-while 스위치는 메뉴를 두 번 표시합니다.

내 do-while 메뉴 루프가 제대로 반복되지 않습니다.

사용자가 옵션 A 또는 B에 정보를 입력 한 후 반복 될 때마다 스위치의 기본 옵션이 인쇄됩니다 (X '종료'가 아닐 때). 기본 메뉴로 돌아가는 대신 기본 스위치가 인쇄됩니다 이 잘못된 입력을 수신하지만 입력이 주어지지 된 것처럼 너무

... 다른 메인 메뉴와 함께 때문이다

이 내 코드입니다!

import java.util.Scanner; 

public class Part3Final 
{ 

     static double rateM = 1.40; 
     static double rateC = 2.40; 
     static double rateLCV = 3.80; 
     static double rateHCV = 7.20; 

     static String M = "M"; 
     static String C= ("C"); 
     static String LCV ="LCV"; 
     static String HCV = ("HCV"); 

     static String Peak = "Peak"; 
     static String offPeak = "Off-Peak"; 
     static String Night = "Night" ;  

     public static void main(String[] args) 
     { 

     Scanner sc = new Scanner(System.in); 

     System.out.print("\nEnter Vehicle Type (M, C, LCV, HCV):"); 
     String vehicleType = sc.nextLine(); 

     if (vehicleType.equals(HCV)) 
      System.out.print("Enter Trip Time (Peak, Off-Peak or Night):"); 
      String tripTime = sc.nextLine();  

     String choiceEntry; 

     String tripDetails=""; 
     String tripList= ""; 

     int sectors; 

     // Adjusted rate calculation 
     double adjustedHCVNight = (7.2 - (rateHCV*0.3)); 
     double adjustedHCVPeak = ((rateHCV*0.4)+7.2); 
     // Variables to alter later 
     double adjustedSectorRate = 100; 
     double tripRate = 0; 
     double tripCharge= 0; 
     double totalCharge=0; 

     String breakList = ""; 
     String breakReport = ""; 

     double totalBreakCharge = 0; 

     //b char choiceEntryCh = '\0'; 

     do 
     { 
      System.out.println("\nToll Road Data Entry Menu"); 
      System.out.println("-----------------------------------------"); 
      System.out.println("\nA - First Option"); 
      System.out.println("B - Second Option"); 
      System.out.println("X - Exit"); 

      System.out.print("\nEnter your selection: "); 
      choiceEntry = sc.nextLine(); 
      choiceEntry = choiceEntry.toUpperCase(); 

      if (choiceEntry.length() != 1) 
       System.out.println("Response must be a single character!"); 
      else 

       switch (choiceEntry) 
       { 
       // equivalent of doing if (selection == 'A' || selection == 'a') 
        case "A": 
        case "a": 
        { 
        System.out.print("Enter Trip Date:"); 
        String tripDate = sc.nextLine(); 
        System.out.print("Enter Entry Point:"); 
        int entryPoint = sc.nextInt(); 
        System.out.print("Enter Exit Point:"); 
        int exitPoint = sc.nextInt(); 

        sectors= Math.abs(exitPoint-entryPoint); 

        if (tripTime.equals(Peak)) 
          tripRate=(adjustedHCVPeak);    
        if (tripTime.equals(Night)) 
          tripRate= (adjustedHCVNight) ; 
        if (tripTime.equals(offPeak)) 
          tripRate= (rateHCV); 

        if (vehicleType.equals(M)) 
          tripRate = rateM; 
        if (vehicleType.equals(C)) 
          tripRate = rateC; 
        if (vehicleType.equals(LCV)) 
          tripRate = rateLCV; 

        tripCharge= (tripRate * sectors); 

        tripDetails = String.format("%s %s %s %d %s %d %s %.2f %s %.2f %s", "- Trip on", tripDate, "from sector", entryPoint, "to sector", exitPoint, "at rate", tripRate, "(toll charge:", tripCharge,")"); 

        tripList= (tripList + "\n" + tripDetails); 

        totalCharge= (totalCharge + tripCharge); 
        } 
        break; 

        case "B": 
        case "b": 
        { 
        System.out.print("\nEnter Breakdown Incident Date:"); 
        String incidentDate = sc.nextLine(); 
        System.out.print("Enter sector breakdown occured in:"); 
        int breakdownPoint = sc.nextInt(); 
        System.out.print("Enter vehicle recovery cost:"); 
        double recoveryCost = sc.nextDouble(); 

        breakReport = String.format("%s %s %s %d %s %.2f %s", "- Breakdown on", incidentDate, "in sector", breakdownPoint, "(recovery cost:", recoveryCost,")"); 

        breakList= (breakList + "\n" + breakReport); 

        totalBreakCharge= (totalBreakCharge + recoveryCost); 

        } 
        break; 

        case "X": 
        case "x": 
        System.out.println("Exiting data entry menu..."); 
        break; 

        default: 
        System.out.println("Error - invalid selection!"); 
        break; 


        }  

      }while (!choiceEntry.equalsIgnoreCase("X")); 
      //if (choiceEntry.equals("X")) 
       //a System.out.println("Exiting data entry menu..."); 


     System.out.printf("\n%-70s %s\n", "Toll Charges:\n", tripList); 

     System.out.printf("\n%s %.2f %s", "(Toll charge total: $",totalCharge,")"); 

     System.out.printf("\n%-70s %s\n", "\nBreakdown Charges:\n", breakList); 

     System.out.printf("\n%s %.2f %s", "(Breakdown charge total: $",totalBreakCharge,")"); 

     double totalInvoice= (totalCharge + totalBreakCharge); 

     System.out.printf("\n%-70s %.2f\n", "\nToll Invoice Total", totalInvoice); 


     } 


     } 

이 인쇄가 발생한 경우 나는 굵게을 얻는다. HCV 입력 트립 시간 (피크, 오프 피크 또는 밤) : 밤

유료 도로 데이터 입력 메뉴

이 차량 종류 (M, C, LCV, HCV)를 입력 :오류입니다

A - 첫 번째 옵션 B - 두 번째 옵션 X - 종료

선택 입력 : 5 를 입력 종료 포인트 : 3

입력 진입 점, • 는 여행 날짜를 입력

유료 도로 데이터 입력 메뉴 A - 첫 번째 옵션 B - 두 번째 옵션 X - 종료 선택을 입력 : 응답은 단일 문자 여야합니다!

참고 응답이 없었다 INPUT

유료 도로 데이터 입력 메뉴

A - 첫 번째 옵션 B - 두 번째 옵션 X - 종료

선택을 입력하십시오 는 입력 여행 날짜 : 5/4/2017 진입 점 입력 : 5 종료 지점 입력 : 2

유료 도로 데이터 입력 메뉴 A - 첫 번째 옵션 B - 두 번째 옵션 X - 출구 선택 사항을 입력하십시오 : 응답은 한 문자 여야합니다!

참고 응답이 없었다 INPUT

유료 도로 데이터 입력 메뉴

A - 첫 번째 옵션 B - 두 번째 옵션 X - 종료

선택 사항을 입력 : X 종료 데이터 입력 메뉴 ...

통행료 : 5.04의 비율 섹터 3 섹터 5 내지 6

  • 트립 (수신자 요금 : 10.08)
  • 비율 5.04에서 섹터 2 섹터 5 내지 2017년 5월 4일에
  • 트립 (수신자 요금 : 15.12)

(총 유료 요금 : $ 25.20)

고장 요금 :

(고장 충전 총 : $ 0.00)

유료 송장 총 25.20

이런 일이 왜 누군가가 설명해 주시겠습니까!

감사합니다.

답변

0

sc.nextInt() 호출 후 sc.nextLine() 호출에 문제가있을 수 있습니다. sc.nextInt() 이후로는 \n 개행 문자를 사용하지 않으며 그 이유는 아마도보고있는 것입니다. 응답은 한 문자 여야합니다! 오류. 여기를 참조하십시오 : Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo()?

+0

Oh golly gumdrops! 귀하의 조언은 효과가있었습니다. 나는 너무 행복해. 도와 주셔서 대단히 감사합니다. – Molecule