Infinite multiplication questions - java

I am trying to make a program that randomly generates two single digit numbers, creates a multiplication question, asks the user for the answer, counts the amount of questions and correct answers, and after every question the user is able to stop the loop to see how many he got correct out of the number of questions that were given.
I believe that I should be using a while loop (probably the easiest way) but I don't know exactly how to go about doing that. Here is what I currently have:
int number = 0;
int number1 = (int)(Math.random() * 10); //Produce two single digit numbers
int number2 = (int)(Math.random() * 10);
Scanner input = new Scanner(System.in); //Create Scanner
System.out.print("What is " + number1 + " + " + number2 + "? ");
int answer = input.nextInt();
while (number <= 10) {
if (number1 + number2 != answer ) {
System.out.println(" Incorrect!\n Would you like to see your overall result? (yes or no)");
}
else {
System.out.println(" Correct, great job!\n Would you like to see your overall result? (yes or no)");
}
}

Since this seems like an assignment I'll just give you pseudocode
MainMethod
{
//Create a new Random to generate random numbers
//(Import java.util.random)
//You need variables for:
//Total number of questions asked
//Total number of correct answers
//Start the question loop
while(true){
//Generate your two random numbers
//Ask the question
//Index the total number of questions
//Get their answer
//Check their answer
if(answer is correct){
//Index correct answers
}
//Ask whether they want to continue
//Check whether they want to stop
if(they want to quit){
//Break out of the while loop (break;)
}
}
//Tell them how many they got correct out of the total
}
Maybe I gave a little too much, but I hope this helps.

Related

Specify a start value in a for loop

I am doing my for loop below in Java. I have a default value for the number that the user starts out with, which is 100. I dedicated a field for the user to input there own number in, which would change the default value in the constructor.
Anyway, I want my for loop to take that number that they put in and start to increment it until they reach 100. The loop runs fine but it starts at 53 and it increments I don't know why. Can someone tell me please?
My code is below.
defaultvaluenumber = userinput;
for(defaultvaluenumber = userinput; userinput < 100; userinput++)
{
System.out.println("Your current number incremented is: " + userinput);
}
Can someone tell me please? My code is below.
defaultvaluenumber = userinput;
for(defaultvaluenumber = userinput; unserinput < 100; userinput++)
{
System.out.println("Your current number incremented is: " + userinput);
}
Yes, for induction userinput contains the value 53. That's the reason!
Not really clear what you are saying about fields and constructors, but based on your later comments, the problem seems to be coming from elsewhere.
Here is what I think you are asking.
I want my for loop to take that number that they put in
java.util.Scanner sc = new java.util.Scanner(System.in);
System.out.print("Enter a starting value: ");
int userinput = sc.nextInt();
and start to increment it until they reach 100
while(userinput < 100) {
System.out.println("Your current number incremented is: " + userinput++);
}

java if statement not executing

I am relatively new to java and this is my first time working with if else statements. I was attempting to make a basic game in which the user guesses a number between 1-3, and the program tells them if they are right or wrong. However, when I go to execute the program, when I type 1, the program does not respond and I have to use ctrl-E to end it. What am I doing wrong? When I enter values aside from 1, the program executes as I want it to by printing "Goodbye."
Here is my code:
import java.util.*;
public class GuessTheNumber {
public static void main(String[] args) {
Scanner game = new Scanner(System.in);
Random rand = new Random();
System.out.println("Hey there! Want to play a game?");
System.out.println("\tIf yes, type 1");
System.out.println("\tIf no, type 2");
int ans1 = game.nextInt();
if (ans1 == 1) { // This is true, yet when I type 1, nothing happens.
int randomNum = rand.nextInt((3 - 1) + 1) + 1;
int guess = game.nextInt();
System.out.println("Great! I am thinking of an integer between 1 and 3. Guess what it is?");
if (guess == randomNum) {
System.out.println("Congradulations! You guessed correctly! The number was" + randomNum);
} else {
System.out.println("Sorry, your guess was incorrect. The number I was thinking of was" + randomNum);
}
} else {
System.out.println("Goodbye.");
}
}
}
This is my first time posting here, so I apologize if this question has been answered elsewhere.
Because if ans1=1, then it expects another input from user and checks if the guess and another input are same.
This is second input that it is waiting for
int guess = game.nextInt();
Input any number ,if the random number generated is equal to the number you added second time, it will return "Congradulations! You guessed correctly! The number was" else "Sorry, your guess was incorrect. The number I was thinking of was" with number
Instead of:
int guess = game.nextInt();
System.out.println( "Great! I am thinking of an integer between 1 and 3. Guess what it is?" );
You should have them reversed.
System.out.println( "Great! I am thinking of an integer between 1 and 3. Guess what it is?" );
int guess = game.nextInt();

Making a quiz with Java using arrays. Need pointers with grading answers

This is for a class. I'm having trouble figuring out how to best compare the user input with the array answerkey and consequently grade the answers given. I tried searching for a while but wasn't able to find what I needed, so any pointers would be much appreciated!
The prompt for the exercise is:
Write a DMV program that grades the written portion of the driver's license exam. It should have 20 multiple choice questions. It should ask the user to enter the student’s answers for each of the 20 questions, which should be stored in another array. After the student’s answer have been entered, the program should display a message indicating whether the student passed or failed the exam.( A student must correctly answer 15 of the 20 questions to pas the exam). It should then display the total number of correctly answered questions, and the total number of incorrectly answered questions. Input validation: Only accept the letters A, B, C or D.
My code so far:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] answerkey = {"b","d","a","a","c","a","a","d","b","b","b","d","c","a","c","c","a","d","a","a"};
int n = 0;
int correct = 0;
int incorrect = 0;
String answer = "";
for (int i = 0; i < 20; i++){
System.out.println("Please enter your answers. Acceptable input is limited to A,B,C and D.\n");
answer = input.next();
if (answer.compareTo(answerkey[0])==0){
correct++;}
else {incorrect++;}
}
if (correct > 14){
System.out.println("You passed.");
} else {
System.out.println("You failed.");
}
System.out.println("You have " + correct + " correct answers.");
System.out.println("You have " + incorrect + " incorrect answers.");
}
Use a dynamic index accessing variable. Right now, every answer you have will be compared to the first answer ("b")
An example of this would be
String[] myArray = { //initialize values here
};
for (int index = 0; index <= myArray.length-1; index++){
if (answer.equals(myArray[index]){
correct++;}
else{
incorrect++;}
}
Try this code on comparing the user input with the array myArray.
Hope this helps.
String[] myArray= { //initialize values here
};
if ((myArray[0]).equals(answer)){
correct++;
} else{
incorrect++;
}

Checking for negative values with scanner in

I have just written my first java program for a class I am taking which is used to give a student graduation information based on the credits for each class remaining. I have gotten everything to work except the required entry to check for negative values. Please see below and let me know if you have any ideas. Thanks in advance.
package txp1;
import java.util.ArrayList;
import java.util.Scanner;
public class txp1 {
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Welcome to the University Graduation Calculator!");
System.out.println();
System.out.println("This calculator will help determine how many terms "
+ "you have remaining and your tuition total based upon credits"
+ " completed per semester.");
System.out.println();
double tuitionpersem = 2890;
System.out.println("We will begin by entering the number of credits for"
+ " each class remaining toward your degree.");
double sum = 0;
ArrayList<Double> credit = new ArrayList<>();
{
System.out.println("Please enter the number of credits for each individual class on a separate line and then press enter, Q to quit:");
Scanner in = new Scanner(System.in);
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
while (in.hasNextDouble()) {
credit.add(in.nextDouble());
}
for (int i = 0; i < credit.size(); i++) {
sum += credit.get(i);
}
System.out.println("Total credits remaining: " + sum);
}
int perterm = 0;
System.out.println("How many credits do you plan to take per term? ");
Scanner in = new Scanner(System.in);
perterm = Integer.parseInt(in.nextLine());
if (perterm <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
double totterms = sum / perterm;
totterms = Math.ceil(totterms);
System.out.print("Your remaining terms: ");
System.out.println(totterms);
double terms = (totterms);
System.out.print("The number of months to complete at this rate is: ");
System.out.println(6 * terms);
double cost = terms * 2890;
System.out.println("The cost to complete at this rate is: " + cost);
}
}
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
The ";" at the end of if statement is the end of it. You are not doing anything with the result of number <=0. I believe you meant it to be like:
if (number <= 0){
//operations….
}
Notice that you create number of type double, then assign an int (parsed from String) to it. You can use nextDouble method to get a double directly, and if you plan this number to be an Integer anyway then use type int instead of double and nextInt instead of parsing. For more information about parsing from input, check Scanner documentation.
Your if statements terminate if you put a semi colon at the end of them. Effectively ending your logic right there. The program basically checks the condition and then moves on. Which in turn executes your second statement regardless of what number <= 0 resolves to.
//Does not get expected results
if (number <= 0);
{
//Gets executed regardless of condition
System.out.println("The number of credits must be greater than zero!");
}
//Gets expected results
if (number <= 0)
{
//Gets executed only if the condition returns true
System.out.println("The number of credits must be greater than zero!");
}
Edit: Changed due to some helpful input.
2nd Edit: I would also consider putting a loop in your code that makes the user re-enter input to get the desired value. If you put in a negative value your code will just spit the error message and keep running which can make you scratch your head. Unless your teacher isn't grading on that then forget all of what I just said. =p

how to determine the multiples of numbers in java

read 2 numbers and determine whether the first one is a multiple of second one.
if (first % second == 0) { ... }
Given that this is almost certainly a homework question...
The first thing you need to think about is how you would do this if you didn't have a computer in front of you. If I asked you "is 8 a multiple of 2", how would you go about solving it? Would that same solution work if I asked you "is 4882730048987" a multiple of 3"?
If you've figured out the math which would allow you to get an answer with just a pen and paper (or even a pocket calculator), then the next step is to figure out how to turn that into code.
Such a program would look a bit like this:
Start
Read in the first number and store it
Read in the second number and store it
Implement the solution you identified in paragraph two using the mathematical operations, and store the result
Print the result to the user.
//To check if num1 is a multiple of num2
import java.util.Scanner;
public class multiples {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number!");
int num1 = reader.nextInt();
reader.nextLine();
System.out.println("Enter another number!");
int num2 = reader.nextInt();
if ((num1 % num2) == 0) {
System.out.println("Yes! " + num1 + " is a multiple of " + num2 + "!");
} else {
System.out.println("No! " + num1 + " is not a multiple of " + num2 + "!");
}
reader.close();
}
}
A number x is a multiple of y if and only if the reminder after dividing x with y is 0.
In Java the modulus operator(%) is used to get the reminder after the division. So x % y gives the reminder when x is divided by y.

Categories

Resources