I'm trying to teach myself Java and running into a little hiccup just two chapters into the book I got :P This is one from one of the exercises:
"Write a class that calculates and displays the conversion of an entered number of dollars into currency denominations---20s, 10s, 5s, and 1s."
I'm going on four hours of reading from 0 knowledge of coding thus far so hopefully this doesn't sound too simple a question to answer. I'm sure there's a much more efficient way of writing this entire thing, but my question pertains to how I can terminate the entire thing if the user answers "yes" or continue on with the revised version if they answer "no"?
Also any advice or guidance you guys can give me on learning Java would be much appreciated!
Thanks for taking the time to read this
import javax.swing.JOptionPane;
public class Dollars
{
public static void main(String[] args)
{
String totalDollarsString;
int totalDollars;
totalDollarsString = JOptionPane.showInputDialog(null, "Enter amount to be converted", "Denomination Conversion", JOptionPane.INFORMATION_MESSAGE);
totalDollars = Integer.parseInt(totalDollarsString);
int twenties = totalDollars / 20;
int remainderTwenty = (totalDollars % 20);
int tens = remainderTwenty / 10;
int remainderTen = (totalDollars % 10);
int fives = remainderTen / 5;
int remainderFive = (totalDollars % 5);
int ones = remainderFive / 1;
JOptionPane.showMessageDialog(null, "Total Entered is $" + totalDollarsString + "\n" + "\nTwenty Dollar Bills: " + twenties + "\nTen Dollar Bills: " + tens + "\nFive Dollar Bills: " + fives + "\nOne Dollar Bills: " + ones);
int selection;
boolean isYes, isNo;
selection = JOptionPane.showConfirmDialog(null,
"Is this how you wanted the total broken down?", "Select an Option", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
isYes = (selection == JOptionPane.YES_OPTION);
JOptionPane.showMessageDialog(null, "You responded " + isYes + "\nThanks for your response!");
isNo = (selection == JOptionPane.NO_OPTION);
int twenties2 = totalDollars / 20;
int tens2 = totalDollars / 10;
int fives2 = totalDollars / 5;
int ones2 = totalDollars / 1;
JOptionPane.showMessageDialog(null, "Total Entered is $" + totalDollarsString + "\n" + "\nTwenty Dollar Bills: " + twenties2 + "\nTen Dollar Bills: " + tens2 + "\nFive Dollar Bills: " + fives2 + "\nOne Dollar Bills: " + ones2);
}
}
First of all, you don't really seem to need the two booleans for isYes and isNo. Basically you asking the user whether he wants a different solution, that is one true/false value (or rather: isNo is the same as !isYes since the option pane will only return one of the values YES_OPTION and NO_OPTION).
What you'll want to do next is go to your 'refined' version if the user indicates that the first output was not what he wanted:
int selection = JOptionPane.showConfirmDialog(null,
"Is this how you wanted the total broken down?", "Select an Option", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (selection == JOptionPane.NO_OPTION) {
int twenties2 = totalDollars / 20;
int tens2 = totalDollars / 10;
int fives2 = totalDollars / 5;
int ones2 = totalDollars / 1;
JOptionPane.showMessageDialog(null, "Total Entered is $" + totalDollarsString + "\n" + "\nTwenty Dollar Bills: " + twenties2 + "\nTen Dollar Bills: " + tens2 + "\nFive Dollar Bills: " + fives2 + "\nOne Dollar Bills: " + ones2);
}
If the user selects 'Yes', your main method is done anyway, so there's no need to do anything in this case.
Related
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.");
}
}
A code returns error <identifier> expected. I don't know why this error is occuring.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
intro();
time();
}
public static void intro() {
System.out.println("Welcome");
System.out.println("What is your name");
Scanner input = new Scanner(System.in);
String name = input.nextLine();
System.out.println("Nice to meet you," + name + " where are you travelling to?");
String dest = input.nextLine();
System.out.println("Great!" + dest + " sounds like a great trip");
}
public static void time() {
Scanner input = new Scanner(System.in);
int hours, minutes;
float perd, perdc, change;
System.out.println("How many days are you going to spend travelling?");
int days = input.nextInt();
hours = days * 24;
minutes = hours * 60;
System.out.println("How much money in USD are you going to spend?");
Double money = input.nextDouble();
perd = (money / days);
System.out.println("What is the three letter currency symbol of your destination?");
String curr = input.nextLine();
System.out.println("How many" + curr + "are there in 1USD?");
Double ex = input.double();
change = money * ex;
perdc = perd * ex;
System.out.println("If you are travelling for" + days + "that is the same as" + hours + "or" + minutes + "minutes");
System.out.println("If you are going to spend" + money + "$USD that means per day you can spend upto $" + perd + "USD");
System.out.println("Your total budget in" + ex + "is" + change + ex + ",which per day is " + perdc + curr);
}
}
I'am glad to see peaple learning Java, and i'am happy to see peaople helping the juniors.
When i see your code, my first advise is to get a good IDE like Eclipse, IntelliJ or Netbeans, it will help you to see quickly the compilation errors.
My second advise is to get a look to the dev norms, as a junior i think is the first methodology you have to study to have a comprehensive and maintainable code.
for example please avoid adding several blank lines between the method signature and the first statment.
I barely touched your code to get it works.
I hope you will enjoy Java.
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
intro(input);
time(input);
}
public static void intro(Scanner input) {
System.out.println("Welcome");
System.out.println("What is your name");
String name = input.nextLine();
System.out.println("Nice to meet you, " + name + " where are you travelling to?");
String dest = input.nextLine();
System.out.println("Great! " + dest + " sounds like a great trip");
}
public static void time(Scanner input) {
int hours, minutes;
float perd, perdc, change;
System.out.println("How many days are you going to spend travelling?");
int days = input.nextInt();
hours = days * 24;
minutes = hours * 60;
System.out.println("How much money in USD are you going to spend?");
Float money = input.nextFloat();
perd = money / days;
System.out.println("What is the three letter currency symbol of your destination?");
String curr = input.nextLine();
System.out.println("How many " + curr + " are there in 1USD?");
Float ex = input.nextFloat();
change = money * ex;
perdc = perd * ex;
System.out.println("If you are travelling for " + days + " that is the same as " + hours + " or " + minutes + " minutes");
System.out.println("If you are going to spend " + money + " $USD that means per day you can spend upto $" + perd + " USD");
System.out.println("Your total budget in " + ex + " is " + change + ex + " ,which per day is " + perdc + curr);
}
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 + "? ");
...
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.
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