Okay so for this code, I ask for someones favorite number, then ask them to pick a letter. The letter is assigned to a variable. For example, if the letter they choose is A (or lowercase A), add two to the original number, if the letter is m, the number gets multiplied by two, and if the letter is S, the number has 2 subtracted from it. However, i want to keep the loop going, and after one letter is applied, say A, and the number has 2 added on to it, i want that total to go through another loop. The problem is, I don't know how to get it to return the loop so that it may continue asking for the letters so it can continue adding, subtracting or multiplying.
For example, Favorite number is 4, i choose letter A and have 2 added on to A and the variable that held the number 4 now holds the number 6. Now it asks again, what letter should i choose, and i choose A again, and the variable is now 8, and i choose m and it multiplies by 2 to get 16 and so forth until a character besides A, S or M is chosen.
This is a question from an old java test i saw online. It didn't have the finished result, and i'm struggling trying to find an answer to this. I am a beginner java programmer trying to learn from Youtube and i don't get complete explanations most of the time so bear with any mistakes in the code :/
import java.util.Scanner;
public class question2
{
public static void main(String[] args)
{
int Total;
char Letter;
Scanner keyboard = new Scanner(System.in);
System.out.println("Whats your favorite number");
Total = keyboard.nextInt();
System.out.println("Pick a letter from the following: A, S, M");
Letter = keyboard.next().charAt(0);
while (Letter == 'A'|| Letter == 'a'|| Letter == 's'|| Letter == 'S'||
Letter == 'm'|| Letter == 'M')
{
if(Letter == 'a'|| Letter == 'A')
{
Total = Total + 2;
System.out.println("2 added to your number is "+Total+".");
return;
}
if(Letter == 's'|| Letter == 'S')
{
Total = Total - 2;
System.out.println("2 subtracted from your number is
"+Total+".");
return;
}
if(Letter == 'm'|| Letter == 'M')
{
Total = Total - 2;
System.out.println("2 subtracted from your number is
"+Total+".");
return;
}
}
}
}
Aucun commentaire:
Enregistrer un commentaire