Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 13 hours ago.
Improve this question
I am trying to create a 5 questions quiz, after question 4 it automatically prints question 5 and not ask first, and then proceeds on printing the results. here is my code
import java.util.Scanner;
public class quiz {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name, section;
int score, numQuestions = 5;
System.out.println("Welcome to the Basic Electronics Quiz!");
boolean repeat;
do {
// Get name and section
System.out.print("Enter your name: ");
name = scanner.nextLine().trim();
System.out.print("Enter your section: ");
section = scanner.nextLine().trim();
// Initialize score
score = 0;
// Question 1
System.out.println("\nQuestion 1: What is Ohm's Law?");
System.out.println("A. Voltage = Current x Resistance");
System.out.println("B. Current = Voltage x Resistance");
System.out.println("C. Resistance = Voltage / Current");
System.out.print("Answer: ");
String answer1 = scanner.nextLine().trim().toLowerCase();
if (answer1.equals("a")) {
System.out.println("Correct!");
score++;
}else {
System.out.println("Wrong. The correct answer is " + "A" + ".");
}
System.out.println();
// Question 2
System.out.println("\nQuestion 2: What is the unit of resistance?");
System.out.println("A. Ampere");
System.out.println("B. Volt");
System.out.println("C. Ohm");
System.out.print("Answer: ");
String answer2 = scanner.nextLine().trim().toLowerCase();
if (answer2.equals("c")) {
System.out.println("Correct!");
score++;
}else {
System.out.println("Wrong. The correct answer is " + "C" + ".");
}
System.out.println();
// Question 3
System.out.println("\nQuestion 3: An LED is a type of resistor. (True/False)");
System.out.print("Answer: ");
String answer3 = scanner.nextLine().trim().toLowerCase();
if (answer3.equals("true")) {
System.out.println("Correct!");
score++;
}else {
System.out.println("Wrong. The correct answer is " + "True" + ".");
}
System.out.println();
// Question 4
System.out.println("Question 4: What is the total resistance of two 10-ohm resistors in parallel?");
System.out.print("Your answer: ");
try {
double answer4 = scanner.nextDouble();
double expectedAnswer4 = 5.0;
if (Math.abs(answer4 - expectedAnswer4) < 0.0001) {
System.out.println("Correct!");
score++;
} else {
System.out.println("Wrong. The correct answer is " + expectedAnswer4 + ".");
}
System.out.println();
} catch (Exception e) {
// If there's an error parsing the input, don't add to score
}
// Question 5
System.out.println("\nQuestion 5: What is the term for a circuit that can generate an output signal with a fixed frequency?");
System.out.print("Your answer: ");
String answer5 = scanner.nextLine().trim().toLowerCase();
if (answer5.contains("Occilator") && answer5.contains("occilator")) {
score++;
}
else {
//System.out.println("Wrong. The correct answer is " + "Oscillator" + ".");
}
System.out.println();
// Display results
System.out.printf("\n%s, section %s, your score is %d/%d.\n", name, section, score, numQuestions);
// Ask to repeat
System.out.print("\nDo you want to take the quiz again? (yes/no): ");
String repeatStr = scanner.nextLine().trim().toLowerCase();
repeat = repeatStr.equals("yes") || repeatStr.equals("y");
} while (repeat);
System.out.println("\nThank you for taking the quiz!");
}
}
I tried copying only the question 5 to another file and it works but when i paste it again in the main file it will only proceeds on printing the results instead of asking for question 5
The problem is in using scanner.nextDouble();. You can read here more about why the problem occurs on this line.
You can solve your problem if you use Double.parseDouble(scanner.nextLine()); instead of scanner.nextDouble();.
Also, as Gilbert Le Blanc
has stated in the comments, you need to update the condition in your 5th question from answer5.contains("Occilator") && answer5.contains("occilator") to answer5.contains("Occilator") || answer5.contains("occilator"), otherwise you will never be able to answer the 5th question correctly. Here you also meant to write oscillator and not ocillator.
Here is an example output after implementing the solution:
Welcome to the Basic Electronics Quiz!
Enter your name: Aleksa
Enter your section: 1
Question 1: What is Ohm's Law?
A. Voltage = Current x Resistance
B. Current = Voltage x Resistance
C. Resistance = Voltage / Current
Answer: a
Correct!
Question 2: What is the unit of resistance?
A. Ampere
B. Volt
C. Ohm
Answer: c
Correct!
Question 3: An LED is a type of resistor. (True/False)
Answer: true
Correct!
Question 4: What is the total resistance of two 10-ohm resistors in parallel?
Your answer: 5
Correct!
Question 5: What is the term for a circuit that can generate an output signal with a fixed frequency?
Your answer: occilator
Aleksa, section 1, your score is 5/5.
Do you want to take the quiz again? (yes/no):
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
Improve this question
package Fare;
import java.util.Scanner;
public class fare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" Enter Class ");
System.out.println(" a. Senior b. Student c. Regular ");
System.out.println("Enter class : ");
int num = input.nextInt();
if (num = 1) {
double fare = 9 * 0.10;
System.out.println("Your fare will be " + fare + "▒. Thank you.");
}
else if (num = 2 ) {
double fare = 9 * 0.08;
System.out.println("Your fare will be " + fare + "▒. Thank you.");
}
else {
System.out.println("your fare will be 9▒. Thank you.");
}
}
}
Hi i can't seem to understand why there is an error in my if statement stating that it cannot convert int to boolean. I have already checked it and still can find any problem or mybe i just don't know.
You should change if(num=1) to if(num==1) and if else(num=2) to if else(num==2).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
For some reason, my program stops when it reaches the part that asks the user if it know it's exam 1 score. I need the user to be able to enter yes or no. Why does the program stop? I need it to work properly. I have all the if-else statements. I am able to enter the percentage weights, but that is all that the program will do. More must be done. My code extends far beyond entering the percentage weights. Please help me.
import java.util.Scanner;
public class GradeCalculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner grade = new Scanner (System.in);
// A new scanner must be created. The scanner is essential to this program performing properly.
double A = 90-100;
double B = 80-89;
double C = 70-79;
double D = 60-69;
double F = 0-59;
String LetterGrade;
String yes;
String no;
double Exam1, Exam2, finalExam, Labs, Projects, Attendance, Quizzes;
double Exam1Grade, Exam2Grade, finalExamGrade, LabAverage, ProjectsAverage, AttendanceAverage, QuizzesAverage;
double knownWeight;
double PercentageWeights;
// As always, the variables must be declared at the beginning of the program.
System.out.print(
"Grading Scale:\n"+
"A = 90-100 \n"+
"B = 80-89 \n"+
"C = 70-79 \n"+
"D = 60-69 \n"+
"F = 00-59 \n");
System.out.println("What letter grade do you want to achieve in this course?");
LetterGrade = grade.next();
// The user will type the letter grade that it wants in this part.
System.out.println("\nEnter Percentage Weights: \t");
String input = grade.nextLine();
// The string above is needed when the user enters the exam grades and averages.
System.out.print("\n\nExam 1: \t");
Exam1 = grade.nextShort();
System.out.print("\nExam 2: \t");
Exam2 = grade.nextShort();
System.out.print("\nFinal Exam: \t");
finalExam = grade.nextShort();
System.out.print("\nLabs: \t");
Labs = grade.nextShort();
System.out.print("\nProjects: \t");
Projects = grade.nextShort();
System.out.print("\nAttendance: \t");
Attendance = grade.nextShort();
System.out.print("\nQuizzes: \t");
Quizzes = grade.nextShort();
PercentageWeights = (int)(Exam1 + Exam2 + finalExam + Labs + Projects + Attendance + Quizzes);
// The equation above will provide the sum of the percentage weights. Since the variables in the equation were
// originally declared as doubles, I had to put "int" before the actual equation.
if (PercentageWeights > 100 || PercentageWeights < 100) {
System.out.println("\nWeights do not add up to 100. Program exiting. Have a nice day!");
System.exit(0);
}
else {
System.out.println("\nEnter your scores out of a 100: \t");
}
// The part above is very important to continue the rest of the program. If the sum of the percentage weights equals 100,
// the program will continue to run. If the sum is greater than or less than 100, the program will terminate.
System.out.print("\nDo you know your Exam 1 score?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nScore received on Exam 1: ");
Exam1Grade = grade.nextDouble();
}
else{
Exam1Grade = 0;
}
System.out.print("\nDo you know your Exam 2 score?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nScore received on Exam 2: ");
Exam2Grade = grade.nextDouble();
}
else{
Exam2Grade = 0;
}
System.out.print("\nDo you know your final exam score?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nScore received on final exam: ");
finalExamGrade = grade.nextDouble();
}
else{
finalExamGrade = 0;
}
System.out.print("\nDo you know your lab average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage lab grade: ");
LabAverage = grade.nextDouble();
}
else{
LabAverage = 0;
}
System.out.print("\nDo you know your project average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage project grade: ");
ProjectsAverage = grade.nextDouble();
}
else{
ProjectsAverage = 0;
}
System.out.print("\nDo you know your quiz average?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nAverage quiz grade: ");
QuizzesAverage = grade.nextDouble();
}
else{
QuizzesAverage = 0;
}
System.out.print("\nDo you know your attendance average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage Attendance Grade: ");
AttendanceAverage = grade.nextDouble();
}
else{
AttendanceAverage = 0;
}
// The user has finished answering the questions. Now the program will automatically calculate the data based on
// what the user typed into the program.
double CurrentGrade, avgToFinalLetterGrade, WeightandGrade, finalOverallGrade;
// The doubles above need to be declared in order for the equations below to work properly.
WeightandGrade = (int)((Exam1 * Exam1Grade) + (Exam2 * Exam2Grade) + (finalExam * finalExamGrade) + (Labs * LabAverage) + (Projects * ProjectsAverage) + (Quizzes * QuizzesAverage) + (Attendance * AttendanceAverage));
CurrentGrade = (int)((WeightandGrade) / (Exam1 + Exam2 + finalExam + Labs + Projects + Quizzes + Attendance ));
knownWeight = (Exam1 + Exam2 + finalExam + Labs + Projects + Quizzes + Attendance);
if (grade.equals(A)){
finalOverallGrade = 90;
}
else if (grade.equals(B)){
finalOverallGrade = 80;
}
else if (grade.equals(C)){
finalOverallGrade = 70;
}
else if (grade.equals(D)){
finalOverallGrade = 60;
}
else
finalOverallGrade = F;
avgToFinalLetterGrade = (((100-finalOverallGrade) * (WeightandGrade)) / (100 - knownWeight));
// The equations above are one of the last parts of the program. These equations are critical to determine whether or not the user received its desired letter grade.
// If the desired grade was not reached, the program will give a score that the user must consistently receive in order to possibly reach the desired letter grade.
if (finalOverallGrade >= 90){
System.out.print("Congratulations! You got an A in the class! Hooray!");
}
else if (finalOverallGrade >=80 && finalOverallGrade < 90){
System.out.print("Good job. You got a B in the class!");
}
else if (finalOverallGrade >=70 && finalOverallGrade < 80){
System.out.print("You got a C in the class.");
}
else if (finalOverallGrade >=60 && finalOverallGrade < 70){
System.out.print("You got a D in the class.");
}
else
System.out.print("I'm sorry, but you have a failing grade in the class. May your GPA have mercy on your soul.");
}
}
There are quite a lot of things wrong with this code.
Doing double A=90-100; will set A equal to -10;
However, for your current question:
You do String input = grade.nextLine();
You never change input, and so if input isn't "yes", it will just skip getting the grades for each piece.
(You might want to also consult Using scanner.nextLine() for other pitfalls with using scanner.nextLine() intermixed with scanner.nextInt or similar [in summary: if you do scanner.nextInt, this doesn't consume the newline, so scanner.nextLine() will just get that newline and not the next line after that you might be expecting to get])
input = grade.nextLine() reads the remainder of the line with the user's "percentage weights" input on it. So unless the user had a priori knowledge to enter "yes", input will be empty.
I.e., you need to update input with user input before if (input.equalsIgnoreCase("yes")) {....
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm about to build a program written in Java. I've already done its pseudocode, but I'm stuck on the code and I don't know what to do exactly. Well this is my progress so far:
pseudocode:
class Customer
Print out “Enter costumer’s name” (Pop up to answer)
Random boolean
If True
print membership type
print current date and time
class Visit
Print out "Have you bought anything?" (Pop up to answer)
if the answer is “no”
print “Have a nice day!”
exit program
if else the answer is “yes”
continue
if else the answer is not “no” nor “yes”
ask again
class Discount
Print "Enter Price of Item:" (Pop up to price)
if customer's membership type is “Premium”
the discount to the price will be 20%
else if customer's membership type is “Gold”
the discount to the price will be 15%
else if customer's membership type is “Silver”
the discount to the price will be 10%
else if customer's membership type “simple”
the discount to the price will be 10%
class Main
Variables: customer, visit, discount
customer = new object
Customer visit = new object
Visit discount = new object Discount
do work with customer
do work with visit
do work with discount
Print customer.name, customer.surname, discount.price, discount.final_price
code:
import java.util.Scanner;
public class Discount
{
public static void main(String[] args)
{
String cust_name;
String cust_surname;
String answer;
String answer2;
float firstPrice, rate_1, D_rate, discount, final_price, prem_disc;
prem_disc = 0;
final_price = 0;
discount = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter Costumer's Name:");
cust_name = in.next();
cust_surname = in.next();
System.out.println("Have you bought anything?");
answer = in.next();
if (answer.equals("no"))
{
System.out.println("Have a good day!");
System.exit(0);
} else if (!answer.equals("no"))
System.out.println("Enter Price of Item:");
firstPrice = in.nextFloat();
System.out
.println("What type of membership do you have? Premium, Gold, Silver or simple?");
answer2 = in.next();
if (answer2.equals("Premium"))
{
prem_disc = 20;
discount = (firstPrice * 20 / 100);
final_price = (firstPrice - discount);
} else if (answer2.equals("Gold"))
{
prem_disc = 15;
discount = (firstPrice * 15 / 100);
final_price = (firstPrice - discount);
} else if (answer2.equals("Silver"))
{
prem_disc = 10;
discount = (firstPrice * 10 / 100);
final_price = (firstPrice - discount);
} else if (answer2.equals("simple"))
{
prem_disc = 10;
discount = (firstPrice * 10 / 100);
final_price = (firstPrice - discount);
}
System.out.println("Costumer Name:" + cust_name + " " + cust_surname
+ "\n" + "Discount Rate:" + prem_disc + "\n"
+ "Discounted Price:" + final_price + "\n");
}
}
It's working, but there are many things that are missing. :/
Just take one step at a time, and when that step completely works, proceed to the next step.
An example:
Here's your pseudo-code (which, by the way, is a great way to start):
class Visit
Print out "Have you bought anything?" (Pop up to answer)
if the answer is “no”
print “Have a nice day!”
exit program
if else the answer is “yes”
continue
if else the answer is not “no” nor “yes”
ask again
Let's just implement and test the "is the answer yes-or-no" functionality:
/**
<P>{#code java MyHomeworkMainClass}</P>
**/
public class MyHomeworkMainClass {
public static final void main(String[] ignored) {
System.out.println("Visit.isUserInputYesNo(null)=" + Visit.isUserInputYesNo(null));
System.out.println("Visit.isUserInputYesNo(\"gibberish\")=" + Visit.isUserInputYesNo("gibberish"));
System.out.println("Visit.isUserInputYesNo(\"yes\")=" + Visit.isUserInputYesNo("yes"));
System.out.println("Visit.isUserInputYesNo(\"no\")=" + Visit.isUserInputYesNo("no"));
}
}
class Visit {
public static final boolean isUserInputYesNo(String input) {
return (input != null &&
(input.equals("yes") || input.equals("no")));
}
}
Now run it and see if it does what you want:
[C:\java_code\]java MyHomeworkMainClass
Visit.isUserInputYesNo(null)=false
Visit.isUserInputYesNo("gibberish")=false
Visit.isUserInputYesNo("yes")=true
Visit.isUserInputYesNo("no")=true
It does. Now add something else small to this and just keep going until you're done. For particularly difficult parts, it may be beneficial to create a completely separate class, with its own testing class. Then at the end, merge it all together. And never get rid of your testing functions, which will always be there for diagnosing future problems.
Good luck!
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Please help me with this. I feel like this is really simple and I am probably going to feel really stupid when its all said and done. Thank You.
I have tried multiple things but none seem to work.
Yes, I am more familiar with Visual Basic than Java, that is why I am having this problem.
import java.util.Scanner;
public class YuGiOhLifePointCounter {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
double choice_1;
System.out.print("\nEnter the starting life points for player-1: ");
choice_1 = sc.nextDouble();
double storage_1;
storage_1 = choice_1;
double choice_2;
System.out.print("\nEnter the starting life points for player-2: ");
choice_2 = sc.nextDouble();
double storage_2;
storage_2 = choice_2;
double lp;
System.out.print("\nEnter a 6 to change the life-points of either player: ");
lp = sc.nextDouble();
double display_1 = choice_1;
double display_2 = choice_2;
while (lp == 6) {
/* Starting here*/
if (display_1 <== 0) {
System.out.println("Player-2 has won the game.");
System.exit(0);
}
if (display_2 <== 0) {
System.out.println("Player-1 has won the game.");
System.exit(0);
}
if (display_1 <> 0 && display_2 <> 0) {
/* these 3 if statements above are giving me illegal import errors, I can't figure out why. Thank You.*/
double choose_1_2;
System.out.print("\nEnter a 1 to change player-1's life-points, or enter a 2 to change player-2's life-points: ");
choose_1_2 = sc.nextDouble();
if (choose_1_2 == 1) {
double ch_1;
System.out.print("\nEnter the number subtracted from or added to player-1's life-points: ");
ch_1 = sc.nextDouble();
double c_1;
System.out.print("\nEnter a 1 to subtract this number from player-1's life-points, or enter a 2 to add this number to player-1's life-points: ");
c_1 = sc.nextDouble();
if (c_1 == 1) {
display_1 = storage_1 - ch_1;
System.out.println("\nPlayer-1's life-points are currently " + display_1);
}
if (c_1 == 2) {
display_1 = storage_1 + ch_1;
System.out.println("\nPlayer-1's life-points are currently " + display_1);
}
}
if (choose_1_2 == 2) {
double ch_2;
System.out.print("\nEnter the number subtracted from or added to player-2's life-points: ");
ch_2 = sc.nextDouble();
double c_2;
System.out.print("\nEnter a 1 to subtract this number from player-2's life-points, or enter a 2 to add this number to player-1's life-points: ");
c_2 = sc.nextDouble();
if (c_2 == 1) {
display_2 = storage_1 - ch_2;
System.out.println("\nPlayer-2's life-points are currently " + display_2);
}
if (c_2 == 2) {
display_2 = storage_1 + ch_2;
System.out.println("\nPlayer-2's life-points are currently " + display_2);
}
}
}
}
}
}
if (display_1 <= = 0)
if (display_1 <> 0)
Not sure what you're trying to do exactly, but these aren't right.
If you want to check for display_1 less than 0, then you need:
if (display_1 < 0)
If you want to check for display_1 less than or equal to 0, then you need:
if (display_1 <= 0)
If you want to check for display_1 equal to 0, then you want:
if (display_1 == 0)
If you want to check for display_1 not equal to 0, then you want:
if (display_1 != 0)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am supposed to build a slot machine that has 3 display windows, each window has 6 options that could display.
I am confused what "test expression" to use after the term switch? and then how to get the program to compare the 6 cases or options (cherry, orange, plum, bell, melon, bar) to see if they match and offer a return of what they won.
import java.util.Random;
import java.util.Scanner;
public class SlotMachine
{
//This is the main method
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Random random = new Random();
String cont = "y" or "Y";
char answer;
int money = 0;
int totalEntered = 0;
int a;
int n;
int amountWon = 0;
int dbl = money * 2;
int trpl = money * 3;
while (cont.equals("y"))OR (cont.equals("Y"))
{
a = random.nextInt(6);
n = random.nextInt(991) +10;
totalEntered += money;
System.out.println("How much money would you like to bet? ");
money = keyboard.nextInt();
switch (TestExpression????)
{
case 0:
System.out.println("Cherry");
break;
case 1:
System.out.println("Orange");
break;
case 2:
System.out.println("Plum");
break;
case 3:
System.out.println("Bell");
break;
case 4:
System.out.println("Melon");
break;
default:
System.out.println("Bar");
}
if ()
{
System.out.println("You have won $0");
}
else if ()
{
System.out.println("Congratulations, you have won $" + dbl);
amountWon += dbl;
}
else if ()
{
System.out.println("Congratulations, you have won $" + trpl);
amountWon += trpl;
}
System.out.println("Continue? Enter y = yes");
cont = keyboard.nextLine();
}
}
}
Put a there. Whatever a is it jumps to that case in the switch statement. Ex: if a is 2 it jumps to case 2 so would print "Plum"
Could I also recommend using an Enum in this case?
enum SlotOptions {
CHERRY,
ORANGE,
PLUM,
BELL,
MELON,
BAR;
}
It looks like the swithc expression is the "actual" slow machine, so you want to put a random int there. Something along the lines of switch(a).
Why? Think about how a slot machine works and then look at your code. The slot machine randomly picks a symbol for each spot (ie 1 fruit). In your code you have a case for each fruit. What is happening is you are representing each case with a number. So to determine which case, you need to pick a number. What number do you pick? Since its a slot machine you pick a random number. That is why you have a=random.nextInt();.
You don't put a test expression in a switch-statement. You put an integer value. In this case, it seems like you want a there.