I was wondering how I should initialize int c from the switch statement. I can't figure out how to "extract" the random switch-argument into the final answer. I am a beginner so maybe I am missing something obvious here. Here is the code that I have so far:
import java.util.*;
public class whileTest{
public static void main (String args[]){
Scanner sc = new Scanner(System.in);
String a;
do{
String operatorSwitch;
int b;
int c;
Random number = new Random();
int d = number.nextInt(100) +1;
int e = number.nextInt(100) +1;
Random operatorChoice = new Random();
int operator = operatorChoice.nextInt(4);
switch (operator){
case 0: operatorSwitch= "+";
c = d+e;
break;
case 1: operatorSwitch= "-";
c = d-e;
break;
case 2: operatorSwitch= "*";
c = d*e;
break;
case 3: operatorSwitch= "/";
c = d/e;
break;
default: operatorSwitch= "";
}
System.out.println("What is: "+d+operatorSwitch+e+"?");
b = sc.nextInt();
if(b!=c)
System.out.println("Wrong answer! Right answer is: "+c);
else{if(b==c)
System.out.println("Right answer!"+c);
}
System.out.println("Continue? y/n");
a = sc.next();
}while(a.equals("y"));
}
}
As a practice, unless you have a good reason not too, you should always explicitly initialize your variables. In this case you want to change this:
String operatorSwitch;
int b;
int c;
To this:
String operatorSwitch = null;
int b = 0;
int c = 0;
The problem with your current code is a compilation one, due to the variable 'c' possibly not being initialized.
Not sure how pretty you wish to make this but you could write an Operator interface with anonymous subclasses and pick a random index from those.
interface Operator{
public int operateOn( int a, int b );
public char getDisplayChar();
}
Operator[] operators = {new Operator(){
public int operateOn(int a, int b){
return a + b;
}
public char getDisplayChar(){
return '+';
}
}, new Operator(){
public int operateOn(int a, int b){
return a - b;
}
public char getDisplayChar(){
return '-';
}
} // etc.
};
Related
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)); ?
I am in a low-level java class where I need to make an app using java and JavaScript. I have decided to create a game that creates a random equation using addition, subtraction, multiplication, and division. the trouble I am having is that my equation is created in the form of a string and I need to be able to calculate the answer to compare it to the users answer. I thought I had a descent solution to my issue but I keep getting some issues. can you help? my code is below:
import java.util.*;
public class GameClient {
private static Stack<String> operations;
private static Stack<Integer> numbers;
private static String[] tokens;
private static int i;
private static Stack<String> subAdd;
private static Stack<Integer> restOfNumbers;
public static void main(String[] args) {
Random variable = new Random();
int numberOfVariables = variable.nextInt(5)+2; //determines length of equation
String equation = "";
equation = equationGenerator(equation, numberOfVariables, variable);
System.out.println(equation);
System.out.print(calculateAnswer(equation));
}
public static String equationGenerator(String equation, int numberOfVariables, Random variable){
int operation;
int var;
var = variable.nextInt(10)+1;
equation += var;
operation = variable.nextInt(4)+1;
if(numberOfVariables == 1){
equation += " = ";
return equation;
}
if(operation == 1)
{
equation += " + ";
}
else if(operation == 2)
{
equation += " - ";
}
else if(operation == 3)
{
equation += " / ";
}
else if(operation == 4)
{
equation += " * ";
}
return equationGenerator(equation, numberOfVariables-1, variable);
}
public static int calculateAnswer(String equation){
String delims = "[ ]+";
tokens = equation.split(delims);
for(i=0; i< tokens.length; i++) //does all multiplication and division first leaving just addition and subtraction
switch(tokens[i]){
case "0": case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":
int number = Integer.parseInt(tokens[i]);
popOrPush(number);
break;
case "*": case "/": case "+": case "-":
popOrPush(tokens[i], tokens);
}
while(!numbers.empty()){ //flips number and operation stacks to do addition and subtraction in correct order
restOfNumbers.push(numbers.pop());
}
while(!operations.empty()){
subAdd.push(operations.pop());
}
while(!subAdd.empty()){
switch(subAdd.pop()){
case "+":
restOfNumbers.push(restOfNumbers.pop() + restOfNumbers.pop());
case "-":
restOfNumbers.push(restOfNumbers.pop() - restOfNumbers.pop());
}
}
return restOfNumbers.pop();
}
public static void popOrPush(int number){
numbers.push(number);
}
public static void popOrPush(String operation, String[] tokens){
switch(operation){
case "*":
int multipliedValue = numbers.pop();
i++;
multipliedValue = multipliedValue * Integer.parseInt(tokens[i]);
numbers.push(multipliedValue);
case "/":
int dividedValue = numbers.pop();
i++;
dividedValue = dividedValue / Integer.parseInt(tokens[i]);
numbers.push(dividedValue);
case "+": case "-":
operations.push(operation);
}
}
}
You're not initializing your Stack, so you're likely getting a NPE when trying to use the numbers variable.
Make sure to initialize all of your variables (particularly your Stack objects). For example:
Stack<Integer> numbers = new Stack<>();
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;
}
}
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);
}
}
I am trying to generate random numbers (1 to 10) using enum. The variable "num" is not getting the updated random value, not sure what mistake I am making. Any pointer will be helpful. Thank you.
Java Code:
enum RandomNumbers
{
ONE,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN;
public static RandomNumbers getRandom()
{
return values()[(int)(Math.random() * values().length)];
}
}
public class RandomNumbersEnum
{
public static void main(String[] args)
{
RandomNumbers randN = RandomNumbers.getRandom();
int num = 0;
if (randN.values().equals("ONE"))
num = 1;
else if(randN.values().equals("TWO"))
num = 2;
else if(randN.values().equals("THREE"))
num = 3;
else if(randN.values().equals("FOUR"))
num = 4;
else if(randN.values().equals("FIVE"))
num = 5;
else if(randN.values().equals("SIX"))
num = 6;
else if(randN.values().equals("SEVEN"))
num = 7;
else if(randN.values().equals("EIGHT"))
num = 8;
else if(randN.values().equals("NINE"))
num = 9;
else if(randN.values().equals("TEN"))
num = 10;
System.out.println("The random number is: " + num);
}
}
You can try to use the Random class of Java, i let you some example:
Random r = new Random();
int number = r.nextInt(10)+1;
System.out.println(number);
The reason that this doesn't work is that your if statements are testing whether the array that enumerates all RandomNumbers instances is equal to some String. Of course, it never could be. When you call randN.values(), you are actually invoking the static method RandomNumbers.values(), the same method you used in your getRandom() method. If you want a string that you can compare, randN.name() would work, but it's really not a good idea.
If you insist on comparing something, you should use an identity comparison, like this:
int num; /* Notice I'm not prematurely assigning meaningless garbage here. */
if (randN == RandomNumbers.ONE)
num = 1;
else if(randN == RandomNumbers.TWO)
num = 2;
else if(randN == RandomNumbers.THREE)
num = 3;
else
throw new IllegalArgumentException("Unrecognized RandomNumber: " + randN);
The next step forward would be to use a switch statement:
int num;
switch(randN) {
case ONE: num = 1; break;
case TWO: num = 2; break;
case THREE: num = 3; break;
default: throw new IllegalArgumentException();
}
You aren't making good use of an enum. Here's an approach that takes full advantage of an enum type:
public enum RandomNumber {
ONE(1),
TWO(2),
THREE(3);
private final int value;
private RandomNumber(int value)
{
this.value = value;
}
public int getValue()
{
return value;
}
public static RandomNumber roll()
{
RandomNumber[] values = values();
int idx = ThreadLocalRandom.current().nextInt(values.length);
return values[idx];
}
public static void main(String... argv)
{
RandomNumber num = RandomNumber.roll();
System.out.printf("The random number is %s (%d).%n", num, num.getValue());
}
}