How do i assign a new value? - java

I need to find a way where the user can enter decimal numbers not only whole numbers for the division part and I also need help to fix the multiplication part, it keeps displaying the wrong answer when I intentionally wrote the wrong answer, for me it kept saying "the correct answer is 140" when the question was 5 x 2, and when I write 10 it says its correct but if its the same question and I write 4, for example, is says wrong the correct answer is 140 to the 5 x 2 question please help? here's my full code, and please if you find any more mistakes I did please let me know.
public static void main(String[] args) {
String name = JOptionPane.showInputDialog(null, "Please enter your name");
JOptionPane.showMessageDialog(null, "Hello " + name + "\nWelcome to your Math Quiz (no calculators allowed) \nPlease answer the following questions");
int randVal1 = (int) (20 * Math.random()) + 1;
int randVal2 = (int) (20 * Math.random()) + 1;
int randomNumberAdd = randVal1 + randVal2;
int randomNumberMul = randVal1 * randVal2;
int randomNumberDiv = randVal1 / randVal2;
int correct = 0;
for (int i = 1; i < 10; i++) {
String userAnswer = JOptionPane.showInputDialog(null, randVal1 + " + " + randVal2 + " = ");
int answer = parseInt(userAnswer);
if (answer == randVal1 + randVal2) {
JOptionPane.showMessageDialog(null, "Correct!");
correct++;
} else if (answer != randVal1 + randVal2) {
JOptionPane.showMessageDialog(null, "Incorrect!");
JOptionPane.showMessageDialog(null, "The correct answer is " + randomNumberAdd);
}
{
randVal1 = (int)(20* Math.random()) + 1;
randVal2 = (int)(20*Math.random()) + 1;
String userAnswerMul = JOptionPane.showInputDialog(null, randVal1 + " x " + randVal2 + " = " );
int answer2 = parseInt (userAnswerMul);
if (answer2 == randVal1 * randVal2){
JOptionPane.showMessageDialog(null, "Correct");
correct++;
} else if (answer2 != randVal1 * randVal2){
JOptionPane.showMessageDialog(null, "Incorrect");
JOptionPane.showMessageDialog(null, "The correct answer is " + randomNumberMul);
}
{
randVal1 = (int) (10 * Math.random()) + 1;
randVal2 = (int) (10 * Math.random()) + 1;
String userAnswerDiv = JOptionPane.showInputDialog(null, randVal1 + " รท " + randVal2 + " = ");
int answer3 = parseInt(userAnswerDiv);
if (answer3 == randVal1 / randVal2) {
JOptionPane.showMessageDialog(null, "Correct!");
correct++;
} else if (answer3 != randVal1 / randVal2) {
JOptionPane.showMessageDialog(null, "Wrong!");
JOptionPane.showMessageDialog(null, "The correct answer is " + randomNumberDiv);
}
{
}
}
}
}
JOptionPane.showMessageDialog(null, "You got " + correct + " correct answers.");
}
}

Related

After asking the user for how many questions they want, how can I get my code to show that number of random problems?

I need to first ask the user to input how many problems they want to do. Then generate the first, then the second after they answer the first and so on.
public static void main(String[] args) {
int number1 = (int) (Math.random() * 40 + 10), number2 = (int) (Math.random() * 40 + 10), uanswer, ianswer, counter, icounter,
acounter, counter1, ui, aacounter, bcounter;
Scanner input = new Scanner(System.in);
System.out.println("How many problems do you want to do?");
ui = input.nextInt();
counter = 1;
icounter = 1;
acounter = counter + icounter;
{
System.out.print("What is " + number1 + " + " + number2 + "? ");
}
uanswer = input.nextInt();
ianswer = number1 + number2;
while (counter < 10000 && icounter < 1000 && acounter < 1000 && number1
+ number2 != uanswer) {
System.out.println("Incorrect, the answer is "
+ ianswer + ", " + icounter + " out of " + icounter + " incorrect. Try again?");
icounter++;
acounter++;
uanswer = input.nextInt();
}
if (ianswer == ianswer) {
aacounter = acounter - 1;
bcounter = icounter - 1;
System.out.println("Correct, the answer is " + ianswer
+ ", " + counter + " out of " + aacounter + " correct, "
+ bcounter + " out of " + aacounter + " incorrect.");
}
}
With my current code, I only see one problem, even though I asked for 2 or more problems at the beginning.
You need to add a loop around this statement:
System.out.print("What is " + number1 + " + " + number2 + "? ");
like:
for(int i=0; i<ui; i++){
System.out.print("What is " + number1 + " + " + number2 + "? ");
...

How do i keep track of correct answers?

public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
System.out.println("Enter your name: ");
String firstname =Keyboard.nextLine();
System.out.println("Welcome "+ firstname+ "!"+ " Please answer the following questions:");
int x = (int)(20 * Math.random()) + 1;
int y = (int)(20 * Math.random()) + 1;
int sum = (x+y);
System.out.println(x + " + " + y + " = ");
String sInput = Keyboard.nextLine();
int answer1 = Integer.parseInt(sInput);
if (answer1 ==sum){
System.out.println("Correct!");
}else{
System.out.println("Wrong!");
}
System.out.println("The correct answer is " +sum);
I have no clue on how to keep track of the correct answers. I need something to keep track of when it prints correct. I don't know what to do though. I know I just need to record the corrects and divide by four. Four because thats how many questions I have in my quiz.
If you just need to keep track of how many right answers were provided, just add an int variable starting with 0 as a value and increment it. If you want to keep track of the questions and answers which were right, create an empty ArrayList and add a string every time a correct answer is provided.
Here an example of the second option:
ArrayList<String> correctAnswers = new ArrayList<String>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your name: ");
String firstname =keyboard.nextLine();
System.out.println("Welcome "+ firstname+ "!"+ " Please answer the following questions:");
for (int i=0;i<10;i++) {
int x = (int)(20 * Math.random()) + 1;
int y = (int)(20 * Math.random()) + 1;
int sum = (x+y);
System.out.println(x + " + " + y + " = ");
String sInput = keyboard.nextLine();
int answer1 = Integer.parseInt(sInput);
if (answer1 ==sum){
System.out.println("Correct!");
correctAnswers.add(x + " + " + y + " = " + sum);
}
else{
System.out.println("Wrong!");
System.out.println("The correct answer is " +sum);
}
}
System.out.println("Correct answers:");
for (String correctAnswer : correctAnswers) {
System.out.println(correctAnswer);
}
It asks 10 questions, keeps track of the right answers and outputs them after the 10th question.
An example for the first option:
int correctAnswers=0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your name: ");
String firstname =keyboard.nextLine();
System.out.println("Welcome "+ firstname+ "!"+ " Please answer the following questions:");
int totalAnswers=4;
for (int i=0;i<totalAnswers;i++) {
int x = (int)(20 * Math.random()) + 1;
int y = (int)(20 * Math.random()) + 1;
int sum = (x+y);
System.out.println(x + " + " + y + " = ");
String sInput = keyboard.nextLine();
int answer1 = Integer.parseInt(sInput);
if (answer1 ==sum){
System.out.println("Correct!");
correctAnswers++;
}
else{
System.out.println("Wrong!");
System.out.println("The correct answer is " +sum);
}
}
System.out.println("Correct answers: "+ correctAnswers + "("+correctAnswers*100/totalAnswers+"%)");

Hanging token from user input is not allowing me to proceed in my program

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);

Double Printing of Data

I am writing a program to print the area and perimeter of a rectangle when a user provides the length and width. The user is asked to input how many rectangles he/she wants and then I use a for loop to ask for the length and width, which loops based on the number of rectangles the user inputed.
It prints and works like I want it to ... however, when the user chooses to continue and create more rectangles, the program will print the results of the old data plus the new data instead of just printing the new data.
I am very new to programming in Java and am stuck on how to fix this. It would be great if someone could help me out. Thanks!
This is my code:
import javax.swing.*;
public class RectangleProgram {
public static void main(String[] args) {
String defaultRectangleOutput = "";
String newRectangleOutput = "";
String finalOutput = "";
int option = JOptionPane.YES_OPTION;
while (option == JOptionPane.YES_OPTION) {
String rectangleNumberString = JOptionPane.showInputDialog(null,
"How many rectangles would you like to create? ",
"Number of Rectangles", JOptionPane.QUESTION_MESSAGE);
if (rectangleNumberString == null) return;
while (rectangleNumberString.equals("")) {
rectangleNumberString = JOptionPane.showInputDialog(
"You have entered nothing.\n" +
"Please try again: ");
}
int rectangleNumber = Integer.parseInt(rectangleNumberString);
while (rectangleNumber <= 0) {
rectangleNumberString = JOptionPane.showInputDialog(
"Entry cannot be 0 or negative.\n" +
"Please try again: ");
if (rectangleNumberString == null) return;
rectangleNumber = Integer.parseInt(rectangleNumberString);
}
for (int i = 0; i < rectangleNumber; i++) {
String lengthString = JOptionPane.showInputDialog(null,
"Enter Length for rectangle: ",
"Getting Length", JOptionPane.QUESTION_MESSAGE);
if (lengthString == null) return;
while (lengthString.equals("")) {
lengthString = JOptionPane.showInputDialog(
"You have entered nothing.\n" +
"Please try again: ");
}
double length = Double.parseDouble(lengthString);
while (length < 0) {
lengthString = JOptionPane.showInputDialog(
"Negative numbers are not allowed.\n" +
"Please try again: ");
if (lengthString == null) return;
length = Double.parseDouble(lengthString);
}
String widthString = JOptionPane.showInputDialog(null,
"Enter Width for rectangle: ",
"Getting Length", JOptionPane.QUESTION_MESSAGE);
if (widthString == null) return;
while (widthString.equals("")) {
widthString = JOptionPane.showInputDialog(
"You have entered nothing.\n" +
"Please try again: ");
}
double width = Double.parseDouble(widthString);
while (width < 0) {
widthString = JOptionPane.showInputDialog(
"Negative numbers are not allowed.\n" +
"Please try again: ");
if (widthString == null) return;
width = Double.parseDouble(widthString);
}
SimpleRectangle newRectangle = new SimpleRectangle(width, length);
newRectangleOutput += "Rect-" + i + " (" + newRectangle.width +
", " + newRectangle.length + ")\n" +
"Area = " + newRectangle.getArea() + "\n" +
"Perimeter = " + newRectangle.getPerimeter() + "\n";
}
SimpleRectangle defaultRectangle = new SimpleRectangle();
defaultRectangleOutput = "Default (" + defaultRectangle.width +
", " + defaultRectangle.length + ")\n" +
"Area = " + defaultRectangle.getArea() + "\n" +
"Perimeter = " + defaultRectangle.getPerimeter() + "\n";
JOptionPane.showMessageDialog(null, defaultRectangleOutput + "\n"
+ newRectangleOutput, "Final Results",
JOptionPane.PLAIN_MESSAGE);
option = JOptionPane.showConfirmDialog(
null, "Would you like to create another rectangle?");
}
}
}
class SimpleRectangle {
double length;
double width;
SimpleRectangle() {
length = 1;
width = 1;
}
SimpleRectangle(double newLength, double newWidth) {
length = newLength;
width = newWidth;
}
double getArea() {
return length * width;
}
double getPerimeter() {
return (2 * (length + width));
}
void setLengthWidth(double newLength, double newWidth) {
length = newLength;
width = newWidth;
}
}
You call
newRectangleOutput += "Rect-" + ...
which is equivalent to
newRectangleOutput = newRectangleOutput + "Rect-" + ...
So you add the output of the new rectangle the the old ones. Replace += by =, that is what you want.
You are appending your new rectangles to the same string. Add newRectangleOutput = ""; in the while loop before your for loop for all rectangles
while (option == JOptionPane.YES_OPTION) {
.
.
newRectangleOutput = "";
for (int i = 0; i < rectangleNumber; i++) {
.
.
}
}
check out what you did here...
newRectangleOutput += "Rect-" + i + " (" + newRectangle.width +
", " + newRectangle.length + ")\n" +
"Area = " + newRectangle.getArea() + "\n" +
"Perimeter = " + newRectangle.getPerimeter() + "\n";
you added the newRectangleOutput to the string again..that's why u re seeing the previous value...
to fix it...before you start with the next rectangle i.e end of each loop... make sure you set newRactangleOutput = "";

Java clarification on += assignment operator

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

Categories

Resources