Beginner help with a do loop
Code :
import java.util.Scanner;
public class aritmetik {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int resultat, tal1, tal2;
System.out.print("Enter a digit: ");
tal1 = keyboard.nextInt();
System.out.print("Enter another digit: ");
tal2 = keyboard.nextInt();
System.out.println("How much is: " +tal1 + "+" +tal2 +"?");
resultat = keyboard.nextInt();
if(resultat == tal1 + tal2){
System.out.println("Your answer was right!");
}else{
System.out.println("Your answer was wrong.");
}
}
}
Hey,
I'm a total newbie to Java programming. Itīs a course i'm taking in the university. Itīs actually a lot of fun (when it works) not so fun when it doesn't:P
Anyway I've managed to program whats above, and it works fine. But I would like to tweak it a bit. I want to the program, say if you answer right: the program asks you if you would like to continue doing the same process again (but entering other digits) and if you answer wrong it will say: wrong answer, try again and let you enter the sum once more until you are right.
I have watched I think 5 different youtube-videos about loops. I think a Do loop would be the case for me. But I have no idea how to implement it. Could someone be helpful and show me a bit for starters so that I have something to go on with :)
Thanks!
Re: Beginner help with a do loop
Quote:
Do loop would be the case for me. But I have no idea how to implement it.
Look at the tutorial for how to code a do{}while loop:
The while and do-while Statements (The Java™ Tutorials > Learning the Java Language > Language Basics)
If you have problems coding it, post the code and and explanation of the problem.
Re: Beginner help with a do loop
Code :
import java.util.Scanner;
public class beraknaTal {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int resultat, tal1, tal2;
System.out.print("Ange ett heltal: ");
tal1 = keyboard.nextInt();
System.out.print("Ange ett till heltal: ");
tal2 = keyboard.nextInt();
do{
System.out.print("Vad blir: " +tal1 + "+" +tal2 +"?");
resultat = keyboard.nextInt();
}
while (resultat != tal1 + tal2);
System.out.println("Du svarade rätt");
}
}
Oh, it was not that hard. I have made it this far now, but I think it gets a bit tricky now. I would like the program to ask would you like to continue YES / NO. If YES go back to the beginning, if no say Ok (or something)?
How is that made =/
Re: Beginner help with a do loop
Put the code to be repeated inside the do{} while loop. Just before the end of the loop, ask the question and use the response to determine if to exit the loop or repeat the loop.
Re: Beginner help with a do loop
Basically you want to create a boolean variable and set it to false, then wrap your code in a do while loop...
(in pseudo-code)
Code java:
do {
do stuff here....
Do you want to continue doing stuff? Yes(true) or No(false)
} while(true)