|
|
Hello, I have created a do-while loop which is supposed to re-run if the user enters "y" or quit if the user enters "n".
It's about a number guessing game. The user must guess the computer's number and if he chooses to quit or if he guesses correctly, he's given the option to replay.The game is supposed to accept as many guesses are necessary until the number is found but when I run it I'm only able to enter one number. On the second attempt I get the error "Exception in thread "main" java.lang.NullPointerException
at Doloop2.main(Doloop2.java:60)"
Can someone help me out? I would appreciate any help.
I am posting my code hoping that it will make things clearer.
import java.util.*;
public class Doloop2
{
public static void main (String[] args)
{
final int MAX = 100;
int answer, guess, attempt = 0;
String replay = null;
Scanner scan = new Scanner (System.in);
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
System.out.print("I am thinking of a number "
+ "between 1 and 100. Enter your guess (0 to guit):");
guess = scan.nextInt();
do
{
if (guess > answer)
{
attempt++;
System.out.print ("Try a smaller number (0 to quit): ");
guess = scan.nextInt();
}
if (guess < answer)
{
attempt++;
System.out.print ("Try a bigger number (0 to quit): ");
guess = scan.nextInt();
}
if (guess == answer)
{
attempt++;
System.out.println ("You got it!");
System.out.println ("Number of total attempts:" + attempt);
System.out.println ();
System.out.print("Play again? (y/n)");
replay = scan.nextLine();
}
if (guess == 0)
{
System.out.println ("You ended the game. Play again? (y/n):");
replay = scan.nextLine();
}
}
while (replay.equals("y") || replay.equals("Y"));
}
}
modified on Wednesday, October 20, 2010 11:07 PM
|
|
|
|
|
Hey ur program had a couple of bugs after i removed the null pointer error. Fixed it
Code
-------------------------------------
import java.util.*;
public class Guess
{
public static void main (String[] args)
{
final int MAX = 100;
int answer, guess, attempt = 0;
String replay = "Y";
Scanner scan = new Scanner (System.in);
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
System.out.print("I am thinking of a number "
+ "between 1 and 100. Enter your guess (0 to guit):");
guess = scan.nextInt();
do
{
if(guess == 101){
answer = generator.nextInt(MAX) + 1;
System.out.print("I am thinking of a number "
+ "between 1 and 100. Enter your guess (0 to guit):");
guess = scan.nextInt();
}
if (guess == 0)
{
System.out.println ("You ended the game. Play again? (y/n):");
replay = scan.next();
guess = 101;
attempt = 0;
}
else{
if (guess > answer)
{
attempt++;
System.out.print ("Try a smaller number (0 to quit): ");
guess = scan.nextInt();
}
if (guess < answer)
{
attempt++;
System.out.print ("Try a bigger number (0 to quit): ");
guess = scan.nextInt();
}
}
if (guess == answer)
{
attempt++;
System.out.println ("You got it!");
System.out.println ("Number of total attempts:" + attempt);
System.out.println ();
System.out.print("Play again? (y/n)");
replay = scan.next();
guess = 101;
attempt = 0;
}
}while (replay.equals("y") || replay.equals("Y"));
}
}
|
|
|
|
|
1. Don't use 'txtspk'.
2. Do use <pre></pre> tags.
Just because questions don't look professional does not mean that answers should follow a similar pattern.
Just say 'NO' to evaluated arguments for diadic functions! Ash
|
|
|
|
|
Thanks. This works right but could you please explain the logic behind guess = 101 and guess == 101?
|
|
|
|
|
Go back to your basic documentation on assignments and expressions.
guess = 101;
is an assignment statement which sets the variable guess to the value 101.
guess == 101
is an expression which yields the boolean value TRUE if the variable guess contains the value 101, otherwise FALSE .
Just say 'NO' to evaluated arguments for diadic functions! Ash
|
|
|
|
|
Thanks for your response. I know about the assignment operator (=) and the boolean expression (==). My question should had been why "101"? What's the logic behind "101" in particular? What do we want to achieve by this number?
|
|
|
|
|
Hi guys,
I edited the code a little more yesterday. The logic behind "guess=101" are the following reasons.
1:When the user gives the correct answer or when the user chooses "0" to quit the variable has to be reset to some value, in this case i used "101" but now i ve made a small edit and changed it "guess = MAX+1", just to make the program a little more dynamic.
2:Also, i have included a condition saying if "guess = MAX+1" then the game restarts again prompting the user to guess a number.
Im pasting the edited code below for your reference. I believe now the program is bug clear. I have fun playing
import java.util.*;
public class Guess
{
public static void main (String[] args)
{
final int MAX = 100;
int answer, guess, attempt = 0;
String replay = "Y";
Scanner scan = new Scanner (System.in);
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
System.out.print("I am thinking of a number "
+ "between 1 and "+ MAX+". Enter your guess (0 to guit):");
guess = scan.nextInt();
do
{
if(guess == MAX + 1){
answer = generator.nextInt(MAX) + 1;
System.out.print("I am thinking of a number "
+ "between 1 and "+ MAX+". Enter your guess (0 to guit):");
guess = scan.nextInt();
}
if (guess == 0)
{
System.out.println ("You ended the game. Play again? (y/n):");
replay = scan.next();
guess = MAX + 1;
attempt = 0;
}
else{
if (guess > answer)
{
attempt++;
System.out.print ("Try a smaller number (0 to quit): ");
guess = scan.nextInt();
}
}
if (guess == 0)
{
System.out.println ("You ended the game. Play again? (y/n):");
replay = scan.next();
guess = MAX + 1;
attempt = 0;
}
else{
if (guess < answer)
{
attempt++;
System.out.print ("Try a bigger number (0 to quit): ");
guess = scan.nextInt();
}
}
if (guess == answer)
{
attempt++;
System.out.println ("You got it!");
System.out.println ("Number of total attempts:" + attempt);
System.out.println ();
System.out.print("Play again? (y/n)");
replay = scan.next();
guess = MAX + 1;
attempt = 0;
}
}while (replay.equals("y") || replay.equals("Y"));
System.out.println("\nThanks for playing - GUESS THE NUMBER");
}
}
|
|
|
|
|
I welcome your help and appreciate the work you invest. But i also think it isn't really good to edit the code completly and just throw it back.
This, and much more of the questions here are from students, trying to get behind "the secrets" of OOP. I'd rather like to explain the particular problem, than to post a complete solution.
regards
Torsten
I never finish anyth...
|
|
|
|
|
Hi,
I get your point, it will be more helpful if they understand and do it on their own. I will be more prudent next time.
|
|
|
|
|
Torsten makes a very valid point. I always think it is best at first to spend some time just watching the forums and looking at the answers posted by some of the regulars to see what the general protocol is. That way we can try and maintain a consistent way of responding to people. I know it can be confusing when you start (I made (and still make) plenty of mistakes) but it is time well spent.
Just say 'NO' to evaluated arguments for diadic functions! Ash
|
|
|
|
|
hi friends...
i am getting the following error while doing a program.....its a runtime error....can u please suggest a solution...also please tell me the reason for the same so that won't repeat the same next time also..
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at testThread.main(testThread.java:78)
My code is as following:
import java.io.*;
import java.lang.*;
import java.awt.*;
import java.awt.event.*;
class testThread extends Frame implements ActionListener,Runnable
{
int lower,upper;
Label l1=new Label("ODD");
Label l2=new Label("EVEN");
List lb1=new List();
List lb2=new List();
Button b2=new Button("EXIT");
void test(int low,int up)
{
lower = low;
upper = up;
setLayout(new FlowLayout());
setSize(700,700);
setTitle("Thread Demo");
setVisible(true);
add(l1);add(lb1);add(l2);add(lb2);add(b2);
b2.addActionListener(this);
Thread t=new Thread(this);
t.start();
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{ System.exit(0); }
}
);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b2)
System.exit(0);
}
public void run()
{
try
{
if((lower % 2) != 0)
{
lower = lower + 1;
}
while(lower <= upper)
{
Thread.sleep(1000);
lb2.add(String.valueOf(lower));
lower += 2;
Thread.sleep(500);
}
}catch(Exception e){}
}
public static void main(String[] args)
{
testThread obj=new testThread();
int lower,upper;
lower = Integer.parseInt(args[0]);
upper = Integer.parseInt(args[1]);
obj.test(lower,upper);
if((lower % 2) == 0)
{
lower = lower + 1;
}
try
{
while(lower <= upper)
{
Thread.sleep(1000);
obj.lb1.add(String.valueOf(lower));
lower = lower + 2;
Thread.sleep(500);
}
}
catch(Exception e){}
}
}
|
|
|
|
|
- do you use eclipse? it is able to debug and shows you where you get stuck.
Your code works here. be shure to give arguments to the programm - first int low, second int a high number. it does not validate, if the arguments are in right order.
regards
Torsten
I never finish anyth...
|
|
|
|
|
i am not using eclipse ..i want that to be run from command prompt...can u suggest a change in code that could rectify the error....
|
|
|
|
|
"ArrayIndexOutOfBoundsException" says, that you try to read a value that does not exist from an array.
"ArrayIndexOutOfBoundsException: 0" says the first value does not exist (computers and all creatures except mankind do intend to count from 0!).
The only array i can see in your code is the argument array the main-method needs. So you're probably not giving the arguments to your app.
Please use eclipse or netbeans. it will enhance your code and make it easier for you to program.
regards,
Torsten
I never finish anyth...
|
|
|
|
|
now its clear Torsten.....thanks for ur suggestion too....
|
|
|
|
|
hi....
Let me tell firstof all that i am a beginner in Java ,can anyone help me to understand the following piece of code...also to elaborate this class a bit so as to get an output...
class A
{
int a;
A()
{
this(10);
}
A(int x)
{
a=x;
}
}
|
|
|
|
|
Firstly, can you add <pre> tags around your code so that can be read easily.
What you have is class A that has one member variable a and two constructors.
The default constructor A() simply delegates to the constructor taking an argument A(int x) .
Example usages would be:
A a1 = new A();
A a2 = new A(10);
A a3 = new A(42);
Panic, Chaos, Destruction.
My work here is done.
or "Drink. Get drunk. Fall over." - P O'H
|
|
|
|
|
Thanks Vilmos....
But can u make the second line a bit more clear.....
ie:
"The default constructor A() simply delegates to the constructor taking an argument A(int x)."
|
|
|
|
|
A constructor can be called just like a function so the line in the default constructor below:
A()
{
this(10);
}
merely calls the constructor that takes an integer parameter and sets the member variable to the value 10. Take a look at The Java Tutorials[^] for more information.
Just say 'NO' to evaluated arguments for diadic functions! Ash
|
|
|
|
|
Thanks Richard...
Now its clear.....
|
|
|
|
|
class A
{
int a;
A()
{
this(10);
}
A(int x)
{
a=x;
}
public int somemethod(int value){
return (x*value);
}
Try to make your work easier by giving full classified names to objects, members and methods. and formate the code. make comments - feel free to express you.
regards,
Torsten
I never finish anyth...
|
|
|
|
|
Thanks,Torsten....
Its clear now....
|
|
|
|
|
Hello,
I have the following problem :
- I have a class My frame that extends JFrame and
also I have a class MyComponent that extends JComponent
- the MyComponent class overrides the paint method and displays a picture on a certain position
The problem is that when I call in the MyFrame constructor the methods (inherited from JFrame )
add(new MyComponent( ...position parameters 1.. ))
and also
add(new MyComponent( ...position parameters 2.. ))
only the last one is displayed (if I add more only the last one is drawn).
I spoke to someone and told me that I could be that the frame draws the components on different layers but didn't knew how to solve it ... .I've googled it and still nothing .
If someone had this issue please reply.
Thanks in advance!
|
|
|
|
|
In your overridden paint method, you need to repaint ALL the components not just the alst one added.
Panic, Chaos, Destruction.
My work here is done.
or "Drink. Get drunk. Fall over." - P O'H
|
|
|
|