I am writing a program (game) that teaches someone multiplication. In this program, random pair of numbers are to be generated and inserted into the question: "What is x * y = z?" If the person answers correctly, then the system will print out "Very Good!" If the person does not answer the question correctly, then the system will print out, "No. Please try again." (Which, in return, the program will continue to ask the question until the person answers the question correctly.) As the person answers the question correctly, a new method will generate another question for the person to answer.
My code is breaking at the variable "answer" and the if statement "(guess != answer)."
Here is my code:
public class Exercise_535 {
public class Multiply{
SecureRandom randomNumbers = new SecureRandom();
int answer;
}
public void Quiz() {
Scanner input = new Scanner(System.in);
int guess;
System.out.println("Enter your answer: ");
guess = input.nextInt();
while(guess != -1)
{
checkResponse(guess);
System.out.println("Enter your answer: ");
guess = input.nextInt();
}
}
public void createQuestion(){
SecureRandom randomNumbers = new SecureRandom();
int digit1 = randomNumbers.nextInt();
int digit2 = randomNumbers.nextInt();
answer = digit1 * digit2;
System.out.printf("How much is %d times %d\n", digit1, digit2);
}
public void checkResponse(){
if (guess != answer)
System.out.println("No. Please try again.");
else{
System.out.print("Very Good!");
createQuestion();
}
}
}
Is there anyone that is able to help, or at least point me in the correct direction?
Thanks.
It is important to understand the scope of variables. In java if you create a variable (where you say int guess or int answer) that variable only lives within whatever curly braces you put it in -> { }. So if you need that variable in another method, you need to pass it that variable in the parentheses. checkResponse() doesn't know what guess or answer are, because they aren't declared in that scope, and you don't pass them in at the start of the function (you could have checkResponse(int guess, int answer) and then pass those in when you call it, for example).
You have an inner class Multiply, is there a reason you created a class within a class? There are reasons to do that, but it doesn't seem like you have any reason to do that here.
Also I don't see a main function, which is the entry point to a Java program, and all other functions need to be called from there (so Main() could then call Quiz() in your case, which would then call your other two functions). Computers read programs one line at a time, and when you call a function/method (like Quiz()) it jumps to that part, and then returns when that function calls "return".
I know this is a lot of information, but it doesn't seem like you understand how Java programs flow. What are you using to study Java? If you are reading a book or doing a course, I recommend reviewing some of the earlier lessons, to understand the flow of the program better. It is difficult for people to answer your question because the way your code is set up doesn't have a logical flow (which is why it isn't working). Hope this helps a little.
Related
I just started learning how to program in Java a month ago. I am trying to make my robot (karel) put a beeper the amount of times that is indicated in the "put" integer only, not the total amount the object has. However, it is not a set number and karel.putBeeper(put); does not get accepted in the compiler due to the class not being applied to given types. Any help would be greatly appreciated, and I am starting to understand why Stack Overflow is a programmer's best friend lol. Note: I might not respond to to any helpful tips until tomorrow.
import java.io.*;
import java.util.*;
public class Lab09 {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.println("Which world?");
String filename = input.nextLine();
World.readWorld(filename);
World.setSize(10,10);
World.setSpeed(6);
Robot karel = new Robot(1,1,World.EAST,0);
int pick=0;
int put=0;
for(int i=0; i<8; i++) {
while(karel.onABeeper()) {
karel.pickBeeper();
pick++;
karel.move();
}
for(i=0; pick>i; pick--) {
put++;
}
if(!karel.onABeeper()) {
karel.move();
}
while(karel.onABeeper() && put>0) {
karel.putBeeper(put);
}
}
}
}
If I got your question right, you're trying to putBeeper put times, which is done by the following code:
while (karel.onABeeper() && put > 0) {
karel.putBeeper(put);
}
The issue I see here is that you're not changing the value of put after calls to putBeeper, hence this while loop will never terminate: for instance, if the value of put was 5 during the first loop iteration, it will always remain 5, which is larger than 0. Also, as you've mentioned, putBeeper doesn't take any arguments, hence trying to pass put as an argument won't work - the compiler catches that error for you.
If your intent is to call putBeeper put times then what you can do is decrement put after every invocation of putBeeper - put will eventually reach 0, at which point you've called putBeeper exactly put times. And since you're just learn to program in Java, I'll leave the actual implementation to you as an exercise. Good luck!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Hello please may someone run my code and assist me in debugging it. I'm having a lot of troubles trying to figure it out and i have not a lot of guidance when it comes to coding.
the problem with my code right now is that it runs certain parts twice. please annotate the issue and any
reccomendations to fix it. Thanks in advance
a brief of what i'm trying to do:
number guessing game
the idea is that the computer will generate a random number and will ask the user if they know the number
if the user gets the answer correct they will get a congrats message and then the game will end but if the user
enters a wrong number they get a try again message and then they will try again
import javax.swing.*;
import java.lang.*;
public class Main {
public static void main(String[] args) {
/*
number guessing game
the idea is that the computer will generate a random number and will ask the user if they know the number
if the user gets the answer correct they will get a congrats message and then the game will end but if the user
enters a wrong number they get a try again message and then they will try again
the problem with my code right now is that it runs certain parts twice. please annotate the issue and any
recomendations to fix it. Thanks in advance
*/
enterScreen();
if (enterScreen() == 0){
number();
userIn();
answer();
}
}
public static int enterScreen (){
String[] options = {"Ofcourse", "Not today"};
int front = JOptionPane.showOptionDialog(null,
"I'm thinking of a number between 0 and 100, can you guess what is is?",
"Welcome",
JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE,
null, options, "Yes" );
if(front == 0){
JOptionPane.showMessageDialog(null, "Goodluck then, you might need it. :D");
}
else {
JOptionPane.showMessageDialog(null, "okay i dont mind");
}
return front;
}
private static int number(){
double numD;
numD = (Math.random() * Math.random()) * 100;
int numI = (int) numD;
System.out.println(numD);
return numI;
}
private static int userIn(){
String userStr = JOptionPane.showInputDialog("What number do you think im thinking of?");
int user = Integer.parseInt(userStr);
return 0;
}
private static void answer(){
// here is the problem
if(userIn() == number()){
JOptionPane.showMessageDialog(null, "Well done! You must be a genius.");
}
else {
JOptionPane.showMessageDialog(null, "Shame, TRY AGAIN!");
userIn();
}
}
}
Your problem is this part:
enterScreen();
if (enterScreen() == 0) {
number();
userIn();
answer();
}
You can leave out the first enterScreen(). Because you call it again in the if statement. If you look at the return type of the method: public static int, it returns and int. This makes it so that the outcome of the method is directly available in the if statement. The fist enterScreen is basicly useless, because you dont use the result.
You could do this:
int num = enterscreen();
if (num == 0) {
number();
userIn();
answer();
}
Which is basicly the same as:
if (enterScreen() == 0) {
number();
userIn();
answer();
}
You call enterScreen() twice. Just call it once, and compare the value returned only once.
Also, StackOverflow typically is not for "Here's my code, fix it" kind of not questions.
https://stackoverflow.com/help/how-to-ask
You call enterScreen() and userIn() functions twice or more. Please Computer Science and coding. Hint: Computer's execute intructions from top to bottom.
This is my first UVa submission so I had a few problems in the way. The biggest hurdle that took my time so far was probably getting all the formats correctly (I know, shouldn't have been too hard but I kept getting runtime error without knowing what that actually meant in this context). I did finally get past that runtime error, but I still get "Wrong answer."
Listed below are the things I've done for this problem. I've been working on this for the last few hours, and I honestly thought about just dropping it altogether, but this will bother me so much, so this is my last hope.
Things I've done:
considered int overflow so changed to long at applicable places
got the whole list (1-1000000) in the beginning through memorization for computation time
submitted to uDebug. Critical input and Random input both show matching output.
submitted to to UVa online judge and got "Wrong Answer" with 0.13~0.15 runtime.
Things I'm not too sure about:
I think I read that UVa doesn't want its classes to be public. So I left mine as class Main instead of the usual public class Main. Someone from another place mentioned that it should be the latter. Not sure which one UVa online judge likes.
input. I used BufferedReader(new InputStreaReader (System.in)) for this. Also not sure if UVa online judge likes this.
I thought my algorithm was correct but because of "Wrong answer," I'm not so sure. If my code is hard to read, I'll try to describe what I did after the code.
Here is my code:
class Main {
public static int mainMethod(long i, int c, List<Integer> l) {
if (i==1)
return ++c;
else if (i%2==0) {
if (i<1000000&&l.get((int)i)!=null)
return l.get((int)i)+c;
else {
c++;
return mainMethod(i/2, c, l);
}
}
else {
if (i<1000000&&l.get((int)i)!=null)
return l.get((int)i)+c;
else {
c++;
return mainMethod(i*3+1, c, l);
}
}
}
public static int countMax(int x, int y, List<Integer> l) {
int max=0;
if (x>y) {
int temp = x;
x= y;
y = temp;
}
for (int i=x; i<=y; i++) {
if (l.get(i)>max)
max = l.get(i);
}
return max;
}
public static void main(String[] args) {
List<Integer> fixed = Arrays.asList(new Integer[1000000]);
for (long i=1; i<1000000; i++) {
fixed.set((int)i, mainMethod(i,0,fixed));
}
String s;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while ((s = br.readLine())!=null) {
int x = -1;
int y = -1;
for (String split : s.split("\\s+")) {
if (!split.equals("\\s+") && x==-1) {
x = Integer.parseInt(split);
} else if (!split.equals("\\s+") && x!=-1) {
y = Integer.parseInt(split);
}
}
if (x!=-1&&y!=-1)
System.out.println(Integer.toString(x) + " " + Integer.toString(y) + " " + Integer.toString(countMax(x,y,fixed)));
}
} catch (IOException e) {
} catch (NumberFormatException e) {
}
}
}
I apologize for generic names for methods and variables. mainMethod deals with memorization and creating the initial list. countMax deals with the input from the problem (15 20) and finding the max length using the list. The for loop within the main method deals with potential empty lines and too many spaces.
So my (if not so obvious) question is, what is wrong with my code? Again, this worked perfectly fine on uDebug's Random Input and Critical Input. For some reason, however, UVa online judge says that it's wrong. I'm just clueless as to where it is. I'm a student so I'm still learning. Thank you!
Haven't spotted your error yet, but a few things that may make it easier to spot.
First off:
int goes to 2^31, so declaring i in mainMethod to be long is unnecessary. It also states in the problem specification that no operation will overflow an int, doesn't it? Getting rid of the extraneous longs (and (int) casts) would make it easier to comprehend.
Second:
It's probably clearer to make your recursive call with c + 1 than ++c or doing c++ before it. Those have side effects, and it makes it harder to follow what you're doing (because if you're incrementing c, there must be a reason, right?) What you're writing is technically correct, but it's unidiomatic enough that it distracts.
Third:
So, am I missing something, or are you never actually setting any of the values in the List in your memoization function? If I'm not blind (which is a possibility) that would certainly keep it from passing as-is. Wait, no, definitely blind - you're doing it in the loop that calls it. With this sort of function, I'd expect it to mutate the List in the function. When you call it for i=1, you're computing i=4 (3 * 1 + 1) - you may as well save it.
We've been learning about methods in java (using netbeans) in class and I'm still a bit confused about using methods. One homework question basically asks to design a grade calculator using methods by prompting the user for a mark, the max mark possible, the weighting of that test and then producing a final score for that test.
eg. (35/50)*75% = overall mark
However, I am struggling to use methods and I was wondering if someone could point me in the right direction as to why my code below has some errors and doesn't run? I don't want any full answers because I would like to try and do it best on my own and not plagiarise. Any help would be greatly appreciated :)! (Also pls be nice because I am new to programming and I'm not very good)
Thanks!
import java.util.Scanner;
public class gradeCalc
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
scoreCalc();
System.out.print("Your score is" + scoreCalc());
}
public static double scoreCalc (int score1, int maxMark, double weighting, double finalScore)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter mark");
in.hasNextInt();
score1 = in.nextInt();
System.out.print("Enter Max mark");
in.hasNextInt();
maxMark = in.nextInt();
System.out.print("Enter weighting as a decimal (eg. 75% = 0.75)");
in.hasNextInt();
weighting = in.nextInt();
finalScore = (score1/maxMark)* weighting;
return finalScore;
}
}
You are calling your method scoreCalc() without passing the parameters you defined.
When you are calling it, it was defined as having 3 parameters.
scoreCalc(7, 10, 3.0, 8.0);
Also, when creating a class, start it with upper case, GradeCalc
As you can see scoreCalc method needs a set of parameters, but you call it without parameters.
The second: there is no need in Scanner in = new Scanner(System.in); into your main(String[] args) method. You are calling it into scoreCalc method.
Third: you are calling scoreCalc twice. The first call is before System.out.println, the second is into System.out.println. And your application will ask user twice to enter values.
store result value in a variable and show it later:
double result = scoreCalc(.... required params .....);
System.out.println("Your score is: " + result);
To start :
1) Follow coding conventions. (Class name should start with a capital letter).
2) In your context, you don't need Scanner in = new Scanner(System.in); in main() because you are not using it.
3) You are a calling the method scoreCalc() without parameters. Whereas, the method needs to be called with parameters.
4) A method,is a module. It as block of code which increases re-usability. So I suggest that accept the values from user in main() method and then pass them to the method for calculation.
A couple of things spring to mind:
You execute scoreCalc() twice. Probably you want to execute it once and save the result in a double variable like: double score = scoreCalc().
Speaking of scoreCalc(): Your definition takes 4 parameters that your don't have as input for that method. You should remove those from your method definition, and instead add score1, maxMark, weighting and finalScorevariable declarations in the method-body.
In your main function, you declare and instantiate a Scanner object you don't use.
Be careful with arithmetic that mixes int and double.
Some mistakes/errors to point out are:-
1) You do not need this statement Scanner in = new Scanner(System.in); in your main() , as you are not taking input from user through that function.
2) Your function scoreCalc (int score1, int maxMark, double weighting, double finalScore) takes parameters, for example its call should look like scoreCalc(15, 50, 1.5, 2.7), but you are calling it as scoreCalc(), that is without paramters from main().
Edit:- There is one more serious flaw in your program, which might work , but is not good coding. I wont provide code for it , and will leave implementation to you. Take input from user in the main() (using scanner) , assign the result to a temp variable there, and then pass that variable as parameter to the function scoreCalc()
//pseudocode in main()
Scanner in = new Scanner(System.in);
int score= in.nextInt();
.
.
.
scoreCalc(score,...);
Or you can make your scoreCalc function without parameters, and take user input in it (like present), and finally return just the result to main().
Both approaches seem appropriate and you are free to choose :)
As opposed to other answers I will start with one other thing.
You forgot about the most important method - and that is the Constructor.
You have to create a grade calculator, so you create a class(type) that represents objects of grade calculators. Using the Java convention this class should be named GradeCalculator, don't use abbreviations like Calc so that the name is not ambiguous.
So back to the constructor - You have not created your Calculator object. It may not be needed and you may achieve your goal not using it, but it's not a good practice.
So use this method as well - this way, you'll create actual Calculator object.
It can be achieved like that:
public static void main(String[] args)
{
GradeCalculator myCalculator = new GradeCalculator();
}
And now you can imagine you have your calculator in front of you. Whan can you do with it?
Getting a mark would be a good start - so, what you can do is:
myCalculator.getMark()
Now you'll have to define an method getMark():
private void getMark() { }
In which you would prompt the user for the input.
You can also do:
myCalculator.getMaxMark() { }
and that way get max mark (after defining a method).
The same way you can call method myCalculator.getWeighting(), myCalculator.calculateFinalResult(), myCalculator.printResult().
This way you'll have actual object with the following mehtods (things that it can do):
public GradeCalculator() { } //constructor
private void getMark() { } //prompts user for mark
private void getMaxMark() { } //prompts user for max mark
private void getWeighting() { } //prompts user for weighting factor
private void calculateFinalResult() // calculates the final result
private void printResult() // prints the result.
And that I would call creating a calculator using methods - and that I would grade highly.
Try to think of the classes you are creating as a real objects and create methods representing the behaviour that objects really have. The sooner you'll start to do that the better for you.
Writing whole code in one method is not a good practice and in bigger applications can lead to various problems. So even when doing small projects try to do them using best practices, so that you don't develop bad habbits.
Edit:
So that your whole program can look like this:
import java.util.Scanner;
public class GradeCalculator
{
//here you define instance fields. Those will be visible in all of your classes methods.
private Scanner userInput; //this is the userInput the calculator keypad if you will.
private int mark; //this is the mark the user will enter.
private int maxMark; //this is the mark the user will enter.
private int weightingFactor; //this is the weighting factor the user will enter.
private int result; //this is the result that will be calculated.
public static void main(final String args[])
{
Scanner userInput = new Scanner(System.in); //create the input(keypad).
GradeCalculator calculator = new GradeCalculator(userInput); //create the calculator providing it with an input(keypad)
calculator.getMark();
calculator.getMaxMark();
calculator.getWeightingFactor();
calculator.printResult();
}
private GradeCalculator(final Scanner userInput)
{
this.userInput = userInput; //from now the provided userInput will be this calculators userInput. 'this' means that it's this specific calculators field (defined above). Some other calculator may have some other input.
}
private void getMark() { } //here some work for you to do.
private void getMaxMark() { } //here some work for you to do.
private void getWeightingFactor() { } //here some work for you to do.
private void printResult() { } //here some work for you to do.
}
Please mind the fact that after constructing the Calculator object you don't have to use methods that are static.
Using loop I want to calculate the average of n numbers in Java and when user enters 0 the loop ends.
Here is the code that I have written:
public class start {
public static void main(String[] args) {
System.out.println("Enter an int value, the program exits if the input is 0");
Scanner input = new Scanner (System.in);
int h = 0;
while (input.nextInt() == 0){
int inp = input.nextInt();
int j = inp;
int i = 0;
h = j + i;
break;
}
System.out.println("The total is: "+ h);
}
}
Am I making any logical error?
Don't name the sum h, but sum.
The while-condition is wrong
Why do you use inp and j and i?
There is an unconditional break - why?
You talk about the average. Do you know what the average is?
Your output message is not about average - it is about the sum.
"Am I making any logical error?"
Yes. This looks like a homework problem so I won't spell it out for you, but think about what the value of i is, and what h = j + i means in this case.
You also need to be careful about calling input.nextInt(). What will happen when you call it twice each time through the loop (which is what you are doing)?
Homework, right?
Calling input.nextInt() in the while loop condition and also to fill in int inp means that each trip through the loop is reading two numbers (one of which is ignored). You need to figure out a way to only read one number per loop iteration and use it for both the == 0 comparison as well as for inp.
Additionally, you've done the right thing having h outside the while loop, but I think you're confusing yourself with j and i inside the loop. You might consider slightly more descriptive names--which will make your code much easier to reason about.
You need to keep a counter of how many numbers you read so you can divide the total by this number to get the average.
Edited the while loop:
while(true){
int e=input.nextInt();
if(e==0) break;
h+=e;
numberOfItems++;
}
Your original implementation called nextInt() twice, which has the effect of discarding every other number (which is definitely not what you intended to do).
Assuming that you asking the user only once, to enter and if the number if zero you simply want to display the average. you need a variable declared outside the while loop that will keep adding different numbers entered by the user, along with a second variable which track the number of cases entered by the user and keep incrementing itself by one till number is not zero as entered by the user. And as the user Enters 0, the loop will break and here our Average will be displayed.
import java.util.Scanner;
public class LoopAverage
{
public static void main(String[] args0)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Integer value : ");
int value = -1, sum = 0, count = 0;
while((value = scan.nextInt()) != 0)
{
count++;
sum = sum + value;
}
System.out.println("Average : " + (sum / count));
}
}
Hope that might help,
Regards
yes, oodles of logical errors.
your while loop condition is wrong, you're consuming the first value
you enter and unless that number is 0 you never enter the loop at all
i var has no purpose
you're breaking after one iteration
you're not calculating a running total
you're not incrementing a count for the average dividend
you're not calculating an average
This looks like you threw some code together and posted it. The most
glaring errors would have been found just by attempting to run it.
Some other things to consider:
Make sure to check for divide by 0
If you do an integer division, you might end up with an incorrect
average, as it will be rounded. Best to cast either the divisor or
dividend to a float
variable names should be helpful, get into the habit of using them
I recommend you to refer to the condition of "while" loop: if condition meets, what would the program do?
(If you know a little bit VB, what is the difference between do...until... and do...while...?)
Also, when you call scanner.nextInt(), what does the program do? For each input, how should you call it?
Last but not least, when should you use "break" or "continue"?
For the fundamentals, if you are in a course, recommend you to understand the notes. Or you can find some good books explaining details of Java. e.g. Thinking in Java
Enjoy learning Java.