I am trying to create a program that prompts the user to enter in the weight of the package and display the cost. I am new to the switch statement, which is why I feel it may have something to do with those statements. However, I return the error "cannot convert from boolean to int". I have looked at other situations where this comes up, but have not found a solution. Using == did not change it.
import java.util.Scanner;
public class Exercise03_18 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the weight of the package: ");
int weight = input.nextInt();
switch (weight) {
case weight <= 1:
System.out.println("The cost is 3.5");
break;
case weight <= 3:
System.out.println("The cost is 5.5");
break;
case weight <= 10:
System.out.println("The cost is 8.5");
break;
case weight <= 20:
System.out.println("The cost is 10.5");
default: System.out.println("The package cannot be shipped");
}
}
}
This post is relevant
Switch statement for greater-than/less-than
When you use switch you can only put equations in cases
switch(x)
{
case 1:
//...
break;
case 2:
//...
break;
}
The following is not valid Java:
case weight <= 1:
You need to rephrase the switch as a series of if statements.
if (weight <= 1) {
System.out.println("The cost is 3.5");
} else if (weight <= 3) {
System.out.println("The cost is 5.5");
} ...
Related
So, I made a burger class with a method for extra stuff, my question is how can I use case 0,1,2 only 1 time, like if I use case 0, I can't use it anymore, I can use only 1 and 2, If I use case 1 after 0 , then I can use only case 2 since I used case 0 and 1 before , It's possible to do something like that ? If yes how ?
The code:
boolean flag=true;
while(flag){
System.out.println("Enter your choice for extra toppings ");
int choice=scanner.nextInt();
scanner.nextLine();
switch(choice) {
case 0:
double salad = 0.35;
setAdditional(getAdditional() + salad);
System.out.println("salad added\n");
break;
case 1:
double bacon=1.05;
setAdditional(getAdditional()+bacon);
System.out.println("Bacon added \n");
break;
case 2:
double fries=0.79;
setAdditional(getAdditional()+fries);
System.out.println("fries added \n");
break;
case 3:
System.out.println("Done");
flag=false;
}
}
} ```
boolean flag = true;
Set<Integer> set = new HashSet<>();
while (flag) {
System.out.println("Enter your choice for extra toppings ");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 0:
if (!set.contains(choice)) {
double salad = 0.35;
setAdditional(getAdditional() + salad);
System.out.println("salad added\n");
break;
}
else {
System.out.println("Added already");
}
continue;
case 1:
double bacon = 1.05;
setAdditional(getAdditional() + bacon);
System.out.println("Bacon added \n");
break;
case 2:
double fries = 0.79;
setAdditional(getAdditional() + fries);
System.out.println("fries added \n");
break;
case 3:
System.out.println("Done");
flag = false;
}
set.add(choice);
}
}
so I did it with Set in the end, only for salad, but it's the same for the rest, if someone else needs it.
your cases go by integer numbers, so an array of boolean with 1 element for every option.
boolean[] allowed = new boolean[options]; (faster than hasMap of string to boolean).
add a check just before the "switch" statement:
if(allowed[choice] && choice != 3) {...}
you should also create an integer constant STOP_OPTION or something like that and use it in the above if-statement and in the final "case" of your switch statement. in your example, set it to 3. then later you can change it without replacing all instances of "3" in your code. but that's more of a styling suggestion.
the "flag" boolean is also redundant, the while loop can just check if choice != 3. be careful of NumberFormatExceptions!
good luck!
I'm trying to convert binary to decimal, how do I change my code to be able to do that? Where did I mess up?
i tried looking at other examples, looking at java api and watching videos but i still can't figure out what mistake i have made.
package Calculator;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("(2) Convert binary to decimal");
System.out.println("\n\n Please enter your choice: ");
int choice = scan.nextInt();
if(choice == 2){
scan.nextLine();
//prompt for user input
System.out.println("Please enter a binary number: ");
String binary = scan.nextLine();
char[] binaryArray = binary.toCharArray();
int i=1;
int integer=0;
//potential problem somewhere around here?
while(i<8){
if(binaryArray[i]==0) {
++i;
}else if(binaryArray[i]==1) {
switch(i) {
case 1:
integer+=128;
++i;
break;
case 2:
integer+=64;
++i;
break;
case 3:
integer+=32;
++i;
break;
case 4:
integer+=16;
++i;
break;
case 5:
integer+=8;
++i;
break;
case 6:
integer+=4;
++i;
break;
case 7:
integer+=2;
++i;
break;
case 8:
integer+=1;
++i;
break;
}
}
}
System.out.println("The decimal value of the binary number is: "+ integer);
scan.close();
}
}
}
The input is always 0. I've tried 11010110, 11111111,and 01010111. Always 0. I know the problem lies somewhere with my integer value not changing but I can't figure out what it specifically is.
This is happening because you are reading the input, and converting into an array of char.
Anywhere where you are making your comparisons to an int, you should instead be doing a comparison to a char, by wrapping your values in single quotations.
while(i<8){
if(binaryArray[i]=='0') {
++i;
}else if(binaryArray[i]=='1') {
switch(i) {
case 1:
integer+=128;
++i;
break;
case 2:
integer+=64;
++i;
break;
case 3:
integer+=32;
++i;
break;
case 4:
integer+=16;
++i;
break;
case 5:
integer+=8;
++i;
break;
case 6:
integer+=4;
++i;
break;
case 7:
integer+=2;
++i;
break;
case 8:
integer+=1;
++i;
break;
}
}
Others have already pointed out that you have got confused between 0 and 1, and '0' and'1'`.
Other problems:
Your i starts at 1, so you miss the most significant bit;
You will never actually hit case 8: in the switch because of the while (i < 8) loop guard.
This doesn't work unless you enter exactly 8 bits.
You can write the entire while loop in a much more concise way:
for (int i = 0; i < binaryArray.length; i++) {
integer *= 2; // shift the digits along by 1 place
if (binaryArray[i] == '1') {
integer += 1; // set the least significant bit.
}
}
You should get away from all those switch statements.
Say you have "10101101" as input.
set val = 0;
Then either multiply by val by 2 or shift left 1 bit. They're the same. It is important
you do this before adding the next bit.
Start from the left and if it's a '1', add a 1 to val. Otherwise, add 0.
Then repeat starting at multiply until you've gone thru the string.
val should then have the decimal version when you print it.
I am working on some online training for java and having difficulty with this concept.
This is what I'm trying to do. I'm close but not sure what I'm missing.
Create a MetricConverter class with the following methods (each method receives a metric value and returns the corresponding standard value):
kgToLbs(kg:double):double (+ means public; requires a double parameter; returns a double value)
kmToMiles(km:double):double
Create a MetricConverterTest application that runs from the following menu:
KG to lbs
KM to miles
So I'm close but The MetricConverter class should only contain four static methods - nothing else.
I can figure out the static methods and returns...but not how to display that returned result back. What am I missing?
The MetricConverterTest class should have a main method that displays the menu.
This is my code:
import java.util.Scanner;
public class MetricConverter {
private static Scanner keyBd = new Scanner(System.in);
//method if 1 is selected
public static double menuOption1() {
double kg = keyBd.nextDouble();
double lbs = 2.20462*kg;
return lbs;
}
//method if 2 is selected
public static double menuOption2() {
System.out.println("Enter the amount of kilometers you wish to convert: ");
double km = keyBd.nextDouble();
double miles = 0.621371 *km;
return miles;
}
public static void main(String[] args) {
char selection;
do {
//displays the menu
System.out.println("\n\nMainMenu");
System.out.println("1. Convert KG to lbs");
System.out.println("2. Convert kilometers to miles");
System.out.println("3. Quit");
System.out.println("Selection: ");
//get a menu selection
selection = keyBd.next().charAt(0);
switch(selection) {
case '1': menuOption1(); break;
case '2': menuOption2(); break;
case '3': break;
default: System.out.println("Invalid selection!");
}//end switch
} while(selection != '3');
}//end main()
}
You could either print the result from each menuOption method
public static double menuOption2() {
System.out.println("Enter the amount of kilometers you wish to convert: ");
double km = keyBd.nextDouble();
double miles = 0.621371 *km;
System.out.println(String.format("%s", miles));
return miles;
}
or from the case statements
switch(selection) {
case '1':
double result = menuOption1();
System.out.println(String.format("%s", result));
break;
case '2':
double result = menuOption2();
System.out.println(String.format("%s", result));
break;
case '3': break;
default: System.out.println("Invalid selection!");
}
You could print result inside de Switch like this, also i added a new line, that request a argument.
switch(selection) {
case '1': {
System.out.println("Fill Kgs to be converted");
System.out.println("Result of converting KG to Lbs is : " + menuOption1());
break;
}
case '2': {
System.out.println("Fill Kilometers to be converted");
System.out.println("Result of converting Kms to Miles is : " + menuOption2());
break;
}
case '3': break;
default: System.out.println("Invalid selection!");
}//end switch
case '1': System.out.println("Result "+menuOption1()); break;
case '2': System.out.println("Result "+menuOption2()); break;
case '3': break;
default: System.out.println("Invalid selection!");
If I understand the assignment well, it requires you to create a class MetricConverter with 2 static methods in it, and a separate class MetricConverterTest with a main method. This would imply that you need to create a package for your classes.
With regards to displaying the result, within your main method you are only calling the methods which return type double, but you don't store or display their result in any way. You need to use System.out.println( menuOptionX() );, or assign the output of your method to a variable like this Double result = menuOptionX(); and display it whenever you please with the aforementioned method.
So I am making a program in Java on a BlueJ environment that computes Binary expansion. However, I can't seem to figure out how to add powers more than 9 in the output.
If I have an input power of anything more than 9 the program goes haywire, presumably because there are no cases after 9.
Also, I personally feel my program in general is extremely inefficient but I just did it this morning and this was the first approach I saw, so if you see a way to make it more efficient than using switch case, that'd be great too.
This is my code so far. It's not all mine, but I'm not sure if intellectual property and stuff applies on here, so just putting it out there.
import java.util.*;
class Binomial_Theorem_Expansion
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the value of x in (x+a)^n");
int x=s.nextInt();
System.out.println("Enter the value of a in (x+a)^n");
int a=s.nextInt();
System.out.println("Enter the value of n in (x+a)^n");
int n=s.nextInt();
System.out.println ("The expanded answer is");
int r=0;
int powx=n;
while (r<=n)
{
long nCr=calculatenCr(n,r);
if(nCr!=-1)
{
double y=Math.pow((double)x,(double)n-r);
double z=Math.pow((double)a,(double)r);
switch (powx)
{
case 0: System.out.print ("("+nCr*y*z);
break;
case 1: System.out.print ("("+nCr*y*z+"x");
break;
case 2: System.out.print ("("+nCr*y*z+"x\u00B2");
break;
case 3: System.out.print ("("+nCr*y*z+"x\u00B3");
break;
case 4: System.out.print ("("+nCr*y*z+"x\u2074");
break;
case 5: System.out.print ("("+nCr*y*z+"x\u2075");
break;
case 6: System.out.print ("("+nCr*y*z+"x\u2076");
break;
case 7: System.out.print ("("+nCr*y*z+"x\u2077");
break;
case 8: System.out.print ("("+nCr*y*z+"x\u2078");
break;
case 9: System.out.print ("("+nCr*y*z+"x\u2079");
break;
case 10: System.out.print ("("+nCr*y*z+"x\u2071\u00B2");
break;
}
switch (r) {
case 0: System.out.print (")");
break;
case 1: System.out.print ("y"+")");
break;
case 2: System.out.print ("y\u00B2"+")");
break;
case 3: System.out.print ("y\u00B3"+")");
break;
case 4: System.out.print ("y\u2074"+")");
break;
case 5: System.out.print ("y\u2075"+")");
break;
case 6: System.out.print ("y\u2076"+")");
break;
case 7: System.out.print ("y\u2077"+")");
break;
case 8: System.out.print ("y\u2078"+")");
break;
case 9: System.out.print ("y\u2079"+")");
break;
}
r++;
if (r<=n)
{
System.out.print ("+");
}
powx--;
}
}
}
public static long calculatenCr(int n,int r)
{
long res=1;
if(n>=r)
{
res=getFact(n)/(getFact(n-r)*getFact(r));
return res;
}
else return -1;
}
public static long getFact(int n)
{
long f=1;
for(int i=n;i>=1;i--)
{
f*=i;
}
return f;
}
}
Thanks for any constructive input. :)
presumably because there are no cases after 9.
Your code is using UNICODE superscript characters, and the cases that you have cover only numbers zero through ten for x and zero through nine for y.
You can fix this by defining a method that produces a superscript UNICODE conversion of a multidigit number, and calling it from both places where you need to produce such representation:
switch (powx) {
case 0: System.out.print ("("+nCr*y*z);
break;
case 1: System.out.print ("("+nCr*y*z+"x");
break;
default: System.out.print ("("+nCr*y*z+"x"+toSuperscript(powx));
break;
}
The other switch (i.e. switch (r)) should be converted in a similar way.
You can implement String toSuperscript(int n) by producing a decimal representation of n, and then replacing '0' with '\u2070', '1' with '\u00B9', and so on.
I'm quite new to java programming. I was unable to find any information relating to the use of the || operator with strings. I was wondering if there was a more efficient way to do this code in particular that was still easily readable. I tried making a simple calculator as a way to familiarize myself with IfThenElse statements.
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
double first;
double second;
String option;
while(true){
System.out.println("What function would you like to calculate?");
option=input.next();
if(option.equals("add") || option.equals("+")){
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double add=first+second;
System.out.println(add);
}
else if(option.equals("subtract") || option.equals("-")) {
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double subtract=first-second;
System.out.println(subtract);
}
else if(option.equals("multiply") ||option.equals("*")) {
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double multiply=first*second;
System.out.println(multiply);
}
else if(option.equals("divide") || option.equals("/")) {
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double divide=first/second;
System.out.println(divide);
}
else if(option.equals("end")){
System.exit(0);
}
}
}
}
For the most part I am wondering about the if requirements, which I have tested and they do work, but it seems a bit clunky to me. However, any critique would be greatly appreciated.
Switch/case statements are a nice alternative to a series of ifs, and as of Java 7 you can use switch statements with strings. Note the syntactical difference between the two. Instead of grouping things with curly braces, each case ends with a break statement.
switch (option) {
case "add":
case "+":
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double add=first+second;
System.out.println(add);
break;
case "subtract":
case "-":
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double subtract=first-second;
System.out.println(subtract);
break;
case "multiply":
case "*":
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double multiply=first*second;
System.out.println(multiply);
break;
case "divide":
case "/":
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double divide=first/second;
System.out.println(divide);
break;
case "end":
System.exit(0);
}
I would then suggest combining the duplicated prompt code. If you find yourself copying and pasting code it's usually a good idea to take a step back and figure out how you can avoid the repetition. Duplicated code is a sign that you should do some refactoring.
if (option.equals("end")) {
System.exit(0);
}
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
switch (option) {
case "add":
case "+":
double add=first+second;
System.out.println(add);
break;
case "subtract":
case "-":
double subtract=first-second;
System.out.println(subtract);
break;
case "multiply":
case "*":
double multiply=first*second;
System.out.println(multiply);
break;
case "divide":
case "/":
double divide=first/second;
System.out.println(divide);
break;
}
Furthermore, you could also eliminate the duplicate printouts by using a single result variable for all of the calculations.
if (option.equals("end")) {
System.exit(0);
}
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double result;
switch (option) {
case "add": case "+": result = first + second; break;
case "subtract": case "-": result = first - second; break;
case "multiply": case "*": result = first * second; break;
case "divide": case "/": result = first / second; break;
}
System.out.println(result);
You're use of || seems fine to me. However I have a number of general suggestions to make the code better overall.
First of all, why not have isAdd, isSubtract, etc. functions? For example:
private boolean isAdd(String input){
return input.equalsIgnoreCase("add") || input.equals("+");
}
Same goes for the other operators. Than you can have code such as:
if (isAdd(option)) ...
Which is more readable than
if (input.equalsIgnoreCase("add") || input.equals("+")) ...
In a larger program, you might need to check these kinds of things more than once, and then having a method to do this becomes extra-handy. Also, this way if you want to change the definition of "add" (for example now "a" also qualifies), you change code in one place and the whole program complies.
Secondly, why not extract the bodies of these if statements into other functions? Than your code would read like so:
if (isAdd(option))
performAddition();
else if (isSubtract(option))
performSubtraction();
// .. etc
// function definitions here
Making for a much more readable program, as opposed to what you currently have.
Thirdly, notice where you put your spaces. option = input.next() looks better than option=input.next().
That's it pretty much. Good luck :)
John Kugelman and Aviv Cohn both gave good advice. I would like to add that your application will throw an InputMismatchException if you don't enter a valid number at the call to nextDouble(). Instead of your program terminating because of the exception you can prompt the user to enter a valid number after which he/she can try again.
One way to do this is by adding the following methods to SimpleCalculator:
private static Double getValidNumber()
{
Double nr = null;
while( nr == null )
{
nr = getNextDouble();
if(nr == null) System.out.println("Please enter a valid number.");
}
return nr;
}
private static Double getNextDouble()
{
Scanner input=new Scanner(System.in);
Double output = null;
try{ output = input.nextDouble(); }catch(InputMismatchException e){}
return output;
}
Then in your main method, simply replace the calls to input.nextDouble() by getValidNumber().