Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I have created a simple magic 8 ball program. But the issue is every single time I compile my program and run the loop the loop keeps on repeating the same random answer.

What I have tried:

Java
import java.util.Random;
import java.util.Scanner;
public class Moreloopex4 {

public Moreloopex4() {
	// TODO Auto-generated constructor stub
}

public static void main(String[] args) 
{
	// Declaring Random
	Random rand = new Random();
	
	// Declaring scanner
	Scanner scan = new Scanner(System.in);
	
	// Declaring variables
	String input;
	int randnum;
	
	
	// Declaring randomizer
	randnum = rand.nextInt(6)+0;
	
	// Conditional Statements
	while(true)
	{
		System.out.println("Enter your statement");
		input = scan.nextLine();
		if (randnum == 0)
		{
			System.out.println("Without a doubt ");
		}
		else if (randnum == 1)
	    {
	    	System.out.println("I cannot predict now");
	    }
		else if (randnum == 2)
	    {
	    	System.out.println("My sources say no");
	    }
		else if (randnum == 3)
	    {
	    	System.out.println("Signs point to yes");
	    }
		else  if (randnum == 4)
	    {
	    	System.out.println("Don't count on it");
	    }
		else if (randnum == 5)
	    {
	    	System.out.println("Better not tell you now");
	    }
		else if (randnum == 6)
	    {
	    	System.out.println("Yes, definetly");
	    }

	}
	    
	}
}
Posted
Updated 27-Apr-17 17:50pm
v2
Comments
[no name] 27-Apr-17 19:51pm    
Mostly because you never change the random number.

You should also add one
randnum = rand.nextInt(6)+0;
inside while(true) to get another random answer.
 
Share this answer
 
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.

Debugger - Wikipedia, the free encyclopedia[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900