I am suppose to write a java program where I ask user how many math questions they want to answer and generate random questions based on their answer using any loop of choice and keep a count of how many they answered correct. I got it to generate the random math problem, but it only does it once it seems to be skipping the loop. Can anyone help?
import javax.swing.JOptionPane;
import java.util.Random;
import java.util.Scanner;
/**
*
* #author user
*/
public class MathQuiz {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random obj = new Random();
int num1 = obj.nextInt(10);
int num2 = obj.nextInt(10);
int rand = num1 + num2;
String response = JOptionPane.showInputDialog(null,"How many problems would you like to solve?");
int ans = Integer.parseInt(response); // answer from question
String result= null;
int times = input.nextInt();
int counter = 0; //counts total math problems
while (counter != ans){
counter++;
JOptionPane.showInputDialog(num1 + "+" +num2);
if (ans == rand){
result= "Correct";
}else {
result= "Incorrect";
}
} JOptionPane.showMessageDialog(null, );
}
}
Here are the problems in your code:
You are not displaying the result after you compute the value.
Not generating the random numbers every time.
public class MathQuiz {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String response = JOptionPane.showInputDialog(null,"How many problems would you like to solve?");
int noOfTimes = Integer.parseInt(response); // answer from question
String result= null;
for (int counter = 0; counter < noOfTimes; counter++) {
Random obj = new Random();
int num1 = obj.nextInt(10);
int num2 = obj.nextInt(10);
int rand = num1 + num2;
int answer = Integer.parseInt(JOptionPane.showInputDialog(num1 + "+" +num2));
if (answer == rand){
result= "Correct";
}else {
result= "Incorrect";
}
JOptionPane.showMessageDialog(null, result);
}
}
}
The number you get inside of the loop should not be stored in the same variable as the one you use in your while(...) condition. In this case, you used ans. In the example below I have separate variables for the math answer and the number of times to iterate in the loop. Another problem you had is that you were not passing the result message to the showMessageDialog(..) method.
import javax.swing.JOptionPane;
import java.util.Random;
import java.util.Scanner;
public class MathQuiz {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random obj = new Random();
String timesString = JOptionPane.showInputDialog(null,"How many problems would you like to solve?");
int timesInt = Integer.parseInt(timesString); // answer from question
int counter = 0; //counts total math problems
while (counter != timesInt) {
counter++;
int num1 = obj.nextInt(10);
int num2 = obj.nextInt(10);
int rand = num1 + num2;
String answerString = JOptionPane.showInputDialog(num1 + "+" +num2);
int answerInt = Integer.parseInt(answerString);
JOptionPane.showMessageDialog(null, answerInt == rand ? "Correct" : "Incorrect");
}
}
}
Related
I am trying to use a set to find the unique numbers and get the sum from user entered numbers. I heard that arrays are easier but a set might just do for me. I don't know much about sets or what they do so any input would be fantastic. Much appreciated everybody!
import java.util.Scanner;
public class getdistinct
{
int dialr;
Scanner scan = new Scanner(System.in);
public double go()
{
double a = 0
counter = 10;
int total = 0;
for (counter != 0)
{
int thisisnewnumber = scan.nextInt();
System.out.println("Enter number that you want to add: ");
if(newInteger < 0)
{
n = n + 1
dial = dial - 1;
}
else
{
System.out.println("wrong");
}
}
System.out.println("the total is ";
return a;
}
}
java.util.HashSet stores unique values. Made minor changes to your program to use Set to store unique values and calculate sum of unique values using for loop
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class quiz_assignment {
int counter;
Scanner scan = new Scanner(System.in);
public int go() {
int a = 0;
int n = 0;
counter = 10;
Set<Integer> unValues = new HashSet<Integer>();
while (counter != 0) {
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if (newInteger < 0) {
unValues.add(new Integer(newInteger));
n += newInteger;
counter = counter - 1;
a = a + newInteger;
} else {
System.out
.println("Must be negative integer, please try again");
}
}
int unSum = 0;
for (Integer value : unValues) {
unSum += value;
}
System.out.println("The sum of all ten integers is: " + a);
System.out.println("The sum of unique integers is: " + unSum);
return n;
}
public static void main(String[] args) {
quiz_assignment o = new quiz_assignment();
o.go();
}
}
Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. Following is an example to explain Set functionality
I used here (HashSet).
import java.util.Scanner;
public class quiz_assignment
{
int counter;
Scanner scan = new Scanner(System.in);
Set<Integer> ditinctSet = new HashSet<Integer>();
public int go()
{
int a=0;
int n=0;
counter = 10;
int total = 0;
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(!ditinctSet.contains(newInteger)){
ditinctSet.add(newInteger);
}
if(newInteger < 0)
{
n+=newInteger;
counter = counter - 1;
a=a+newInteger;
}
else
{
System.out.println("Must be negative integer, please try again");
}
}
System.out.println("The sum of all ten integers is: " + a);
System.out.println("Distinct numbers are: ");
System.out.println(ditinctSet);
return n;
}
}
And here a link to start knoing more about sets.
Hashsets are useful because they don't store duplicate entries. You can use them to store your set of unique numbers that the user inputs. I also removed the variable "a" from your code because its purpose seemed identical to variable n's.
import java.util.Scanner;
public class quiz_assignment{
int counter;
Scanner scan = new Scanner(System.in);
public int go()
{
HashSet<Integer> distinctNumbers = new HashSet<>();
int n=0;
counter = 10;
int total = 0;
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(newInteger < 0)
{
n+=newInteger;
counter = counter - 1;
distinctNumbers.add(newInteger);
}
else
{
System.out.println("Must be negative integer, please try again");
}
}
int size = distinctNumbers.size();
System.out.println("The sum of all ten integers is: " + n);
System.out.println("You inputed " + size + " numbers.");
System.out.println("Your numbers are:");
for(Integer i: distinctNumbers){
System.out.println(i);
}
return n;
}
}
I'm in a Beginner Java class and I'm confused about using additional methods and using them in another. I think that I have most of my assignment done but I just need help to create the methods. One is to generate the question and the other one is to display the message.
I know that in order to call a method
public static test(num1,num2,num3)
but in my code, how do I make it so that I call the method and still make it loop correctly?
In the assignment instructions that was given to me, In order to do that, I have to write a method named
public static in generateQuestion()
and
public static void displayMessage(boolean isCorrect)
This is my code:
//For Random Generator
import java.util.Random;
//Uses a class Scanner
import java.util.Scanner;
public class Assign6
{
public static void main(String[] args)
{
//Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
//Generate Random Number for Quiz
Random randomNumbers = new Random();
int number1 = 0;
int number2 = 0;
int answer = 0;
//Rolls number from 1-9
number1 = randomNumbers.nextInt(9);
number2 = randomNumbers.nextInt(9);
//Question prompt
System.out.println("How much is " +number1+ " times " +number2+ "? ");
answer = input.nextInt();
//If Else While Statements
if(answer == (number1*number2))
{
System.out.println("Good job! You got it right!");
}
else
{
while (answer !=(number1*number2))
{
System.out.println("You got it wrong, try again!");
answer = input.nextInt();
}
}
}
}
You are going to have two methods
public static void generateQuestion()
Which is going to hold the code to generate the random values and output it. It will return void because all it's doing is printing out.
Next you will have
public static void displayMessage(boolean isCorrect)
which will be called if if(answer == (number1*number2)) is true with true as the parameter. Otherwise it will still be called, but the parameter passed in will be false. This method will determine if isCorrect is true or false, and output the appropriate message.
If I got it right, I have a solution that might be a little stupid but will work for your assignment.
If you make generateQuestion that makes two random ints, prints the question and returns their multiple (answer).
And displayMessgae that prints "Good job! You got it right!" if isCorrect is true and "You got it wrong, try again!" else,
you can call generateQuestion, then get an answer (in main), and loop until answer is correct (according to return value of generateQuestion).
Every time you get a new answer (in loop), call displayMessgae(false).
After the loop ended call displayMessgae(true)
This is my working code for this:
//For Random Generator
import java.util.Random;
//Uses a class Scanner
import java.util.Scanner;
public class Assign6
{
public static int generateQuestion()
{
Random r = new Random();
int x = r.nextInt(9), y = x = r.nextInt(9);
System.out.println("How much is " + x + " times " + y + "? ");
return x * y;
}
public static void displayMessage(boolean isCorrect)
{
if (isCorrect)
System.out.println("Good job! You got it right!");
else
System.out.println("You got it wrong, try again!");
}
public static void main(String[] args)
{
//Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
int rightAnswer = 0;
rightAnswer = generateQuestion();
while (input.nextInt() != rightAnswer)
displayMessage(false);
displayMessage(true);
}
}
If I understand your question correctly, It's simply a matter of separating the functionality that prints a question and displays the answer into separate methods. See my edited version of your code below
public class Assign6
{
public static void main(String[] args)
{
// Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
// Generate Random Number for Quiz
Random randomNumbers = new Random();
int number1 = 0;
int number2 = 0;
int answer = 0;
// Rolls number from 1-9
number1 = randomNumbers.nextInt(9);
number2 = randomNumbers.nextInt(9);
displayQuestion("How much is " + number1 + " times " + number2 + "?");
answer = input.nextInt();
// If Else While Statements
if (answer == (number1 * number2))
{
displayMessage(Boolean.TRUE);
}
else
{
while (answer != (number1 * number2))
{
displayMessage(Boolean.FALSE);
answer = input.nextInt();
}
}
}
public static void displayQuestion(String q)
{
System.out.println(q);
}
public static void displayMessage(Boolean isCorrect)
{
if (isCorrect)
{
System.out.println("Good job! You got it right!");
}
else
{
System.out.println("You got it wrong, try again!");
}
}
}
I have a program which should generate the factorial of any given number n.
When the user enters a number, the output is the factorial for every number entered after that into the calculator.
The code compiles fine but the calculator will not calculate any factorial except for the first.
As i can't use recursion for solving this problem please post only answers without using recursion.
Here's the code:
import javax.swing.JOptionPane;
public class Assignment7
{
public static void main(String[] args)
{
int number1;
int factorial = 1;
String message;
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : "));
for(int i = 1; i <= number1; i++)
{
factorial = factorial * i;
}
do
{
message = String.format("The factorial of %d is: %d", number1, factorial);
JOptionPane.showMessageDialog(null, message);
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : "));
}
while(number1 != 1);
}
}
This code
for(int i = 1; i <= number1; i++)
{
factorial = factorial * i;
}
needs to be repeated for each input.
I suggest that your GF put this into a method that can be called and the method will return the result.
import javax.swing.JOptionPane;
public class Assignment7
{
public static void main(String[] args)
{
int number1;
int factorial = 1;
String message;
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : "));
for(int i = 1; i <= number1; i++)
{
factorial = factorial * i;
}
do
{
message = String.format("The factorial of %d is: %d", number1, factorial);
JOptionPane.showMessageDialog(null, message);
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : "));
factorial = 1;
for(int i = 1; i <= number1; i++)
{
factorial = factorial * i;
}
}
while(number1 != 1);
}
}
You have to reset the number and the factorial to get the right factorial.
Also i would consider to use a head-controlled loop. Because it's easier to understand what is going on. Also maybe don't put the Inputdialog and the Parsing of the string to int into one line, it makes it a lot easier to handle wrong user-inputs, what you also should be doing.
Here my solution:
import javax.swing.JOptionPane;
class Assignment7 {
public static void main(String[] args) {
int number1 = 0;
int factorial = 1;
String message;
while (number1 != 1) {
String positiveInteger = JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : ");
// You could check if there was a user-input and also later check if it's a number.
if (positiveInteger.length() > 0) {
number1 = Integer.parseInt(positiveInteger);
}
for (int i = 1; i <= number1; i++) {
factorial = factorial * i;
}
message = String.format("The factorial of %d is: %d", number1, factorial);
JOptionPane.showMessageDialog(null, message);
//Reset everything
number1 = 0;
factorial = 1;
message = "";
}
}
}
I seems like I cant skip over the while loop as my code does not understand that I typed in the right number.
import java.util.Scanner;
public class HelloWorld1{
static Scanner userInput = new Scanner(System.in);
static int randomNumbe
public static void main(String[] args){
System.out.println(randomNum());
int randomGuess = -1 ;
while(randomGuess != randomNum()){
System.out.println("Guess a number between 0 to 100");
randomGuess = userInput.nextInt();
}
System.out.println("Yes the random number is:" + randomGuess);
}
public static int randomNum(){
randomNumber = (int) (Math.random()*101);
return randomNumber;
}
}
When you call randomNum(), you're getting another random value back. Try:
int expected = randomNum();
System.out.println(expected);
int guess = -1;
while(guess != expected) {
...
}
package randomguess;
import java.util.Scanner;
public class RandomGuess {
/**
* #param args the command line arguments
*/
static int randomNumber = 0;
public static int getRandomInt() {
randomNumber = (int) (Math.random()*101);
return randomNumber;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int guessInt = sc.nextInt();
int randomInt = getRandomInt();
while(guessInt != randomInt) {
System.out.println("Better luck nextTime :D Random number was "+randomInt);
guessInt = sc.nextInt();
randomInt = getRandomInt();
}
System.out.println("Yeah! You are oracle!");
}
}
Here is probably what you want. Let me know if it is.
I'm writing a program for my class where I have to use a for loop to takes two numbers from the keyboard. The program should then raise the first number to the power of the second number. Use a for loop to do the calculation. I'm getting the error that inum3 is not being initialized (I understand because the loop may never enter) but I cannot figure out how to make this work. Line 25 and 28 to be specific.
import javax.swing.*;
public class Loop2
{
public static void main(String[] args)
{
int inum1, inum2, inum3, count;
String str;
str = JOptionPane.showInputDialog("Please Enter a Numer");
inum1 = Integer.parseInt(str);
str = JOptionPane.showInputDialog("Please Enter a Numer");
inum2 = Integer.parseInt(str);
for (count = 1; count == inum2; count+=1)
{
inum3 = inum3 * inum1;
}
JOptionPane.showMessageDialog(null, String.format ("%s to the power of %s = %s", inum1,inum2, inum3), "The Odd numbers up to" + inum1,JOptionPane.INFORMATION_MESSAGE);
}//main
}// public
you need to initialize the variable inum3. As it stands right now, when your program tries to execute
inum3 = inum3 * inum1;
inum3 has no value, so it can't do the multiplication.
I think you want it to be 1 in this case.
So instead of
int inum1, inum2, inum3, count;
you can do
int inum1, inum2, inum3 = 1, count;
initialize num3 to one because you cand use something to define itself.
num3 = one;
import javax.swing.JOptionPane;
public class Loop2 {
public static void main(String[] args) {
int base, exp, result = 1;
String str;
str = JOptionPane.showInputDialog("Please Enter a Number");
base = Integer.parseInt(str);
str = JOptionPane.showInputDialog("Please Enter an Exponent");
exp = Integer.parseInt(str);
for (int count = 0; count < exp; count++) {
result *= base;
}
JOptionPane.showMessageDialog(null, String.format("%s to the power of %s = %s", base, exp, result),
"The Odd numbers up to" + base, JOptionPane.INFORMATION_MESSAGE);
}
}