Constructors and objects - java

So I just learned about Constructors. I wrote this program myself, and I want to incorporate constructors into this program(AS it could use it!). Also I get null instead of a symbol type but other than that the program runs fine(Thinking maybe constructors can fix the null).
My main issue currently is that I don't want to take out the class called "Options"(or is it called a method class?). But yet I still want to use the constructor, to get rid of "choice" and "getOperatives".
While I'm aware my "Options" class(Should it be capitalized), can just simply go in main, as it's only going to be used once, I'm focusing on understanding the concepts not so much it being robust(but still being robust).
//Call objects
Scanner scan = new Scanner(System.in);
css cssAccess = new css();
//Call Variables
int choice;
int x,y;
int total;
String type;
String str;
//Give Choices & Input Choice
choice = scan.nextInt();
//Get 2 itmes to operate on
System.out.println("Please enter two items to operate on");
x = scan.nextInt();
y = scan.nextInt();
//Pass in operatives AND then choice
cssAccess.getOperatives(x,y);
cssAccess.arithmeticDecision(choice);
//Grab total
total = cssAccess.answer();
//Grab type of operation user entered
type = cssAccess.arithmeticSymbol();
//Output Results
System.out.println(x + type + y + " = " + total);
And Here is the file with all my classes in it
public class css {
//Declare Variables
private int getChoice;
private int input1,input2;
private int total;
private String symbol;
int refchoice;
public void choice(int choice){
getChoice = choice;
}
public void getOperatives(int x, int y){
input1 = x;
input2 = y;
}
public void Options(){
System.out.println("Would you like to add(1)");
System.out.println("Would you like to subtract(2)");
System.out.println("Would you like to multiply(3)");
System.out.println("Would you like to Divide(4)");
System.out.println("Or would you like to find the remainder(5)");
}
public void arithmeticDecision(int choice){
choice = refchoice;
switch (refchoice){
case 5:total = input1 % input2;
break;
case 4:total = input1 / input2;
break;
case 3:total = input1 * input2;
break;
case 2:total = input1 - input2;
break;
case 1:total = input1 + input2;
break;
}
}
public int answer(){
return total;
}
public String arithmeticSymbol(){
switch (Integer.toString(refchoice)){
case "5":symbol = "%";
break;
case "4":symbol = "/";
break;
case "3":symbol = "*";
break;
case "2":symbol = "-";
break;
case "1":symbol = "+";
break;
}
return symbol;
}
}

Related

please check my Java homework, dialog boxes and variable type mismatches

The title says this is homework, I have been beating my head into the wall for hours, so please help. It works fine, at least the math part does, I work the conversion it worked just fine. I went to change the output dialog box to list what the ending unit was, instead of just listing the variable e.g. your lbs is the end. And not to allow negative starting weights.
Now I can't get the dialog box to not give me an error. (Lines 145 -148) I put in a sample dialog box using the Return option that doesn't work, but if I set it to a variable in my case test, it will work fine. He gave us starting code, I recopied his original code and that doesn't work. The next error I get is I wrote a method that takes two doubles and a char. When I call the function I pass it two doubles and a char it says it can't convert a string (Line 255).
This has been frustrating I over engineered this and now to have it not work is killing me. I don't understand how I can copy his original code in and it no longer works. Dialog boxes confuse me but I think I understand them.
return JOptionPane.showConfirmDialog(A)(null(B), display(C),0,1);
A is the call of the for the box what type
B is the object type my understanding its always call
C is the string, text message of the box
The last two got to do with the the icon and button displayed.
He got us started on eclipse, which said I had error in code where there none, I spent hours looking at them, they went away once I reloaded my code.
Please any thing would be helpful, but an example or corrected code (I know that is a lot) with explanations on why there are correct would be helpful. My husband knows java but not dialog boxes, so he can't help. And the method call looks right to both of us.
/*
* Uses: methods, dialog boxes, and a menu to convert weights
*
*/
import javax.swing.JOptionPane;
public class WeightCon {
char choices, choicee;
public static char menu() {
char choice;
int typeNum = 3;
boolean OK;
String prompt, results, title;
prompt = "Choose Starting Unit\n";
prompt += "A. Pounds\n";
prompt += "B. Kilograms\n";
prompt += "C. Stones\n";
prompt += "D. ounces\n";
prompt += "E. Netons\n";
prompt += "F.Grams\n";
prompt += "\n\nEnter the letter of your choice:";
title = "Weights";
do {
results = JOptionPane.showInputDialog(null,prompt,title, typeNum);
choice = results.toUpperCase().charAt(0);
if(choice >= 'A' && choice <= 'F') {
OK = true;
}
else {
OK = false;
title = "Not Valid Input!";
typeNum = 0;
}
}while(! OK);
return choice;
}
public static double LbstoKG(double k) {
return k * 0.453592;
}
public static double KtoLBS(double L) {
return L / 0.453592;
}
public static double LbstoStone(double S) {
return S / 14;
}
public static double LBStoOunce(double O) {
return O / .0625;
}
public static double LbstoNewton(double N) {
return N * 4.4482216282509;
}
public static double LBStoGarm(double G) {
return G / 0.00220462 ;
}
public static double KtoL(double L) {
return L / 0.453592;
}
public static double stoneToLbs(double L) {
return L * 14;
}
public static double ounceToLBS(double L) {
return L * .0625;
}
public static double NewtonToLBS(double L) {
return L / 4.4482216282509;
}
public static double GramtoLBS(double L) {
return L * 0.00220462 ;
}
//public static double
public static double getDouble(String prompt) {
boolean OK;
double val=0;
String temp, title = "Enter a double value";
int typeNum = 3;
do {
OK = true;
temp = JOptionPane.showInputDialog(null, prompt, title, typeNum);
try {
val = Double.parseDouble(temp);
}
catch(Exception e) {
OK = false;
title = "Error! Invalid input. Must be a double value";
typeNum = 0;
}
try {
val = Double.parseDouble(temp);
}
catch(Exception b) {
if( val < 0) {
title = "Error! Invalid input. Must be a positive double value";
typeNum = 0;
}
}while(! OK);
}while(! OK);
return val;
}
public static String outputResults(double start, double end, char choices){
int test;
String end1;
if(choices == 'A') {
end1 = "Your end weight is the following pounds: ";
} else if (choices == 'B') {
end1 = " Your end weight is the following kilograms: ";
} else if (choices == 'C') {
end1 = " Your end weight is the following stones: ";
} else if (choices == 'D') {
end1 = " Your end weight is the following ounces: ";
} else if (choices == 'E') {
end1 = " Your end weight is the following newtons: ";
} else if (choices == 'F') {
end1 = " Your end weight is the following grams: ";
} else {end1 = " ERROR ERROR UNDEFINDED ERROR PLEASE CONSOLT DOCUMENTATION";}
String endreal = String.valueOf(end);
String display = "" + end1 + endreal;
//int input =
test = JOptionPane.showConfirmDialog(null, display,0,1);
test = JOptionPane.showConfirmDialog(null, display);
return JOptionPane.showConfirmDialog(null, display);
return JOptionPane.showConfirmDialog(null, display,0,1);
}
//display += "Do again?";
//return JOptionPane.showConfirmDialog(null,"test",0,1);
//return JOptionPane.showConfirmDialog(null,display,0,1);}}
//return JOptionPane.showConfirmDialog(null, "test",0,1);}}
//}
//
public static void main(String[] args) {
double get;
double lbs=0,ounce=0,kgs=0, stone=0,newton=0,gram=0 ;
double temp,start, end;
char choice, choices;
int button;
//String end1;
start =-99;
end = -999;
get = 0;
temp = 0;
do {
choice = menu();
choices = choice;
switch(choice) {
case 'A':
get = getDouble("Enter pounds : ");
lbs = get;
start = get; //LbstoKG(get);
temp = kgs;
break;
case 'B':
get = getDouble("Enter kilograms : ");
kgs = get;
start = KtoL(get);
temp = lbs;
break;
case 'C':
get = getDouble("Enter Stones : ");
stone = get;
start = stoneToLbs(get);
temp = lbs;
break;
case 'D':
ounce = getDouble("Enter Ounces : ");
start = ounceToLBS(get);
temp = lbs;
break;
case 'E':
get= getDouble("Enter Newtons : ");
newton = get;
start = NewtonToLBS(get);
temp = lbs;
break;
case 'F':
get = getDouble("Enter grams : ");
gram = get;
start = GramtoLBS(get);
temp = lbs;
break;
}
//button = outputResults(get,get);
//} while(button == 0);
// do {
choice = menu();
switch(choice) {
case 'A':
//get = getDouble("Enter pounds : ");
//lbs = getDouble("Enter pounds : ");
//kgs = get;
end = start;
break;
case 'B':
//get = getDouble("Enter kilograms : ");
end = LbstoKG(start);
break;
case 'C':
//get = getDouble("Enter Stones : ");
//stone = get;
end = LbstoStone(start);
break;
case 'D':
//ounce = getDouble("Enter Ounces : ");
end = LBStoOunce(start);
break;
case 'E':
//get= getDouble("Enter Newtons : ");
end = LbstoNewton(start);
System.out.printf("Hello");
break;
case 'F':
//get = getDouble("Enter grams : ");
end = LBStoGarm(start);
break;
}
button = outputResults(end,start,choice);
} while(button == 0);
}}
After copying and pasting your code into my compiler, there were multiple errors.
First Mistake in outputResults(): Remove the 0, and the 1.
The method showConfirmDialog(Component, Object, String, int) in the type JOptionPane
is not applicable for the arguments (null, String, int, int)
Line:
test = JOptionPane.showConfirmDialog(null, display,0,1);
Correction:
test = JOptionPane.showConfirmDialog(null, display);
Second and Third Mistake also in outputResults(): You cannot return two objects. Also, your method returns a String.
return JOptionPane.showConfirmDialog(null, display);
return JOptionPane.showConfirmDialog(null, display,0,1); // 0, 1 again.
// The second return statement is dead code, and this also makes the first mistake again
Your method returns a String.
JOptionPane.showConfirmDialog(null, display); returns an int.
So in your method returning a String, if you return an int instead, it will be a compiler error. For example:
... String outputResults(...){
return JOptionPane.showConfirmDialog(null, display);
}
1 quick fix: change return type to int (method: String outputResults(double, double, char))
Fourth Mistake in main(): Fix your Third Mistake and ignore this fix.
int button = ...;
...
button = outputResults(end,start,choice); // Returns String, but button is an int
// Change button to a string?
// Integer.parseInt(outputResults(end,start,choice)); ?

Craps Project - Debugs for non apparent syntax errors

I'm making a bare-bones Craps simulator with Java on the Eclipse IDE, I'm having a terribly hard time debugging the things that don't seem to indicate any errors in syntax only during the compiling process.
I'm running into this issue when trying to assign a value to the first bet on the "table."
The Pass()method isn't operating as I expected it would, I don't have any immediate error messages however it does not want to compile past this point, which is only line 33 down on the main method.
char answer = keyboard.nextLine().toUpperCase().charAt(0); This line seems to be the largest hurdle in getting all of my methods to operate smoothly throughout.. from what I understand.
I do have a die class but that's proving to be a non issue so I didn't include it in this post.
EDIT: This is the entirety of the program as it stands. I've been tweaking left and right on either end to find the appropriate ways to compile this absolute mess.
Any input is much appreciated. Thank you in Advance.
import java.util.Scanner;
public class Craps {
//Declaring start value of balances
static double totalMoney = 0.00;
static double rollMoney = 0.00;
public static void main(String[] args) {
//Creating Die Objects
Die die1 = new Die();
Die die2 = new Die();
//Beginning of loop
do {
//Displaying the rules for the game
displayMenu();
//Array to hold both Dice and create total for the first roll
//as well as every roll there after
//Initialized 'purses' for the first bets
int dice[] = new int[2];
int intTotal = 0;
int total = 0;
int passBet = 2;
double pass = 0.00;
double dontPass = 0.00;
//Rolling Dice for the first time in the Round
die1.Roll();
dice[0] = die1.getValue();
die2.Roll();
dice[1] = die2.getValue();
intTotal = (dice[0] + dice[1]);
//Assigning Value to Pass/Don't Pass bets
do {
while(Pass() == true) {
try{
pass = getBet();
} catch(NumberFormatException nfe) {
System.out.println("Please answer in this numerical format (0.00)");
}
}
while(dontPass() == true) {
try{
dontPass = getBet();
} catch(NumberFormatException nfe) {
System.out.println("Please answer in this numerical format (0.00)");
}
}
//Display of each individual rolls
//Display of total
//Win-Loss-Continue Play check
switch(intTotal) {
case 7:
case 11:
rollMoney = (pass*passBet);
dontPass = 0.00;
System.out.println(dice[0] + " - " + dice[1]);
System.out.println("Very Nice! Pay the Man!");
System.out.println("Sorry Don't Pass line, better luck next time.");
System.out.println("You have made: " + pass);
System.out.println("Total Earnings: " + totalMoney);
case 2:
case 3:
case 12:
rollMoney = (dontPass*passBet);
pass = 0.00;
System.out.println(dice[0] + " - " + dice[1]);
System.out.println("Very Nice! Pay the Man!");
System.out.println("Sorry Pass line, better luck next time.");
System.out.println("You have made: " + dontPass);
System.out.println("Total Earnings: " + totalMoney);
case 4:
case 5:
case 6:
case 8:
case 9:
case 10:
//"Actual" Game of Craps
do {
double placeBet[] = {1.2, 1.5, 2.0};
int hardBet[] = {7, 9};
int hornBet[] = {15, 30};
//List<Double> place = new ArrayList<Double>();
//List<Double> hard = new ArrayList<Double>();
//List<Double> horn = new ArrayList<Double>();
double place[] = new double[6];
double hard[] = new double[4];
double horn[] = new double[4];
int pBetMax = 6;
int haBetMax = 4;
int hoBetMax = 4;
int pBets[] = new int[pBetMax];
int haBets[] = new int[haBetMax];
int hoBets[] = new int[hoBetMax];
//Gathering Place Bets w/ Location and Value
if(Place() == true) {
pBets = getPlace();
for(int pBetOffset = 1; pBetOffset <= pBetMax; pBetOffset++) {
switch(pBets[pBetOffset]) {
case 4:
place[0] += getBet();
case 5:
place[1] += getBet();
case 6:
place[2] += getBet();
case 8:
place[3] += getBet();
case 9:
place[4] += getBet();
case 10:
place[5] += getBet();
case 0:
break;
}
}
}
//Gathering Hardway Bets w/ Location and Value
if(Hard() == true) {
haBets = getHard();
for(int haBetOffset = 1; haBetOffset <= haBetMax; haBetOffset++) {
switch(haBets[haBetOffset]) {
case 4:
hard[0] += getBet();
case 6:
hard[1] += getBet();
case 8:
hard[2] += getBet();
case 10:
hard[3] += getBet();
case 0:
break;
}
}
}
//Gathering Horn Bets w/ Location and Value
if(Horn() == true) {
hoBets = getHorn();
for(int hoBetOffset = 1; hoBetOffset <= hoBetMax; hoBetOffset++) {
switch(hoBets[hoBetOffset]) {
case 2:
horn[0] += getBet();
case 3:
horn[1] += getBet();
case 11:
horn[2] += getBet();
case 12:
horn[3] += getBet();
case 0:
break;
}
}
}
//Redefining the roll separate from the intRoll
dice = new int[2];
die1.Roll();
dice[0] = die1.getValue();
die2.Roll();
dice[1] = die2.getValue();
total = (dice[0] + dice[1]);
if(intTotal != total) {
switch(total) {
case 11:
rollMoney += (horn[2] * hornBet[1]);
case 2:
rollMoney += (horn[0] * hornBet[2]);
case 3:
rollMoney += (horn[1] * hornBet[1]);
case 12:
rollMoney += (horn[3] * hornBet[2]);
case 4:
if(dice[0]== dice[1]) {rollMoney += (hard[0] * hardBet[1]);}
rollMoney += (place[0] * placeBet[3]);
case 5:
rollMoney += (place[1] * placeBet[2]);
case 6:
if(dice[0]== dice[1]) {rollMoney += (hard[1] * hardBet[2]);}
rollMoney += (place[2] * placeBet[1]);
case 8:
if(dice[0]== dice[1]) {rollMoney += (haBets[2] * hardBet[2]); }
rollMoney += (place[3] * placeBet[1]);
case 9:
rollMoney += (place[4] * placeBet[2]);
case 10:
if(dice[0]== dice[1]) {rollMoney += (haBets[3] * hardBet[1]);}
rollMoney += (place[5] * placeBet[3]);
case 7:
//Wiping the bets clean off the board
pass = 0.00;
place = new double[10];
hard = new double[10];
horn = new double[10];
//Redefining the initial roll for the game
intTotal = 0;
total = 0;
totalMoney += (dontPass * 2);
crapOut();
}
}
}while(crapOut() == true);
}
}while(keepPlaying() == true);
}while(displayMenu() == true);
}
/*
* This method determines if the player will continue after the round is over
*/
public static boolean keepPlaying() {
Scanner keyboard = new Scanner(System.in);
boolean playAgain = false;
System.out.println("");
System.out.println("Do you want to roll some more? (Y/N)");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
playAgain = answer == 'Y';
keyboard.close();
return playAgain;
}
public static boolean crapOut() {
Scanner keyboard = new Scanner(System.in);
boolean playAgain = false;
System.out.println("Crap Out! All Bets are OFF!");
System.out.println("After this roll you now have: $" + rollMoney + " on the board!");
System.out.println("Which bring's your grand total to.. $" + (totalMoney + rollMoney));
System.out.println("Care to make another wager?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
playAgain = answer == 'Y';
keyboard.close();
return playAgain;
}
/*
* This method will assign values to all the bets available to the player
*/
public static double getBet() {
System.out.println("How much would you like to bet?");
Scanner keyboard = new Scanner(System.in);
String bet = keyboard.nextLine();
float num;
num = Float.parseFloat(bet);
keyboard.close();
return num;
}
/*
* This method will ask if the player would like to Accept or Press their bet
*/
public static boolean pressBet(int bet) {
Scanner keyboard = new Scanner(System.in);
boolean press = false;
System.out.println("Press your bet? (Double your initial wager)");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
press = answer == 'Y';
bet = bet * 2;
keyboard.close();
return press;
}
/*
* Methods to check if play would like to place wager
* Methods to assign those bets to appropriate places on the table
*/
public static boolean Pass() {
Scanner keyboard = new Scanner(System.in);
boolean pass = false;
System.out.println("Would you like to make a Pass Line Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
pass = answer == 'y';
keyboard.close();
return pass;
}
public static boolean dontPass() {
Scanner keyboard = new Scanner(System.in);
boolean dontPass = false;
System.out.println("Would you like to make a Don't Pass Line Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
dontPass = answer == 'Y';
keyboard.close();
return dontPass;
}
public static boolean Place() {
Scanner keyboard = new Scanner(System.in);
boolean place = false;
System.out.println("Would you like to make a Place Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
place = answer == 'Y';
keyboard.close();
return place;
}
public static int[] getPlace() {
int counter = 1;
int max = 6;
Scanner keyboard = new Scanner(System.in);
int[] select = new int[6];
do {
System.out.println("Make selections from the numbers (4, 5, 6, 8, 9, 10), Enter 0 to exit.");
System.out.println("Enter bet and hit return for each selection.");
select[counter] = keyboard.nextInt();
counter++;
} while(counter <= max || select[counter] != 0);
keyboard.close();
return select;
}
public static boolean Horn() {
Scanner keyboard = new Scanner(System.in);
boolean horn = false;
System.out.println("Would you like to make a Pass Line Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
horn = answer == 'Y';
keyboard.close();
return horn;
}
public static int[] getHorn() {
int counter = 1;
int max = 4;
Scanner keyboard = new Scanner(System.in);
int[] select = new int[4];
do {
System.out.println("Make selections from the numbers (2, 3, 11, 12), Enter 0 to exit.");
System.out.println("Enter bet and hit return for each selection.");
select[counter] = keyboard.nextInt();
counter++;
} while(counter <= max || select[counter] != 0);
keyboard.close();
return select;
}
public static boolean Hard() {
Scanner keyboard = new Scanner(System.in);
boolean hard = false;
System.out.println("Would you like to make a Hardway Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
hard = answer == 'Y';
keyboard.close();
return hard;
}
public static int[] getHard() {
int counter = 1;
int max = 4;
Scanner keyboard = new Scanner(System.in);
int[] select = new int[4];
do {
System.out.println("Make a selection from the numbers (4 (2&2), 6 (3&3), 8(4&4), 10(5&5)");
System.out.println("Enter bet and hit return for each selection.");
select[counter] = keyboard.nextInt();
counter++;
} while(counter <= max || select[counter] != 0);
keyboard.close();
return select;
}
/*
* Method to display rules and parameters of game prior to playing
*/
public static boolean displayMenu() {
System.out.println("Welcome to the Crosby Casino!");
System.out.println("The Game is Craps, Rules Are:");
System.out.println("If a 7 or 11 is the first roll on the table,");
System.out.println("Pass bets get paid on the first roll!");
System.out.println("If a 2, 3, or 12 is the first roll on the table, ");
System.out.println("Don't pass bets get paid on the first roll!");
System.out.println("If any other value is rolled, the game begins..");
System.out.println("Pass bets believe whatever other value was rolled will appear before the next 7 does.");
System.out.println("Don't Pass bets believe that the 7 will appear before the initial roll's value is shown again.");
System.out.println("During the duration of the roll you can make up to 3 separate side bets");
System.out.println("'Place bets' - (2, 5, 6, 8, 9, 10) Which pay out every time these numbers appear following the initial roll");
System.out.println("'Hard bets' - (4, 6, 8, 10) Which has the most coverage of all potential outcomes");
System.out.println(" & 'Horn bets' - (2, 3, 11, 12) The best payout odds on the table");
System.out.println("The table minimum is $5.00 to play");
System.out.println("All side bet minimums are $1.00 to play");
Scanner keyboard = new Scanner(System.in);
boolean menu = false;
System.out.println("Would you like play?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
menu = answer == 'Y';
keyboard.close();
return menu;
}
}
Java arrays are 0-origin. Basically, that means that the first element in arrays have an index of 0, not 1, as your dice array shows. Thus, you need to replace dice[1] and dice[2] with dice[0] and dice[1], respectively.
EDIT Based on new info from comments:
This sounds like a new error than the AIOOBE that you previously described. The issue with your code is that you need to ensure that you use Scanner's hasNextLine() method before calling the nextLine() method. Essentially, you are calling nextLine() when there is no "next line", causing the NoSuchElementException.

My code won't run if values over four are entered

This code converts from meters to feet/inches/kilometers. Sorry, I know this is basic, I'm new to Java. When prompted for a number of meters, if 4 or over is entered it doesn't convert and ends the program. Does anyone know what I did wrong?
import javax.swing.JOptionPane;
public class Measurements
{
public static void main(String[] args)
{
// Have user make selection
String input;
int selectedNum; // number chosen
float numMeters; // number of meters
input = JOptionPane.showInputDialog("Enter a distance in meters.");
numMeters = Float.parseFloat(input);
menu();
selectedNum = Integer.parseInt(input);
// Selection results
if (selectedNum < 1 )
{ errorMessage(); }
if (selectedNum == 1)
{ showKilometers(numMeters); }
if (selectedNum == 2)
{ showInches(numMeters); }
if (selectedNum == 3)
{ showFeet(numMeters); }
if (selectedNum == 4)
{
exitSystem();
}
}
/** errorMessage method */
public static double errorMessage()
{
double selectedNum;
String input;
input = JOptionPane.showInputDialog("That is not a valid selection. Please enter 1, 2, 3, or 4.");
selectedNum = Integer.parseInt(input);
return selectedNum;
}
/** menu method */
public static String menu()
{
String input;
input = JOptionPane.showInputDialog("Choose a selection:\n1. Convert to kilometers\n2. Convert to inches\n3. Convert "
+ "to feet\n4. Quit the program.");
return input;
}
/** showKilometers method */
public static void showKilometers(double numMeters)
{
double result;
result = numMeters*.001;
JOptionPane.showMessageDialog(null, numMeters + " meters is " + result + " kilometers.");
}
/** showInches method */
public static void showInches(double numMeters)
{
double inches;
inches = numMeters*(39.37);
JOptionPane.showMessageDialog(null, numMeters + " meters is " + inches + " inches.");
}
/** showFeet */
public static void showFeet(double numMeters)
{
double awesome;
awesome = (3.281*numMeters);
JOptionPane.showMessageDialog(null, numMeters + " meters is " + awesome + " feet.");
}
public static void exitSystem()
{
System.exit(0);
}
}
The String input in menu() is a different variable from the String input in main.
The menu function should be returning the value for selectedNum to use. Once that fix is made,
menu();
selectedNum = Integer.parseInt(input);
should be changed to:
selectedNum = Integer.parseInt(menu());
The input return from menu() is not the input in main, the input in main is always refer to the input of "Enter a distance in meters.", that is the reason why when user enter number of meters >=4 the program either exit or show error. Besides, I would prefer using switch than if else for condition switching scenario;
public static void main(String[] args)
{
double numMeters = Double.parseDouble(JOptionPane.showInputDialog("Enter a distance in meters."));
switch(menu()) {
case 1:
showKilometers(numMeters);
break;
case 2:
showInches(numMeters);
break;
case 3;
showFeet(numMeters);
break;
case 4;
exitSystem();
break;
default;
errorMessage();
break;
}
}
just use this
selectedNum = menu();
instead of
menu();
selectedNum = Integer.parseInt(input);
since the menu() function is already return integer value, no need to parse it.
however you can use switch statement as in this code
switch (selectedNum){
case 1: showKilometers(numMeters);
case 2: showInches(numMeters);
case 3: showFeet(numMeters);
case 4: exitSystem();
default: errorMessage();
}

Why is case 2 printing when I enter 2?

I am working on a program that tracks items and their costs as you add them to you bag. I have switch statement to give options for 1. adding new items, 2. printing the totals, and 3. ending the program.
For some reason when I select case 1 it also prints the totals using my toString method. But I only have the toString method in case 2.
Can anyone explain why this would be happening?
Here is my main
import java.util.Scanner;
public class ShoppingBagTracker {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
float taxRate, cost;
int items, newItems, choice;
String receipt;
String menu = ("1. Add items" +
"2. Get receipt"
+ "3. Exit");
System.out.print("Enter the sales tax rate: ");
taxRate = in.nextFloat();
ShoppingBag myBag = new ShoppingBag(taxRate);
items = 0;
do{
System.out.println("What would you like to do?");
System.out.println(menu);
choice = in.nextInt();
switch(choice){
case 1:
System.out.print("Enter cost of item: ");
cost = in.nextFloat();
System.out.print("Enter number of items: ");
newItems = in.nextInt();
items = items + newItems;
myBag.place(items, cost);
myBag.getItems();
myBag.getCost();
myBag.getTotal();
myBag.getAverage();
case 2:
receipt = myBag.toString();
System.out.println(receipt);
case 3:
break;
default:
System.out.println("That is not an option");
}
}while(choice != 3);
}
}
Here is my Shopping Bag class
public class ShoppingBag {
public float taxRate;
public int items;
public float cost;
public float average;
public float totalCost;
public float finalCost;
public ShoppingBag(float taxRate)
{
this.taxRate = taxRate;
}
public void place(int newitems, float newcost)
{
items = newitems;
cost = newcost;
cost = items * cost;
}
public int getItems()
{
return items;
}
public float getCost()
{
return cost;
}
public float getTotal()
{
finalCost = cost + (cost * taxRate);
return finalCost;
}
public float getAverage()
{
average = finalCost/items;
return average;
}
#Override
public String toString()
{
return("Items: " + items + " Cost: " + cost + " Total cost: " + finalCost + " Average cost: " + average);
}
}
A switch case isn't restrict to execute one 'case'. It execute all code from the matching case down to a break; or to the end of the switch.
In your case add a break; before the case 2
You need to have break in switch-cases.
switch(something){
case 1:
// do something
break;
case 2:
//do something
break;
default:
// do something
break;
}
If there is no break, that will execute all cases here.
switch-cases in Java.
Conclusion.
If there is no return in cases, you should use break for every case.
Following case you don't need break.
switch (cases){
case "a":
return "a";
case "b":
return "b";
default:
return "default";
}
You need to add a break statement inside the case 1 body
case 1:
System.out.print("Enter cost of item: ");
cost = in.nextFloat();
System.out.print("Enter number of items: ");
newItems = in.nextInt();
items = items + newItems;
myBag.place(items, cost);
myBag.getItems();
myBag.getCost();
myBag.getTotal();
myBag.getAverage();
break;
Here is the official tutorial
You should either have a break for all the cases or have a return statements in all cases. Otherwise when Java will execute all the cases which are after the matching case.
swicth(urSwitch){
case 1:// logic
break; // or return something
case 2:// logic
break; // or return something
case 3:// logic
break; // or return something
}

Java calculator switch dont work

I can enter 2 numbers but when I enter an integer for "wahl" (the switch) the result is wrong.
import java.util.Scanner;
public class taschenrechner {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Bitte erste Zahl eingeben:");
int a = s.nextInt();
System.out.println("Bitte zweite Zahl eingeben:");
int b = s.nextInt();
System.out.println("1.+ \n 2.- \n 3.* \n 4. /");
int wahl = s.nextInt();
switch(wahl){
case 1:
addieren(a,b);
break;
case 2:
subtrahieren(a,b);
break;
case 3:
multiplizieren(a,b);
break;
case 4:
dividieren(a,b);
break;
}
System.out.println("Bye Bye World");
}
private static int addieren(int a, int b){
int c = a + b;
return c;
}
private static int subtrahieren(int a, int b){
int c = a - b;
return c;
}
private static int multiplizieren(int a, int b){
int c = a * b;
return c;
}
private static int dividieren(int a , int b){
int c = a / b;
return c;
}
}
Maybe some method leaks?
I wanted to do this with methods and the return function to practice a bit java.
Your methods return int, but you don't seem to use the result and call them as void instead.
Try testing in your switch cases with something like:
System.out.println(multiplizieren(a,b));
It will print the result to sdtout.
Also note that as per both Java and SO convention, code should all be in English (although it's quite clear in this case).
If you want to see the result, use the returned value from the methods in a new variable in main (say, result) or print out the result inside the methods using System.out.println() or something of the sort. For example like this:
int result = 0;
case 1:
result = addieren(a,b);
break;
case 2:
result = subtrahieren(a,b);
break;
case 3:
result = multiplizieren(a,b);
break;
case 4:
result = dividieren(a,b);
break;
}
System.out.println("Result = " + result);
you just return the result...
you have to print the result, too
int result = 0
switch(wahl){
case 1:
result = addieren(a,b);
break;
case 2:
result = subtrahieren(a,b);
break;
case 3:
result = multiplizieren(a,b);
break;
case 4:
result = dividieren(a,b);
break;
}
System.out.println(result)
If you are returning the result then you should put it in some valriable or can directly display by s.o.println
like...
switch(wahl){
case 1:
system.out.println(addieren(a,b));
or
int result = addieren(a,b)
system.out.println(result);
int result = 0
switch(wahl){
case 1:
result = addieren(a,b);
break;
case 2:
result = subtrahieren(a,b);
break;
case 3:
result = multiplizieren(a,b);
break;
case 4:
result = dividieren(a,b);
break;
}
//Print the result using a syso
System.out.println(result)
OK here are a couple of pointers that might be useful:
import java.util.Scanner;
// Class names typically start with a capital letter, good practice to get accustomed to
public class Taschenrechner {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Bitte erste Zahl eingeben:");
int a = s.nextInt();
System.out.println("Bitte zweite Zahl eingeben:");
int b = s.nextInt();
System.out.println("1.+ \n 2.- \n 3.* \n 4. /");
int wahl = s.nextInt();
switch(wahl){
case 1:
addieren(a,b); // <- nothing happens to the result!!
break;
case 2:
subtrahieren(a,b); // <- nothing happens to the result!!
break;
case 3:
multiplizieren(a,b); // <- nothing happens to the result!!
break;
case 4:
dividieren(a,b); // <- nothing happens to the result!!
break;
default: // <- always good to have a default in a switch
// warn user that invalid option is entered
}
System.out.println("Bye Bye World");
}
// dont need the integer "c" as you never use it locally.
private static int addieren(int a, int b){
retrun a + b;
}
private static int subtrahieren(int a, int b){
return a - b;
}
private static int multiplizieren(int a, int b){
return a * b;
}
private static int dividieren(int a , int b){
return a / b;
}
}
I suppose you made the 4 operation methods static, since you call it in main, and the compiler complains about static reference? If so, read a bit about what static means; and consider creating an instance of your calculator by:
supplying a constructor method, and
creating an instance of it in your main something like:
Taschenrechner t = new Taschenrechner();
t.addieren(a,b); //the methods don't need to be static anymore :)
Hope it helps
You can use this example
package com.alindal.calc;
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
System.out.println("Select an option : \n 1:Addition 2:Subtraction 3:Multiplication 4: Division");
// TODO Auto-generated method stub
Scanner read=new Scanner(System.in);
int x=read.nextInt();
switch(x)
{
case 1:
add();
break;
case 2:
sub();
break;
case 3:
multi();
break;
case 4:
div();
break;
default:
System.out.println("Invalid choice");
}
}
public static void add()
{
Scanner read=new Scanner(System.in);
System.out.println("Enter the values a and b");
int a=read.nextInt();
int b=read.nextInt();
int c=a+b;
System.out.println("The sum is "+c);
}
public static void sub()
{
System.out.println("Enter the values a and b");
Scanner read=new Scanner(System.in);
int a=read.nextInt();
int b=read.nextInt();
int c=a-b;
System.out.println("The difference is "+c);
}
public static void multi()
{
System.out.println("Enter the values a and b");
Scanner read=new Scanner(System.in);
int a=read.nextInt();
int b=read.nextInt();
int c=a*b;
System.out.println("The product is "+c);
}
public static void div()
{
System.out.println("Enter the values a and b");
Scanner read=new Scanner(System.in);
int a=read.nextInt();
int b=read.nextInt();
int c=a/b;
System.out.println("The division is "+c);
}
}

Categories