Estoy creando código que tradujo una palabra (obtenida por el usuario) al Pig Latin. Mi código funciona realmente bien, excepto por una cosa. Quiero que el usuario escriba "y" o "n" para determinar si el código se ejecutará o no. Estoy usando un ciclo while para determinar qué ejecutar. Si un usuario escribe algo que no sean los dos mencionados anteriormente, quiero que vuelva a preguntar. Por el momento tengo un marcador de posición que llama al usuario tonto y reiniciar el código. ¿Cómo puedo lograr esto? Muchas gracias a todos!
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String playGame;
String word;
// Explains what the program does \\
System.out.println("Welcome to Coulter's Pig Latin Translator!");
System.out.println("If you choose to play, you will be asked to type a word which will be translated.");
System.out.println();
// Asks the user if they would like to play and checks 'y' or 'n' using a while statement \\
System.out.println("Would you like to play? [y/n]: ");
playGame = stdIn.next();
while(playGame.equals("y") || playGame.equals("n")) // While expression that will check if the user enters a 'y' or 'n'
{
if (playGame.equals("y")) // Executes if the user entered 'y'
{
System.out.println("Please enter the word that you would like to translate: ");
word = stdIn.next(); // Receives the word the user wishes to translate
System.out.println("_______________________________________________________");
System.out.println();
System.out.println("You entered the word: " + word); // Displays what the user entered
System.out.println();
System.out.println("Translation: " + solve(word)); // Displays the solved word
System.out.println();
System.out.println("Thanks for playing!"); //
return; // Ends the code
}
else if(playGame.contentEquals("n")) // Executes if the user entered 'n'
{
System.out.println("That's okay! Come back when you want to.");
return; // Ends the code
}
}
System.out.println("_______________________________________________________");
System.out.println("Don't be silly. Restart and type either 'y' or 'n'"); // Tells the user to restart if they entered anything but 'y' or 'n'
}
// Word translator code using a new static\\
public static String solve (String word)
{
String temp = word.toLowerCase();
char[] vowels = {'a', 'e', 'i', 'o', 'u'}; // Stores vowels in an array
char first = temp.charAt(0); // Defines first character for later use
for (int i = 0; i < vowels.length; i++) // Looks for first vowel to replace it
{
if (first == vowels[i])
{
return word + "way"; // Replaces checked vowel
}
}
word = word.substring(1); // Returns the string to the end of the word
word += first + "ay";
return word; // Returns the translated word to the program above
}
}
Bueno, estás pidiendo la entrada aquí:
playGame = stdIn.next();
Eso simplemente tiene que ir a tu ciclo entonces:
playOn = true;
while(playOn) {
playGame = stdIn.next();
if ( y ) { ... play
} else {
if ( n ) { ... dont play, set playOn = false
} else {
... ask again
}
}
Lo anterior solo sirve como inspiración, y para señalar: lo que realmente importa aquí es que obtienes tu cadena if / else, y los "bloques" correspondientes. ¡Necesita otro if / else completamente dentro del primer bloque "else"!
Dado que la parte de su código que desea que se repita es solo la pregunta inicial, eso es todo lo que debería estar en el bucle:
boolean askAgain = true;
while(askAgain) {
// print your prompt;
playGame = stdIn.next();
if (playGame.equals("y") || playGame.equals("n")) {
askAgain = false;
}
}
// Now do your if/elseif for which letter was retrieved.
Es una buena práctica recorrer solo partes del código que pueden repetirse.
Tengo el siguiente código tratando de convertir entre bytes y matrices de bits, de alguna manera no se está convirtiendo correctamente, ¿qué está mal y cómo corregirlo? Cadena getBitsFromBytes (byte [] Byte_Array) ...
Después de refactorizar algunos paquetes / clases, cuando intento comprometer mi proyecto me sale este error: org.tigris.subversion.javahl.ClientException: svn: Commit falló (los detalles siguen): svn: Item 'One-of-my- .. .
Estamos utilizando Spring versión 4.3.9 y utilizando RestTemplate para llamadas de descanso. Tenemos casos de prueba en los que intencionalmente tenemos contenido mal formateado cuando llamamos a un punto final particular (la solicitud en sí ...
Si tengo una clase auxiliar con métodos estáticos, ¿cómo puedo hacer mejor la inicialización? public class MyClass {// inicia un archivo de propiedades {properties.load (..)} public static String ...