2014-09-15 5 views
-1

Как преобразовать цикл do-while в цикл while?Как преобразовать цикл while в цикл while

int numAttempts = 0; 

do 
{ 
    System.out.println("Do you want to convert to Peso or Yen?"); 
    pesoOrYen = readKeyboard.nextLine(); 

    if(pesoOrYen.equalsIgnoreCase("Peso")||pesoOrYen.equalsIgnoreCase("Yen")) 
    { 
     notPesoOrYen = false; 
    } 
    else if (numAttempts < 2) 
    { 
     System.out.println("Sorry, but '"+pesoOrYen+"' is not a valid currency type. Try again:"); 
     notPesoOrYen = true; 
    } 

    numAttempts++; 

} while(notPesoOrYen==true && numAttempts < 3); 

Я пытался сделать while(notPesoOrYen==true && numAttempts < 3) то заявление, но это не сработало.

МОЙ ПОЛНЫЙ КОД

пакет CurrencyConverter;

импорт java.util.Scanner; import java.text.NumberFormat;

общественного класса CurrencyConverter {

public static void main(String[] args) 
{ 
    Scanner readKeyboard = new Scanner(System.in); 

    double doubleUsersCaptial; 
    boolean notPesoOrYen=true; 
    String pesoOrYen; 
    double usersConvertedCapital; 
    boolean userInputToRunProgramAgain=true; 

    final double US_DOLLAR_TO_PESO = 13.14; 
    final double US_DOLLAR_TO_YEN = 106.02; 


    do 
    { 

     System.out.println ("How much money in US dollars do you have?"); 
     String usersCaptial = readKeyboard.nextLine(); 
     doubleUsersCaptial = Double.parseDouble(usersCaptial); 

     int numAttempts = 0; 

     do 
     { 
      System.out.println ("Do you want to convert to Peso or Yen?"); 
      pesoOrYen  = readKeyboard.nextLine(); 



      if(pesoOrYen.equalsIgnoreCase("Peso")||pesoOrYen.equalsIgnoreCase("Yen")) 
      { 
       notPesoOrYen = false; 
      } 
      else if (numAttempts < 2) 
      { 
       System.out.println("Sorry, but '"+pesoOrYen+"' is not a valid currency type. Try again:"); 
       notPesoOrYen = true; 

      } 
     numAttempts++; 
     }while(notPesoOrYen==true && numAttempts < 3); 

     if(numAttempts==3) 
     { 
      System.out.println("Sorry, but '"+pesoOrYen+"' is not a valid currency type."); 
      System.out.println("You entered the wrong currency type too many times\nGood Bye"); 
      System.exit(0); 
     } 

     if (pesoOrYen.equalsIgnoreCase("Peso")) 
     { 
      usersConvertedCapital = doubleUsersCaptial*US_DOLLAR_TO_PESO; 
     } 
     else 
     { 
      usersConvertedCapital = doubleUsersCaptial*US_DOLLAR_TO_YEN; 
     } 


     NumberFormat formatter  = NumberFormat.getCurrencyInstance(); 
     String formatUsersCaptial = formatter.format(doubleUsersCaptial); 
     String formatUsersConvertedCapital = formatter.format(usersConvertedCapital); 


     System.out.println(formatUsersCaptial+"US Dollars = " 
          +formatUsersConvertedCapital+" "+pesoOrYen); 
     System.out.println("Would you like to run the Program Again?(enter 'yes' or 'no')"); 
     String runProgramAgain = readKeyboard.nextLine(); 


     if (runProgramAgain.equalsIgnoreCase("yes")) 
     { 
      userInputToRunProgramAgain = true; 
     } 
     else if (runProgramAgain.equalsIgnoreCase("no")) 
     { 
      System.out.println("Goood Bye"); 
      System.exit(0);  
     } 

     else 
     { 
      System.out.println ("You entered something other than 'yes' or 'no'\n" 
           +"Good Bye"); 
      System.exit(0); 
     } 
    }while (userInputToRunProgramAgain==true); 
} 

}

+0

Любая конкретная причина, почему вы пытаетесь переписать эту петлю по-другому? – Bruno

+2

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html начать здесь – maress

+0

@ Herman - знаете ли вы разницу между циклом 'while' и циклом' do/while'? – jww

ответ

0

while и do... while почти то же самое, do... while просто выполняет итерации перед оценкой в ​​первый раз условие выхода, тогда как while оценивает его даже для первая итерация (так что в конечном итоге тело петли while никогда не может быть reacher, тогда как тело do... while всегда будет выполняться хотя бы один раз).

Ваш фрагмент кода не является полным, но я думаю, вы не инициализировали notPesoOrYen до true перед циклом, и поэтому он не работает. Наконец, не пишите while(notPesoOrYen==true && numAttempts < 3), но while(notPesoOrYen && numAttempts < 3), сравнение == true не нужно.

+0

Я отредактировал для ввода моего полного кода –

+0

Я пробовал это, и он не позволял пользователю вводить другой тип валюты после запуска программы один раз –

+0

Ну, единственная разница между 'while' и' do while' - это первая итерация, поэтому, если на начало условия conitnuation истинно (это ваш случай), они строго эквивалентны. – Dici

0

Initialise вашу логическую переменную вне во время цикла:

int numAttempts = 0; 
boolean notPesoOrYen=true; 
while (notPesoOrYen && numAttempts < 3) { 
    System.out.println("Do you want to convert to Peso or Yen?"); 
    pesoOrYen = readKeyboard.nextLine(); 

    if (pesoOrYen.equalsIgnoreCase("Peso") || pesoOrYen.equalsIgnoreCase("Yen")) { 
     notPesoOrYen = false; 
    } else if (numAttempts < 2) { 
     System.out.println("Sorry, but '" + pesoOrYen + "' is not a valid currency type. Try again:"); 
     notPesoOrYen = true; 
    } 
    ++numAttempts; 
}; 
Смежные вопросы