Hi guys I'm writing a maths quiz program as a learning exercise and I cant get this 'response' variable to be recognised later in the method. Specifically the 'response' variable with *s either side of it does not link to the response variables declared earlier. I'm new to programming so fairly sure I'm making a basic error but I can't work it out and I'd be grateful if anyone can help me. Thanks!
import acm.util.*;
import acm.program.*;
public class MathsQuiz extends ConsoleProgram{
public void run(){
println("This program gives atudents a series of maths questions");
askQuestions();
}
private void askQuestions(){
for (int i = 0; i < NUMBER_OF_QS; i++){
askQ();
}
}
private void askQ(){
int answer = rgen.nextInt(0,20);
int number1 = rgen.nextInt(0,20);
int number2 = answer - number1;
if (number2 > 0){
int response = readInt("What is " + number1 + "+" + number2 + "?");
}else {
int response = readInt("What is " + number1 + " " + number2 + "?");
}
if (**response** == answer){
println("Correct!");
}else{
println("Incorrect");
}
}
private RandomGenerator rgen = RandomGenerator.getInstance();
int NUMBER_OF_QS = 5;
int RES = 0;
}
Move response to an outer scope:
int response;
if (number2 > 0) {
response = readInt("What is " + number1 + "+" + number2 + "?");
} else {
response = readInt("What is " + number1 + " " + number2 + "?");
}
Local variables have the most limited scope. Such a variable is
accessible only from the function or block in which it is declared.
The local variable's scope is from the line they are declared on until
the closing curly brace of the method or code block within which they
are declared.
You need to define response outside of the if statement:
int response = -1;
if (number2 > 0) {
response = /* ... Something ... */
} else {
response = /* ... Something else ... */
}
Just declare it before the if statement:
int response;
if (number2 > 0) {
response = ...
} else {
response = ...
}
Alternatively, spot the small amount of difference between the two blocks, and change just that using a conditional operator:
String separator = number2 > 0 ? "+" : " ";
int response = readInt("What is " + number1 + separator + number2 + "?");
its because you are creating the variable response inside of the if statement. try this instead
private void askQ(){
int answer = rgen.nextInt(0,20);
int number1 = rgen.nextInt(0,20);
int number2 = answer - number1;
int response; //to create the variable in the right scope
if (number2 > 0){
response = readInt("What is " + number1 + "+" + number2 + "?");
}else {
response = readInt("What is " + number1 + " " + number2 + "?");
}
if (**response** == answer){
println("Correct!");
}else{
println("Incorrect");
}
}
response is a local variable, and its accessibility is limited to inside the block in which it has been declared. So, response is accessible only within the if else block. IF you try to use response outside the area of scope, you will get a compile time error, until you don't redeclare it.
So, if you want to use response out of the if else block, you have to declare it out of the block as follows:
int response;
if (number2 > 0){
response = readInt("What is " + number1 + "+" + number2 + "?");
}else {
response = readInt("What is " + number1 + " " + number2 + "?");
}
Related
im not too sure how you add a loop statement to this. I want it to be a while loop that makes it do that the calculations repeat after finishing. I've tried but it just keeps on giving me errors. ive tried doing While statements but just will not work im not sure how you set it up as my teacher did not explain very well
import com.godtsoft.diyjava.DIYWindow;
public class Calculator extends DIYWindow {
public Calculator() {
// getting number one
double number1 = promptForDouble("Enter a number");
//getting number2
int number2 = promptForInt("Enter an integer");
//getting what to do with operation
print("What do you want to do with these numbers?\nAdd\tSubtract\tMultiply\tDivide");
String operation = input();
//declaring variable here so the same one can be used
double answer = 0;
switch(operation) {
case "add":
answer = number1 + number2;
print(number1 + " + " + number2 + " = " + answer);
break;
case "subtract":
answer = number1 - number2;
print(number1 + " - " + number2 + " = " + answer);
break;
case "multiply":
answer = number1 * number2;
print(number1 + " * " + number2 + " = " + answer);
break;
case "divide":
try {
answer = number1 / number2;
}
catch(ArithmeticException e) {
print("A number cannot be divided by 0.");
}
print(number1 + " / " + number2 + " = " + answer);
break;
}
double double1 = promptForDouble("Enter a number");
double double2 = promptForDouble("Enter another number");
double double3 = promptForDouble("Enter one last number");
print("What do you want to do with these numbers?\nAdd\tSubtrack\tMultiply\tDivide");
String operation2 = input();
double answer2 = 0;
switch(operation2) {
case "add":
answer2 = double1 + double2 + double3;
print(double1 + " + " + double2 + " + " + double3 + " = " + answer2);
break;
case "subtract":
answer2 = double1 - double2 - double3;
print(double1 + " - " + double2 + " - " + double3 + " = " + answer2);
break;
case "multiply":
answer2 = double1 * double2 * double3;
print(double1 + " * " + double2 + " * " + double3 + " = " + answer2);
break;
case "divide":
try {
answer2 = double1 / double2 / double3;
}
catch(ArithmeticException e) {
print("A number cannot be divided by 0.");
}
print(double1 + " / " + double2 + " / " + double3 + " = " + answer2);
break;
}
want it to loop after the code on top
}
private double promptForDouble(String prompt) {
double number1 = 0;
print(prompt);
String number = input();
try {
number1 = Double.parseDouble(number);
}
catch(NumberFormatException e){
print("That is not a number. Please enter a number.");
number1 = promptForDouble(prompt);
}
return number1;
}
private int promptForInt(String prompt) {
int number2 = 0;
print(prompt);
String number = input();
try {
number2 = Integer.parseInt(number); }
catch(NumberFormatException e) {
print("That is not an integer. Enter an integer.");
number2 = promptForInt(prompt); }
return number2;
}
public static void main(String[] args) {
new Calculator();
}
}
Put this in your main method:
while (true)
{
Thread.sleep(1000); // optional, make some deplay for more nature
new Calculator();
}
Or you can wrap all body blocks of the constructor inside the above while statement.
EDIT
So I didn't realize that the program was running, it was just blank, because java reads down, the system was waiting for me to input the answer before I saw the answer. Thank you #wdc for your help.
Original
I'm currently practicing java, I came into a problem that I solved, but I don't understand why, how come the program runs when I have it like this:
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int number1 = (int)(System.currentTimeMillis() % 10);
int number2 = (int)(System.currentTimeMillis() / 10 % 10);
System.out.print("What is " + number1 + " + " + number2 + "?");
int answer = in.nextInt();
System.out.println(number1 + " + " + number2 + " = " + answer + " is " + (number1 + number2 == answer));
}
}
But doesn't work when I have it like this:
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int number1 = (int)(System.currentTimeMillis() % 10);
int number2 = (int)(System.currentTimeMillis() / 10 % 10);
int answer = in.nextInt();
System.out.print("What is " + number1 + " + " + number2 + "?");
System.out.println(number1 + " + " + number2 + " = " + answer + " is " + (number1 + number2 == answer));
}
}
I want to know so I can avoid this problem in the future.
Thank you ahead of time.
If I understood your question correctly, you are not sure why is the output different in this two cases?
Note that java executes the statements in the order as they appear in the code. So,
When you put int answer = in.nextInt(); before the System.out.print("What is " + number1 + " + " + number2 + "?"); your program is waiting for user input and you don't see anything printed on the screen. If you enter something in the console and press enter, the program will continue it's execution and you would see the rest of the output.
But if you move int answer = in.nextInt(); after the print statement the first print statement will be executed and you would see some output in the console.
Well saying it doesn't work its not really correct, because it does.
The problem is in the seconde snippet you have the blocking method "in.nextInt()", before the console print of the question, so you need to put he answer and only after you have the question.
My program is not allowing me to enter user input if i do not enter a number and i want to go through the program again, it think its due to a hanging token somewhere but i cannot seem to find it.
import java.util.Scanner;
public class LessonTwo {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
char answer = ' ';
do {
System.out.print("Your favorite number: ");
if (userInput.hasNextInt()) {
int numberEntered = userInput.nextInt();
userInput.nextLine();
System.out.println("You entered " + numberEntered);
int numEnteredTimes2 = numberEntered + numberEntered;
System.out.println(numberEntered + " + " + numberEntered
+ " = " + numEnteredTimes2);
int numEnteredMinus2 = numberEntered - 2;
System.out.println(numberEntered + " - 2 " + " = "
+ numEnteredMinus2);
int numEnteredTimesSelf = numberEntered * numberEntered;
System.out.println(numberEntered + " * " + numberEntered
+ " = " + numEnteredTimesSelf);
double numEnteredDivide2 = (double) numberEntered / 2;
System.out.println(numberEntered + " / 2 " + " = "
+ numEnteredDivide2);
int numEnteredRemainder = numberEntered % 2;
System.out.println(numberEntered + " % 2 " + " = "
+ numEnteredRemainder);
numberEntered += 2; // *= /= %= Also work
numberEntered -= 2;
numberEntered++;
numberEntered--;
int numEnteredABS = Math.abs(numberEntered); // Returns the
int whichIsBigger = Math.max(5, 7);
int whichIsSmaller = Math.min(5, 7);
double numSqrt = Math.sqrt(5.23);
int numCeiling = (int) Math.ceil(5.23);
System.out.println("Ceiling: " + numCeiling);
int numFloor = (int) Math.floor(5.23);
System.out.println("Floor: " + numFloor);
int numRound = (int) Math.round(5.23);
System.out.println("Rounded: " + numRound);
int randomNumber = (int) (Math.random() * 10);
System.out.println("A random number " + randomNumber);
} else {
System.out.println("Sorry you must enter an integer");
}
System.out.print("Would you like to try again? ");
answer = userInput.next().charAt(0);
}while(Character.toUpperCase(answer) == 'Y');
System.exit(0);
}
}
Yes you are right you need to consume the characters first after the user inputted character in the nextInt before allowing the user to input data again
just add this in your else block and it will work:
else {
System.out.println("Sorry you must enter an integer");
userInput.nextLine(); //will consume the character that was inputted in the `nextInt`
}
EDIT:
change this:
answer = userInput.next().charAt(0);
to:
answer = userInput.nextLine().charAt(0);
With the given code I was given the directions: Java lets us use Methods/Functions so we can store procedures that we may use more than once, so I would like you to update your code where there is common tasks it can be done inside a method/function. Any idea how to do this?
package fifthAssignment;
public class Arithmetic {
public static void main(String[] args) {
// setting up the variable firstNumber and secondNumber
int length = args.length;
if (length != 3) {
System.out.println("Your suppose to enter an int, int then an operation sign like +,-,X or /.");
return;
}
int firstNumber = Integer.parseInt(args[0]);
int secondNumber = Integer.parseInt(args[1]);
int addition = firstNumber + secondNumber;
int minus = firstNumber - secondNumber;
int division = firstNumber / secondNumber;
int multiply = firstNumber * secondNumber;
String arithmetic = args[2];
if (arithmetic.equals("+")) {
System.out.println(args[0] + " " + args[2] + " " + args[1] + " = " + addition);
} else if (arithmetic.equals("-")) {
System.out.println(args[0] + " " + args[2] + " " + args[1] + " = " + minus);
} else if (arithmetic.equals("/")) {
System.out.println(args[0] + " " + args[2] + " " + args[1] + " = " + division);
// I could not use "*" operator as it was looking to pull down all
// the files associated with this program instead of
// using it the way I intended to use it. So in this case I changed
// the "*" to "x" so that I can get the solution you
// were looking for.
} else if (arithmetic.equals("x")) {
System.out.println(args[0] + " " + args[2] + " " + args[1] + " = " + multiply);
}
// following prints out to the console what the length of each argument
// is.
System.out.println(args[0] + " has the length of " + args[0].length());
System.out.println(args[1] + " has the length of " + args[1].length());
if (arithmetic.equals("+")) {
int total = String.valueOf(addition).length();
System.out.println(addition + " has the length of " + total);
}else if (arithmetic.equals("-")) {
int total = String.valueOf(minus).length();
System.out.println(minus + " has the length of " + total);
}else if (arithmetic.equals("/")) {
int total = String.valueOf(division).length();
System.out.println(division + " has the length of " + total);
} else if (arithmetic.equals("x")) {
int total = String.valueOf(multiply).length();
System.out.println(multiply + " has the length of " + total);
}
}
}
I'll provide a singular example, but you should do this on your own.
You have this in your code:
System.out.println(addition + " has the length of " + total);
Instead, you could potentially create a method that would work with two ints:
public void printStatus(int check, int length) {
System.out.println(check + " has the length of " + length);
}
Which would allow you to call
printStatus(addition, total);
This is just a rough example, but you can wrap a "process" of code in a method, and pass the necessary parameters needed to execute the method to it.
package fifthAssignment;
public class Arithmetic {
public static void main(String[] args) {
// setting up the variable firstNumber and secondNumber
int length = args.length;
if (length != 3) {
System.out.println("Your suppose to enter an int, int then an operation sign like +,-,X or /.");
return;
}
int firstNumber = Integer.parseInt(args[0]);
int secondNumber = Integer.parseInt(args[1]);
int addition = firstNumber + secondNumber;
int minus = firstNumber - secondNumber;
int division = firstNumber / secondNumber;
int multiply = firstNumber * secondNumber;
String arithmetic = args[2];
// following prints out to the console what the length of each argument
// is.
System.out.println(args[0] + " has the length of " + args[0].length());
System.out.println(args[1] + " has the length of " + args[1].length());
performOperation(arithmetic);
}
public void performOperation(String arithmetic) {
if (arithmetic.equals("+")) {
int total = String.valueOf(addition).length();
System.out.println(addition + " has the length of " + total);
} else if (arithmetic.equals("-")) {
int total = String.valueOf(minus).length();
System.out.println(minus + " has the length of " + total);
} else if (arithmetic.equals("/")) {
int total = String.valueOf(division).length();
System.out.println(division + " has the length of " + total);
} else if (arithmetic.equals("x")) {
int total = String.valueOf(multiply).length();
System.out.println(multiply + " has the length of " + total);
}
}
}
I'm a bit confused about how += assignment operator works. I know that x += 1 is x = x+1. However, in this code there is a string variable called 'String output' and initialized with an empty string. My confusion is that that there are 5 different outputs for the variable 'output' but I don't see where it's being stored. Help clarify my misunderstanding. I can't seem to figure it out.
import java.util.Scanner;
public class SubtractionQuiz {
public static void main(String[] args) {
final int NUMBER_OF_QUESTIONS = 5; //number of questions
int correctCount = 0; // Count the number of correct answer
int count = 0; // Count the number of questions
long startTime = System.currentTimeMillis();
String output = " "; // Output string is initially empty
Scanner input = new Scanner(System.in);
while (count < NUMBER_OF_QUESTIONS) {
// 1. Generate two random single-digit integers
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
// 2. if number1 < number2, swap number1 with number2
if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
// 3. Prompt the student to answer "What is number1 - number2?"
System.out.print(
"What is " + number1 + " - " + number2 + "? ");
int answer = input.nextInt();
// 4. Grade the answer and display the result
if (number1 - number2 == answer) {
System.out.println("You are correct!");
correctCount++; // Increase the correct answer count
}
else
System.out.println("Your answer is wrong.\n" + number1
+ " - " + number2 + " should be " + (number1 - number2));
// Increase the question count
count++;
output += "\n" + number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "
wrong");
}
long endTime = System.currentTimeMillis();
long testTime = endTime = startTime;
System.out.println("Correct count is " + correctCount +
"\nTest time is " + testTime / 1000 + " seconds\n" + output);
}
}
Answer given by Badshah is appreciable for your program and if you want to know more about operator' usability, jst check out this question i came across
+ operator for String in Java
The answers posted have very good reasoning of the operator
Its Add AND assignment operator.
It adds right operand to the left operand and assign the result to left operand.
In your case
output += someString // output becomes output content +somestring content.
`
Maybe the proper answer was written but if I understand your question correctly, you want some clarification instead of meaning of +=
Change the code;
// Increase the question count
count++;
output += "\n" + number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "wrong");
as this:
output += "\nCount: " + count + " and the others: " +
number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "wrong");
// Increase the question count
count++;
So you can see the line and the count together. Then increase as your wish.
In Java, Strings are immutable. So output += somethingNew makes something like this:
String temp = output;
output = temp + somethingNew;
At the end, it becomes something like concat/merge