I'm working on a program and I don't understand what's wrong with the program, I've tried to make it work, but every time I would run it and put in an answer, it adds a zero to the answer. Help.
import javax.swing.JOptionPane;
public class Furniture
{
public static void main(String args[])
{
String response_1 = JOptionPane.showInputDialog(null, "Type of Table - 1)Pine Wood, 2)Oak, 3)Mahogany");
int type_of_wood = Integer.parseInt(response_1);
String response_2 = JOptionPane.showInputDialog(null, "Size of table - 4)Small, or 5)Large");
int size = Integer.parseInt(response_2);
int price_of_wood = 0;
int price_of_table = 0;
switch(type_of_wood)
{
case 1:
price_of_wood = 100;
break;
case 2:
price_of_wood = 225;
break;
case 3:
price_of_wood = 310;
break;
case 4:
price_of_table = 0;
break;
case 5:
price_of_table = 35;
break;
default:
JOptionPane.showMessageDialog(null, "Unknown Number entered.");
}
JOptionPane.showMessageDialog(null, "The price is " + price_of_wood + price_of_table + " dollars");
}
}
When you use variable like int, float etc. with String in println() for showing output they gets concatenated instead of getting added or whatever operation you try to do. So first evaluate your expression which is to output. Try this,
int price = price_of_wood + price_of_table;
JOptionPane.showMessageDialog(null, "The price is " + price + " dollars");
Related
I have been working on a code that registers students for courses. I was given a teachers copy and needed to write the code for the validateChoice method. I have it completed but I am still getting two errors. The program is recognizing 0 as a duplicate instead of an invalid course number, and is allowing the user to duplicate twice before throwing an invalid message. There should be no duplicates allowed. Any ideas on why this would happen? I have already turned this in because it runs correctly with the course codes I was given for the assignment, I just want to know for personal reference. Thanks!
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package u6a1_consoleregisterforcourse;
import java.util.Scanner;
/**
*
* #author omora
*/
public class U6A1_ConsoleRegisterForCourse {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Kim's Copy");
Scanner input = new Scanner(System.in);
//choice is the current menu selection
//firstChoice is the first menu selection mande by the user
//secondChoice is the second menu selection mande by the user
//thirdChoice is the third menu selection mande by the user
// a choice of 0 means the choice has not been made yet
int choice;
int firstChoice = 0, secondChoice = 0, thirdChoice = 0;
int totalCredit = 0;
String yesOrNo = "";
do {
choice = getChoice(input);
switch (ValidateChoice(choice, firstChoice, secondChoice, thirdChoice, totalCredit)) {
case -1:
System.out.println("**Invalid** - Your selection of " + choice + " is not a recognized course.");
break;
case -2:
System.out.println("**Invalid** - You have already registerd for this " + ChoiceToCourse(choice) + " course.");
break;
case -3:
System.out.println("**Invalid** - You can not register for more than 9 credit hours.");
break;
case 0:
System.out.println("Registration Confirmed for course " + ChoiceToCourse(choice) );
totalCredit += 3;
if (firstChoice == 0)
firstChoice = choice;
else if (secondChoice == 0)
secondChoice = choice;
else if (thirdChoice == 0)
thirdChoice = choice;
break;
}
WriteCurrentRegistration(firstChoice, secondChoice, thirdChoice);
System.out.print("\nDo you want to try again? (Y|N)? : ");
yesOrNo = input.next().toUpperCase();
} while (yesOrNo.equals("Y"));
System.out.println("Thank you for registering with us");
}
public static int getChoice(Scanner input) {
System.out.println("Please type the number inside the [] to register for a course");
System.out.println("[1]IT4782\n[2]IT4784\n[3]IT4786\n[4]IT4789\n[5]IT2230\n[6]IT3345\n[7]IT3349");
System.out.print("Enter your choice : ");
return (input.nextInt());
}
//This method validates the user menu selection
//against the given registration business rules
//it returns the following code based on the validation result
// -1 = invalid, unrecognized menu selection
// -2 = invalid, alredy registered for the course
// -3 = invalid, No more than 9 credit hours allowed
// 0 = menu selection is valid
public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {
// TO DO - Add Code to:
// Validate user menu selection (the int choice method argument)
// against the given registration business rules
int result = 0;
if (choice <=0 ||choice >7){
result = -1;
}
if(choice==firstChoice||choice == secondChoice||choice == thirdChoice) {
result = -2;
}
if(totalCredit == 3) {
result = 0;
}
if (totalCredit > 9) {
result = -3;
}
return result;
}
public static void WriteCurrentRegistration(int firstChoice, int secondChoice, int thirdChoice) {
if (firstChoice == 0)
System.out.println("Current course registration: { none } " );
else if (secondChoice == 0)
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) + " }" );
else if (thirdChoice == 0)
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) +
", " + ChoiceToCourse(secondChoice) + " }");
else
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) +
", " + ChoiceToCourse(secondChoice) + ", " + ChoiceToCourse(thirdChoice) + " }");
}
public static String ChoiceToCourse(int choice) {
String course = "";
switch (choice)
{
case 1:
course = "IT4782";
break;
case 2:
course = "IT4784";
break;
case 3:
course = "IT4786";
break;
case 4:
course = "IT4789";
break;
case 5:
course = "IT2230";
break;
case 6:
course = "IT3345";
break;
case 7:
course = "IT3349";
break;
default:
break;
}
return course;
}
}
My issue is that I can't seem to call the "RustySword" block from a "switch" in my main class. See below.
import java.util.Scanner;
public class Heart {
static int playerGold = 100;
static int oldHatPrice = 25;
static int canOfBeansPrice = 250;
static int rustySwordPrice = 125;
public static Scanner Economy = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Hi, Welcome to my store.\nWould you like to see my wares?");
String c = Economy.next();
switch (c) {
case "yes":
System.out.println("old hat: " + oldHatPrice +" gold\nRusty Sword: " + rustySwordPrice + " gold\nCan of beans: " + canOfBeansPrice + " gold");
String e =Economy.next();
switch (e) {
case "Rusty sword":
RustySword();
break;
default: System.out.println("I don't think you need that!");
}
}
}
public static void RustySword() {
System.out.println("Would you like to buy this rusty sword?\n Rusty sword: " + rustySwordPrice + "\n Your gold: " + playerGold);
String a = Economy.nextLine();
switch (a) {
case "yes":
if (playerGold >= rustySwordPrice) {
System.out.println("Here you go");
playerGold = playerGold - rustySwordPrice;
System.out.println("-Rusty Sword- added to inventory\n Gold remaining: " + playerGold);
}
else {
System.out.println("Sorry, you don't have enough gold!\ncome back when you have more.");}
break;
case "no":
System.out.println("Is there anything else I can do for you?");
String d = Economy.nextLine();
switch (d) {
case "no":
System.out.println("Thanks for shopping");
break;
}
break;
default: System.out.println("i'm not sure what your talking about!");
}
}
}
You are using next() to read the input that is reading only till space then the cursor is being placed in the same line after reading the input.
So the cursor will be at the end of the line \n if your input is only a single word e.g., yes in your case.
The end of the line will be consumed by following next() method. Hence your condition is not matching.
Use nextLine() to read the complete line and use it. You can look into this question
for more info.
I am trying to make a text based game. I am putting somethings I have learned to practice.
When you read about my problem you will probably be confused. My problem contains methods that have yet not been explained in what they do. This is so it does not get too confusing. Each piece of code will have a description of what methods it has and what they do.
My problem: I have a class named CharStartingPoint, this class is the main starting point to my game. Inside the class I call the choose(); method which is a method from class CharObe then the settingNPC(); and bbs(); methods are called, both of those methods are from CharWosna class. The bbs(); method just returns a boolean referenced, player1HasShieldBo, and prints out string player1HasShield. (player1HasShield and player1HasShieldBo are from class CharObe and player2HasShieldBo is from class CharWosna). When choose(); is called, and the player types yes to the question "Do you have a shield?", if the if statement sees if the user typed yes it will call a method named setPlayerShieldTrue(boolean HasSield); and pass player1HasShieldBo which sets player1HasShieldBo = true. If I type System.out.println(player1.player1HasShieldBo); and
System.out.println(player1.player1HasShield); from class CharStartingPoint, it prints out true and yes. Class CharStartingPoint has no problem accessing CharObe's variables. When CharWosna class tries accessing CharObe's variable, CharWosna can access them but they are not initialized, WHY????? for this problem to be seen, when method settingNPC(); is called, player2HasShieldBo is set to true if player2HasShieldBo is true. In this case player2HasShieldBo is set to false because class CharWosna accessed player1HasShieldBo from class CharObe, but it is not initialized although it had been initialized earlier. String player1HasShield prints out null when accessed from class CharWosna. WHY????
player1 is of type CharObe and has a constructor of CharObe.
player2 is of type CharWosna and has a constructor of CharWosna.
Here is my code by chunks and explained
Class CharObe:
The choose(); method: The choose method asks the user if they have a shield or not. If the user types no to the question, do you have a shield? the boolean player1HasShieldBo is set to false. If the user types yes, then inside the if statement the setPlayerShieldTrue(); method is called.
The setPlayerShieldTrue(boolean HasSield); method: this method takes in a boolean. Inside this boolean the local variable HasSield is set to true which then is assigned to player1HasShieldBo.
The returnIfHasShield(); method: this method just returns boolean player1HasShieldBo
import java.util.Scanner;
public class CharObe implements CharInterface {
String player1HasShield;
boolean player1HasShieldBo = false;
int player1ShieldLevel;
int player1ShieldHealth;
boolean valid = false;
Scanner keyBoard = new Scanner(System.in);
public void choose(){
do{
//asking the user if they have a shield or not
System.out.println("\ndo you have a shield? (if yes only type" +
"'yes' if no type 'no')");
System.out.print("Shield? yes or no? > ");
if(keyBoard.hasNext()){
player1HasShield = keyBoard.next();
if(player1HasShield.equalsIgnoreCase("yes")){
System.out.println("You have a SHIELD!!!");
setPlayerShieldTrue(player1HasShieldBo);
System.out.println("What is your shield Level? (Only" +
"numbers 1-5)");
do{
System.out.print("Shield level > ");
if(keyBoard.hasNextInt()){
player1ShieldLevel = keyBoard.nextInt();
if(player1ShieldLevel >= 1 && player1ShieldLevel <= 5){
valid = false;
}else{
System.out.println("PLEASE only numbers from 1-" +
" 5");
valid = true;
}
}else{
System.out.println("Only numbers are valid");
keyBoard.next();
valid = true;
}
}while(valid);
}else{
System.out.println("You did not type 'yes'"
+ " now you dont have a shield...");
player1ShieldLevel = 0;
valid = false;
}
}
}while(valid);
if(player1HasShieldBo){
switch(player1ShieldLevel){
case 1: player1ShieldHealth = 5; break;
case 2: player1ShieldHealth = 7; break;
case 3: player1ShieldHealth = 15; break;
case 4: player1ShieldHealth = 20; break;
case 5: player1ShieldHealth = 30; break;
}
}else{
player1ShieldHealth = 0;
}
if(player1HasShieldBo){
System.out.println(
"\nPlayer1's shield level: "+ player1ShieldLevel +
"\nplayer1's shield HP: " + player1ShieldHealth);
}else{
System.out.println(
"\nPlayer1's shield level: "+ player1ShieldLevel +
"\nplayer1's damage: " + player1Damage);
}
System.out.println("\nSetting player2's variables...");
}
public void setPlayerShieldTrue(boolean HasSield){
HasSield = true;
player1HasShieldBo = HasSield;
}
public boolean returnIfHasShield(){
return player1HasShieldBo;
}
}
Method settingNPC();, this method sets boolean player2HasShieldBo = true if what is returned from method returnIfHasShield(); is true. If what is returned is not true then player2HasShield will not be initialized and will stay false. That is the problem, although what is returned from returnIfHasShield(); is player1HasShieldBo equaled to true, it will always returns false when access by CharWosna class.
Method bbs();, this method prints out player1HasShieldBo and player1HasShield which come out to false and null because they are not initialized altough they had been earlier, why does this happen?
import java.util.Random;
public class CharWosna implements CharInterface{
//player2 variables
boolean player2HasShieldBo = true;
int player2ShieldLevel;
int player2ShieldHealth;
CharObe toGet = new CharObe();
public void settingNPC(){
if(toGet.returnIfHasShield()){
player2HasShieldBo = true;
player2ShieldLevel = toGet.player1ShieldLevel;
player2ShieldHealth = toGet.player1ShieldHealth;
System.out.println("Wosna's shield level: " + player2ShieldLevel +
"\nWosna's shield health: " + player2ShieldHealth
);
}else{
player2ShieldHealth = 0;
System.out.println("To have a fair fight, Wosna, like you, will"
+ "not have a shield.");
}
}
public void bbs(){
System.out.println(toGet.player1HasShieldBo + " " +
toGet.player1HasShield);
}
}
Class CharStarting point, this class calls all methods
I found out the reason that CharObe's variable are initialized and can be accessed nicely in this class, it's because this class calls the choose(); method.
public class CharStartingPoint {
public static void main(String[] args) {
System.out.println("Welcome! Fellow traveler.");
System.out.println("please input proper information in order to"
+ procceed to fight.\n");
CharObe player1 = new CharObe();
CharWosna player2 = new CharWosna();
player1.choose();
player2.settingNPC();
player2.bbs();
System.out.println(player1.player1HasShieldBo);
System.out.println(player1.player1HasShield);
}
}
Interface CharInterface, this is not yet used.
public interface CharInterface {
int hurt(int curHealth, int hurting);
int damage(int hitDamage);
int shield(int shieldHealth, int shielLevel);
}
*Another problem is when i create an object in class CharObe, it straight up gives me a java.lang.StackOverflowError, why is that. *
I dont know why I have all these problems. I may just have somethings that are very simple that have been messing up my program, I dont know.
Things I have tried
-directly accessing the boolean player1HasShieldBo from class CharWosna
-creating another boolean having it have the value of player1HasShieldBo(when player1HasShieldBo equaled to true)
-initializing player1HasShieldBo from class CharObe (did not turn out as wanted, it always equaled true)
if you want to see all my code here it is.
insterface
public interface CharInterface {
int hurt(int curHealth, int hurting);
int damage(int hitDamage);
int shield(int shieldHealth, int shielLevel);
}
class CharStartingPoint
public class CharStartingPoint {
public static void main(String[] args) {
System.out.println("Welcome! Fellow traveler.");
System.out.println("please input proper information in order to"
+ " procceed to fight.\n");
CharObe player1 = new CharObe();
CharWosna player2 = new CharWosna();
player1.choose();
player2.settingNPC();
player2.bbs();
System.out.println(player1.player1HasShieldBo);
System.out.println(player1.player1HasShield);
}
}
class CharObe
import java.util.Scanner;
public class CharObe implements CharInterface {
int player1Level;
int player1Damage;
int player1Health;
String player1HasShield;
boolean player1HasShieldBo = false;
int player1ShieldLevel;
int player1ShieldHealth;
boolean valid = false;
Scanner keyBoard = new Scanner(System.in);
CharObe f = new CharObe();
//Letting the user pick the players level and whether it has a shield or
not.
public void choose(){
System.out.println("what is Your player level? (number from 1-20)");
do{
//asking user for the level of their player
System.out.print("Enter level here > ");
if(keyBoard.hasNextInt()){
player1Level = keyBoard.nextInt();
if(player1Level >= 1 && player1Level <= 20){
valid = false;
}else{
System.out.println("Enter a number between 1 and 20!");
valid = true;
}
}else{
System.out.println("Only numbers are valid");
keyBoard.next();
valid = true;
}
}while(valid);
do{
//asking the user if they have a shield or not
System.out.println("\ndo you have a shield? (if yes only type" +
"'yes' if no type 'no')");
System.out.print("Shield? yes or no? > ");
if(keyBoard.hasNext()){
player1HasShield = keyBoard.next();
if(player1HasShield.equalsIgnoreCase("yes")){
System.out.println("You have a SHIELD!!!");
setPlayerShieldTrue(player1HasShieldBo);
System.out.println("What is your shield Level? (Only" +
"numbers 1-5)");
do{
System.out.print("Shield level > ");
if(keyBoard.hasNextInt()){
player1ShieldLevel = keyBoard.nextInt();
if(player1ShieldLevel >= 1 && player1ShieldLevel <= 5){
valid = false;
}else{
System.out.println("PLEASE only numbers from 1-5");
valid = true;
}
}else{
System.out.println("Only numbers are valid");
keyBoard.next();
valid = true;
}
}while(valid);
}else{
System.out.println("You did not type 'yes'"
+ " now you dont have a shield...");
player1ShieldLevel = 0;
valid = false;
}
}
}while(valid);
switch(player1Level){
case 1: player1Health = 100; player1Damage = 10; break;
case 2: player1Health = 105; player1Damage = 11; break;
case 3: player1Health = 110; player1Damage = 12; break;
case 4: player1Health = 80; player1Damage = 20; break;
case 5: player1Health = 100; player1Damage = 15; break;
case 6: player1Health = 150; player1Damage = 5; break;
case 7: player1Health = 115; player1Damage = 17; break;
case 8: player1Health = 130; player1Damage = 20; break;
case 9: player1Health = 135; player1Damage = 15; break;
case 10: player1Health = 140; player1Damage = 23; break;
case 11: player1Health = 160; player1Damage = 17; break;
case 12: player1Health = 150; player1Damage = 28; break;
case 13: player1Health = 180; player1Damage = 15; break;
case 14: player1Health = 155; player1Damage = 30; break;
case 15: player1Health = 115; player1Damage = 40; break;
case 16: player1Health = 200; player1Damage = 20; break;
case 17: player1Health = 250; player1Damage = 35; break;
case 18: player1Health = 1000; player1Damage = 67; break;
case 19: player1Health = 550; player1Damage = 130; break;
case 20: player1Health = 9999; player1Damage = 479; break;
}
if(player1HasShieldBo){
switch(player1ShieldLevel){
case 1: player1ShieldHealth = 5; break;
case 2: player1ShieldHealth = 7; break;
case 3: player1ShieldHealth = 15; break;
case 4: player1ShieldHealth = 20; break;
case 5: player1ShieldHealth = 30; break;
}
}else{
player1ShieldHealth = 0;
}
if(player1HasShieldBo){
System.out.println(
"\nPlayer1's level: " + player1Level +
"\nPlayer1's Health: " + player1Health +
"\nplayer1's damage: " + player1Damage +
"\nPlayer1's shield level: "+ player1ShieldLevel +
"\nplayer1's shield HP: " + player1ShieldHealth);
}else{
System.out.println(
"\nPlayer1's level: " + player1Level +
"\nPlayer1's Health: " + player1Health +
"\nPlayer1's shield level: "+ player1ShieldLevel +
"\nplayer1's damage: " + player1Damage);
}
System.out.println("\nSetting player2's variables...");
}
public void setPlayerShieldTrue(boolean HasSield){
HasSield = true;
player1HasShieldBo = HasSield;
}
public boolean returnIfHasShield(){
return player1HasShieldBo;
}
#Override
public int hurt(int curHealth, int hurting) {
return curHealth;
}
#Override
public int damage(int hitDamage) {
return hitDamage;
}
#Override
public int shield(int shieldHealth, int shielLevel) {
return 0;
}
}
class CharWosna
import java.util.Random;
public class CharWosna implements CharInterface{
//player2 variables
int player2Level;
int[] player2Damage = {15, 45, 67, 100, 5, 25, 1000};//array
int player2Health[] = {100, 50, 1000, 550, 250, 99, 600};//array
boolean player2HasShieldBo = true;
int player2ShieldLevel;
int player2ShieldHealth;
//CharObe object created for acquiring CharObe's variables in that class
CharObe toGet = new CharObe();
//ran is going to be used to access damage and health randomly
Random ran = new Random();
public void settingNPC(){
//LEVEL, HEALTH, and DAMAGE//
player2Level = ran.nextInt(6) + 1;
System.out.println("\n> Wosna's stats <");
System.out.println(
"\nWosna's level: " + player2Level +
"\nWosna's health: " + player2Health[player2Level] +
"\nWosna's damage: " + player2Damage[player2Level]
);
if(toGet.returnIfHasShield()){
player2HasShieldBo = true;
player2ShieldLevel = toGet.player1ShieldLevel;
player2ShieldHealth = toGet.player1ShieldHealth;
System.out.println("Wosna's shield level: " + player2ShieldLevel +
"\nWosna's shield health: " + player2ShieldHealth
);
}else{
player2ShieldHealth = 0;
System.out.println("To have a fair fight, Wosna, like you, will" +
"not have a shield.");
}
}
public void bbs(){
System.out.println(toGet.player1HasShieldBo + " " +
toGet.player1HasShield);
}
#Override
public int hurt(int curHealth, int hurting) {
return 0;
}
#Override
public int damage(int hitDamage) {
return 0;
}
#Override
public int shield(int shieldHealth, int shielLevel) {
return 0;
}
}
Thank you
First thing, Your code will work for setting the boolean. But you have some mistakes.
The stackOverflow is caused since you create a object of CharObe within the same class as a attribute. So for creating a CharObe object it needs to create a CharObe and so on...
the culprit line: on CharObe class
CharObe f = new CharObe();//remove this
Second thing, you cant just create an object of CharObe in CharWosna just to read the attributes.
This code is culprit too:
//CharObe object created for acquiring CharObe's variables in that class
CharObe toGet = new CharObe();
Instead try passing the player1 object when creating player2 in the constructor.
like this in CharWonsa:
//CharObe object created for acquiring CharObe's variables in that class
CharObe toGet;
public CharWosna(CharObe obe) {
toGet=obe;
}
And finally in the class CharStartingPoint, create objects like this:
CharObe player1 = new CharObe();
CharWosna player2 = new CharWosna(player1);
Another better way is that you maintain a GameContext class seperately and have all the necessary data like players there, and access from there.
You're welcome. Next time be precise with what you ask.
I've spent hours on this program trying to figure out how to repeat the main menu to show until the user write 3 (to quit the program).
The program asks the user to enter 2 integer numbers, then Main menu shows to choose from 3 options.
I chose the do while loop to force it show at least once, but i don't know what's my mistake?
package javaapplication33;
import static java.lang.System.exit;
import java.util.Scanner;
public class JavaApplication33 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter two numbers: ");
int n1 = input.nextInt();
int n2 = input.nextInt();
int multb = n1 * n2;
int optionn = showMenu();
do {
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
showMenu();
}// End of switch statement
} while (optionn == 3);
System.out.println("Thank you. Good Bye.");
}
public static int showMenu() {
int optionn = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Main Menu:");
System.out.println("--------------");
System.out.println("1.Add the numbers");
System.out.println("2.Multiply the numbers");
System.out.println("3.Quit");
System.out.println("--------------");
System.out.println("Enter your choice:");
optionn = keyboard.nextInt();
return optionn;
}
You could consider just a while loop, instead of a do-while.
int optionn = 0;
while (optionn != 3)
{
optionn = showMenu();
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
}
}
Additionally, there's no reason to clear out your optionn variable in your showMenu method.
try this
do {
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
showMenu();
}// End of switch statement
int optionn = showMenu();//SHOWS THE MENU AGAIN
} while (optionn == 3);
System.out.println("Thank you. Good Bye.");
Your showmenu() method isnt in your while that why i dosent repeat
The two lines of code that needed fixing - have comments, see below:
do {
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
}// End of switch statement
optionn = showMenu(); // <--- changed
} while (optionn != 3); // <--- changed
A couple of mistakes.
First you should be getting the user input inside the do/while loop. Just move your optionn=showMenu() inside the do (That way you can show the options again and allow the user to choose again).
Second you want to keep on looping while optionn!=3 instead of optionn==3 (You want to continue looping if the user doesn't want to exit).
I would also not use exit(0) and also move your exit print statement to inside the loop (So you print it before you exit your function). Something like this:
int n1 = input.nextInt();
int n2 = input.nextInt();
int multb = n1 * n2;
int optionn;
do {
optionn = showMenu(); //Allow user to select from menu every iteration
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
System.out.println("Thank you. Good Bye."); //Moved from the bottom
return; //I would use return instead of the exit(0) here.
//exit(0);
default:
System.out.println("Sorry, please enter valid Option");
showMenu();
}// End of switch statement
} while (optionn != 3); //Make sure this is != not ==
Hope this helps!
Having trouble with this the whole day. Please help me. I can't get the problem to display
The output shows
PROBLEM NUMBER 1
Answer:0
Correct....
PROBLEM NUMBER 2
Answer:1
Wrong....
It must show:
PROBLEM NUMBER 1
10 + 11 = ?
Answer: 21
Correct...*/
import java.util.Random;
import java.util.*;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.lang.Math;
public class MathIsSuperFun1{
Scanner input = new Scanner(System.in);
int correctAnswers;
int randomNum1;
int randomNum2;
int choice;
int corrrectAnswers, wrongAnswers;
String playerName ="";
int operation;
int userAnswer;
int correctAnswer = 0;
int userRemainder, correctRemainder;
int x = 0;
int temporaryNum1, temporaryNum2;
int range;
int randomNumber;
public static void main (String args[]){
MathIsSuperFun1 lab = new MathIsSuperFun1();
lab.init();
}
public void init(){
getName();
pickDifficulty();
pickOperation();
for(int x = 0; x < 10; x++)
{
System.out.println("\t\t\t~~~~~~~PROBLEM NUMBER" + (x + 1) + "~~~~~~~~");
assignNum();
getProblem();
checkAnswer();
}
}
//GET PLAYER NAME USING PANE
public static String getName(){
String playerName;
playerName = JOptionPane.showInputDialog(null, "Welcome!\nEnter your name and press OK.", "Math Is Super Fun!", JOptionPane.QUESTION_MESSAGE);
System.out.println("Do your best," + playerName + "!");
return playerName;
}
//GET PROBLEM BASED ON OPERATION
public void getProblem(){
switch(operation){
case 1:
System.out.println(randomNum1 + "+" + randomNum2 + "= ?\n");
correctAnswer = randomNum1 + randomNum2;
break;
case 2:
System.out.println(randomNum1 + "-" + randomNum2 + "= ?\n");
correctAnswer = randomNum1-randomNum2;
break;
case 3:
System.out.println(randomNum1 + "*" + randomNum2 + "= ?\n");
correctAnswer = randomNum1*randomNum2;
break;
case 4:
System.out.println(randomNum1 + "/" + randomNum2 + "= ?\n");
correctAnswer = randomNum1/randomNum2;
correctRemainder = randomNum1%randomNum2;
break;
}
System.out.print("Answer: ");
userAnswer = input.nextInt();
if(operation == 4){
System.out.print("Remainder: ");
userRemainder = input.nextInt();
}
return 0;
}
//PICK DIFFICULTY USING DIALOG
public void pickDifficulty(){
int choice = 0;
System.out.println("1 - Child's Play\n2 - No Sweat\n3 - Bitter\n4 - Cold-blooded\n5 - Brutal\n6 - Genius");
choice = input.nextInt();
}
//PICK OPERATIONS
public void pickOperation(){
int operation = 0;
System.out.println("1 - Addition\n2 - Subtraction\n3 - Multiplication\n4 - Division ");
operation = input.nextInt();
}
//GET NUMBER RANGE BASED ON DIFFICULTY
public int numberRange(){
int range = 0;
switch(choice){
case 1:
range = 100;
break;
case 2:
range = 1000;
break;
case 3:
range = 10000;
break;
case 4:
range = 100000;
break;
case 5:
range = 1000000;
break;
case 6:
range = 10000000;
break;
}
return range;
}
//GET CORRECT RANDOM RESPONSE USING CASE SWITCH BASED ON GETRANDOM METHOD
public void correctResponse(){
String responseCorrect = "";
switch (getRandom(5)){
case 1:
responseCorrect = "Correct. Keep up the good work!";
break;
case 2:
responseCorrect = "Correct. Keep aiming higher!";
break;
case 3:
responseCorrect = "Correct. Well done!";
break;
case 4:
responseCorrect = "Correct. Nice work!";
break;
case 5:
responseCorrect = "Correct. We're almost there!";
break;
}
System.out.println(responseCorrect);
correctAnswers += 1;
}
//GET WRONG RANDOM RESPONSE USING CASE SWITCH BASED ON GETRANDOM METHOD
public String wrongResponse(){
String responseWrong = "";
switch (getRandom(5)){
case 1:
responseWrong = "Wrong. Don't give up!";
break;
case 2:
responseWrong = "Wrong. You can do it!";
break;
case 3:
responseWrong = "Wrong. Try again puny human!";
break;
case 4:
responseWrong = "Wrong. You must be really weak at math!";
break;
case 5:
responseWrong = "Wrong. I pity you!";
break;
}
System.out.println(responseWrong);
System.out.println("The correct answer is:" + correctAnswer);
if(operation == 4)
System.out.println("Correct Remainder: " + correctRemainder);
return responseWrong;
}
public void checkAnswer(){
if(operation != 4 && userAnswer == correctAnswer){
correctResponse();
}
else if(operation == 4 && userAnswer == correctAnswer && userRemainder == correctRemainder){
correctResponse();
}
else{
wrongResponse();
}
}
public void assignNum(){
int temporaryNum1 = getRandom(numberRange());
int temporaryNum2 = getRandom(numberRange());
while(operation == 4 && temporaryNum1 == 0){
temporaryNum1 = getRandom(numberRange());
}
while(operation == 4 && temporaryNum2 == 0){
temporaryNum2 = getRandom(numberRange());
}
if(temporaryNum1 > temporaryNum2)
{
randomNum1 = temporaryNum1;
randomNum2 = temporaryNum2;
}
else
{
randomNum1 = temporaryNum2;
randomNum2 = temporaryNum1;
}
}
public int getRandom(int range){
randomNumber = (int)Math.floor((Math.random()*range)+1);
return randomNumber;
}
}
The reason your questions are not outputting is simple.
public void pickOperation(){
int operation = 0;
System.out.println("1 - Addition\n2 - Subtraction\n3 - Multiplication\n4 - Division ");
operation = input.nextInt();
}
You are creating a local variable, operation, and assigning the input value to it. This means that the field, operation, is never set, so when it comes to the switch statement in your getProblem method, it doesn't output anything because it doesn't match the switch statement.
To fix this, simply remove the int operation = 0; declaration.
Edit
Just noticed the same problem with your pickDifficulty method. I would strongly recommend you have a look at this tutorial on scope in Java.
Explanation of your Problem
Okay. So let's look at your code:
public void pickOperation(){
int operation = 0;
// Declare an int, called 'operation'.
System.out.println("1 - Addition\n2 - Subtraction\n3 - Multiplication\n4 - Division ");
// Set the newly declared value to an int from the keyboard.
operation = input.nextInt();
}
As soon as this method is finished, the value inside operation is destroyed. The reason why it isn't staying in your field int operation, is because you declared a more local operation variable. By removing the int operation = 0; at the start of this method, you force the JVM to look for the next available variable named operation in your class, which is in the field. That's why, when you remove the first assertion statement, your value for operation will stick around.
the problem is : int operation = 0; you need to take the value of the operation in operation variable which you create it in Main
Try this :
import java.util.Random;
import java.util.*;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.lang.Math;
public class Main {
Scanner input = new Scanner(System.in);
int correctAnswers;
int randomNum1;
int randomNum2;
int choice;
int corrrectAnswers, wrongAnswers;
String playerName = "";
int operation;
int userAnswer;
int correctAnswer = 0;
int userRemainder, correctRemainder;
int x = 0;
int temporaryNum1, temporaryNum2;
int range;
int randomNumber;
public static void main(String args[]) {
Main lab = new Main();
lab.init();
}
public void init() {
getName();
pickDifficulty();
pickOperation();
for (int x = 0; x < 10; x++) {
System.out.println("\t\t\t~~~~~~~PROBLEM NUMBER" + (x + 1) + "~~~~~~~~");
assignNum();
getProblem();
getAnswers();
checkAnswer();
}
}
//GET PLAYER NAME USING PANE
public static String getName() {
String playerName;
playerName = JOptionPane.showInputDialog(null, "Welcome!\nEnter your name and press OK.", "Math Is Super Fun!", JOptionPane.QUESTION_MESSAGE);
System.out.println("Do your best," + playerName + "!");
return playerName;
}
//GET PROBLEM BASED ON OPERATION
public void getProblem() {
switch (operation) {
case 1:
System.out.println(randomNum1 + "+" + randomNum2 + "= ?\n");
correctAnswer = randomNum1 + randomNum2;
break;
case 2:
System.out.println(randomNum1 + "-" + randomNum2 + "= ?\n");
correctAnswer = randomNum1 - randomNum2;
break;
case 3:
System.out.println(randomNum1 + "*" + randomNum2 + "= ?\n");
correctAnswer = randomNum1 * randomNum2;
break;
case 4:
System.out.println(randomNum1 + "/" + randomNum2 + "= ?\n");
correctAnswer = randomNum1 / randomNum2;
correctRemainder = randomNum1 % randomNum2;
break;
}
System.out.print("Answer: ");
userAnswer = input.nextInt();
if (operation == 4) {
System.out.print("Remainder: ");
userRemainder = input.nextInt();
}
// return 0;
}
//PICK DIFFICULTY USING DIALOG
public void pickDifficulty() {
System.out.println("1 - Child's Play\n2 - No Sweat\n3 - Bitter\n4 - Cold-blooded\n5 - Brutal\n6 - Genius");
choice = input.nextInt();
}
//PICK OPERATIONS
public void pickOperation() {
System.out.println("1 - Addition\n2 - Subtraction\n3 - Multiplication\n4 - Division ");
operation = input.nextInt();
}
//GET NUMBER RANGE BASED ON DIFFICULTY
public int numberRange() {
int range = 0;
switch (choice) {
case 1:
range = 100;
break;
case 2:
range = 1000;
break;
case 3:
range = 10000;
break;
case 4:
range = 100000;
break;
case 5:
range = 1000000;
break;
case 6:
range = 10000000;
break;
}
return range;
}
//GET CORRECT RANDOM RESPONSE USING CASE SWITCH BASED ON GETRANDOM METHOD
public void correctResponse() {
String responseCorrect = "";
switch (getRandom(5)) {
case 1:
responseCorrect = "Correct. Keep up the good work!";
break;
case 2:
responseCorrect = "Correct. Keep aiming higher!";
break;
case 3:
responseCorrect = "Correct. Well done!";
break;
case 4:
responseCorrect = "Correct. Nice work!";
break;
case 5:
responseCorrect = "Correct. We're almost there!";
break;
}
System.out.println(responseCorrect);
correctAnswers += 1;
}
//GET WRONG RANDOM RESPONSE USING CASE SWITCH BASED ON GETRANDOM METHOD
public String wrongResponse() {
String responseWrong = "";
switch (getRandom(5)) {
case 1:
responseWrong = "Wrong. Don't give up!";
break;
case 2:
responseWrong = "Wrong. You can do it!";
break;
case 3:
responseWrong = "Wrong. Try again puny human!";
break;
case 4:
responseWrong = "Wrong. You must be really weak at math!";
break;
case 5:
responseWrong = "Wrong. I pity you!";
break;
}
System.out.println(responseWrong);
System.out.println("The correct answer is:" + correctAnswer);
if (operation == 4) {
System.out.println("Correct Remainder: " + correctRemainder);
}
return responseWrong;
}
public void checkAnswer() {
if (operation != 4 && userAnswer == correctAnswer) {
correctResponse();
} else if (operation == 4 && userAnswer == correctAnswer && userRemainder == correctRemainder) {
correctResponse();
} else {
wrongResponse();
}
}
public void assignNum() {
int temporaryNum1 = getRandom(numberRange());
int temporaryNum2 = getRandom(numberRange());
while (operation == 4 && temporaryNum1 == 0) {
temporaryNum1 = getRandom(numberRange());
}
while (operation == 4 && temporaryNum2 == 0) {
temporaryNum2 = getRandom(numberRange());
}
if (temporaryNum1 > temporaryNum2) {
randomNum1 = temporaryNum1;
randomNum2 = temporaryNum2;
} else {
randomNum1 = temporaryNum2;
randomNum2 = temporaryNum1;
}
}
public int getRandom(int range) {
randomNumber = (int) Math.floor((Math.random() * range) + 1);
return randomNumber;
}
private void getAnswers() {
////////////////Not yet implemented";
}
}