After writing 1 on scanner I want a random dice number generated and after pressing 1 again I want another random number generated but now I want it added with previous number. I want to make a loop, I want to keep pressing 1 and keep adding random numbers till I reach a certain number. Thank you.
import java.util.Random;
import java.util.Scanner;
public class dice {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int k=0; k<100;k ) {
Scanner scan =new Scanner(System.in);
int s = scan.nextInt();
System.out.println(s);
int previous = s;
if (s==1) {
Random ran = new Random();
int n = ran.nextInt(6) 1;
System.out.print(n);
int next;
while (true) {
next=scan.nextInt();
if (next==1) {
System.out.println(previous);
}
previous=n 10;
}
}
}
}}
CodePudding user response:
Define previous outside the for loop, and replace
int previous = s;
previous = n 10;
with
previous = s;
previous = n 10;
CodePudding user response:
Scanner sc=new Scanner(System.in);
int sum=0;
for(;;)
{
if(sc.nextInt()==1)
{
int num = (int)(Math.random()*6); // using the pre-defined random function in java.lang.Math class
System.out.println("Dice Value: " num);
sum =num; // shorthand adding the number for each iteration
}
//if(sum>100)
// break;
//if statement to check if value of sum is greater/lesser than a specific number
}
System.out.println("Final Answer: " sum)
Something like this might work (not yet tested): an infinite loop that can be terminated as per choice.
If you are looking for a way that the program works as soon as you physically press the '1' key on your keyboard, without having to press the enter key, something like a keyevent might work: https://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html
Please do let me know if there are any errors or doubts :)
