Seeking advice for case switch in loops. my description is below - java

How do I make my output for Binary to Decimal this: Choice: 1 Binary Number : 2222 INVALID Binary Number
If a user types the binary above 1.
Also, how should I make the default of the switch case not show unless the user inputs the wrong option. Example: They input "HOOPdoop" which is not on the menu screen, the default will output saying that they must try again with the correct input. However, I don't want the default to output when the user inputs "Octal to Decimal" / after the calculation.
here is my code:
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//VARIABLES BEFOR LOOP / FOR LOOP
boolean Loop = true;
String Choice;
//OBJECTS
Scanner input = new Scanner(System.in);
while (Loop == true) {
//MENU
System.out.println("This program will convert...\n" + " \n" + "Binary to Decimal\n" + "Octal to Decimal\n" + "Decimal to Binary\n" + "Decimal to Octal\n" + "or you may Exit");
//ASK
System.out.println("--------------------------------------------");
System.out.println("Which converter would you like to use? or would you like to exit? : ");
Choice = input.nextLine();
//VARIABLES INSIDE LOOP
String binary = "";
int decimal;
String octal;
switch (Choice) {
case "Binary to Decimal":
System.out.print("Enter a binary number: ");
binary = input.nextLine();
if (binary.equals(2)) {
System.out.println("INVALID.");
} else {
System.out.println("Decimal: " + Integer.parseInt(binary, 2));
System.out.println("-----------------------------------------");
}
break;
case "Decimal to Binary":
System.out.print("Enter decimal number: ");
decimal = input.nextInt();
int answer = decimal;
while (answer > 0) {
binary = (answer % 2) + binary;
answer = answer / 2;
}
System.out.println("The binary number = " + binary);
System.out.println("-----------------------------------------");
break;
case "Decimal to Octal":
System.out.print("Enter decimal number: ");
decimal = input.nextInt();
octal = Integer.toOctalString(decimal);
System.out.println("Octal number = " + octal);
System.out.println("-----------------------------------------");
break;
case "Octal to Decimal":
System.out.print("Enter a Octal number: ");
octal = input.nextLine();
System.out.println("Decimal: " + Integer.parseInt(octal, 8));
System.out.println("-----------------------------------------");
break;
case "Exit":
System.out.println("Goodbye!!");
Loop = false;
break;
}
}
}
}```

Related

Illegal start of expression on my function public static void

My code is about looping and method, A program that will let user either compute an area or use the 4 basic math operations. the (Triangle, Square,Rectangle) with their choice of process: Addition, Subtraction, Multiplication and Division.
I think i properly closed the addition function there and i already check the closing every functions they seem work well other than the addtion function since thats the only error i got.
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//WHILE LOOP FOR CHOICES
while(true){//CHOICES LOOP
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
System.out.println("Input Choice of Process");
System.out.println("1 - Addition process");
System.out.println("2 - Subtraction process");
System.out.println("3 - Multiplication process");
System.out.println("4 - Division process");
System.out.println("5 - Compute process");
System.out.println("Your choice: ");
int option = scan.nextInt();
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
if(option == 1){
Add();
}
else if(option == 2){
Sub();
}
else if(option == 3){
Mul();
}
else if(option == 4){
Div();
}
else if(option == 5){
Com();
}
else if((option>=6)&&(option<=100)){//INVALID
System.out.println("Invalid Input, Please Input Choice Again.");
}
else{//- if user input other number, the program will break and stop from looping
break;
}
Here Im getting a error here im not sure what is it
public static void Add(){
System.out.println("ADDITION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int add1=scan.nextInt();
System.out.println("2nd number: ");
int add2=scan.nextInt();
int addtotal=add1+add2;
if(addtotal>100){// In addition, if the sum is higher than 100, print the answer the word high. if equal and below 100, print low
System.out.println("Total is "+addtotal+" High");
}
else if(addtotal<100){
System.out.println("Total is "+addtotal+" Low");
}
}
public static void Sub(){//SUBTRACTION
System.out.println("SUBTRACTION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int sub1=scan.nextInt();
System.out.println("2nd number: ");
int sub2=scan.nextInt();
int subtotal=sub1-sub2;
if(subtotal<0){// In subtraction, if the difference is negative, print invalid. If 0 or above, print the difference and the word valid.
System.out.println("Invalid ");
}
else if(subtotal>0){
System.out.println("Total is "+subtotal+" Valid");
}
}
public static void Mul(){//MULTIPLICATION
System.out.println("MULTIPLICATION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
double multi1=scan.nextDouble();//In multiplication, make it accepts decimal value
System.out.println("2nd number: ");
double multi2=scan.nextDouble();
double multitotal=multi1*multi2;
System.out.println("Total is "+multitotal);
}
public static void Div(){
System.out.println("DIVISION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int div1=scan.nextInt();
System.out.println("2nd number: ");
int div2=scan.nextInt();
int divtotal= div1 / div2;
int divremainder= div1 % div2;//In division, if it has remainder, print the answer and the remainder.
System.out.println("Total is "+divtotal);
System.out.println("Remainder is "+divremainder);
}
public static void Com(){// If user choose 5, the user needs to choose again on a ,b or c. If other letter, print invalid and then go pack on choosing of process.
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
System.out.println("Input Choice of Process");
System.out.println("a - Rectangle");
System.out.println("b - Square");
System.out.println("c - Triangle");
System.out.println("Your choice: ");
Scanner Keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
char choice = Keyboard.nextLine().charAt(0);
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
if (choice == 'A' || choice == 'a')//rectangle
{
System.out.println("Enter length of rectangle's base: ");
double base = input.nextDouble();
System.out.println("Enter length of rectangle's height: ");
double height = input.nextDouble();
double rArea = base * height;
System.out.println("The area of a rectangle with a base length of " + base + " and a height of " + height + " is " + rArea + ".");
}
else if (choice == 'B' || choice == 'b') //square
{
System.out.println("Enter length of square's sides: ");
double sSide = input.nextDouble();
double sArea = sSide * sSide;
System.out.println("The area of a square with a side length of " + sSide + " is " + sArea + ".");
}
else if (choice == 'C' || choice == 'c') //traingle
{
System.out.println("Enter traingle's side length: ");
double tSide = input.nextDouble();
double tArea = tSide * tSide * tSide;
System.out.println("The area of a triangle with a side length of " + tSide + " is " + tArea + ".");
}
else //invalid
{
System.out.println("You've entered an invalid character.");
}
}
}
You haven't got a closing brace for your main method

Java Calculator Switch Issue

I incorporated a couple different methods I've seen on here. Does anyone know how to fix this problem I am having? When you use this code, It asks for you to enter the mathematical operator, BUT when I do if I enter +9 or -%, it will still work and use the first symbol. I want it to give an error if someone inputs */ instead of just *. I even tried switching the case to numbers (ie case 1:) and it will do the same thing if I set addition to 1 and if I enter 15, it will read the one and do addition. Any ideas?
import java.util.Scanner;
public class javacalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Scanner operation = new Scanner(System.in);
double num1, num2, answer;
char userOperation;
System.out.print("Enter your full name: ");
String userName = input.nextLine();
System.out.println("+ Addition");
System.out.println("- Subtraction");
System.out.println("* Multiplication");
System.out.println("/ Division");
System.out.println("% Modulus");
System.out.println("\n");
System.out.print("Enter mathematical operator e.g. + for Addition: ");
userOperation = operation.next().charAt(0);
boolean invalidOperator = false;
switch (userOperation) {
case '+':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 + num2;
System.out.print(num1 + " + " + num2 + " = " + answer);
break;
case '-':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 - num2;
System.out.print(num1 + " - " + num2 + " = " + answer);
break;
case '*':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 * num2;
System.out.print(num1 + " * " + num2 + " = " + answer);
break;
case '/':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 / num2;
System.out.print(num1 + " / " + num2 + " = " + answer);
break;
case '%':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 % num2;
System.out.print(num1 + " % " + num2 + " = " + answer);
break;
default:
System.out.println("Invalid operator!");
break;
}
}
}
Let us break this down: operation.next().charAt(0);
operation.next() -> Gives you full input string
.charAt(0); -> returns the first character of the full input string
So anything we enter +9 or */ -> it returns the first element.
Now let's handle this case:
String o = operation.next(); // here is complete input
if(o.length()!=1){
userOperation = 0; //if length of input is not 1 we set custom value
}else{
userOperation = o.charAt(0); //get and set the first and only element
}
Hopefully it helps!

Number Conversion System in Java

import java.util.Scanner;
public class NumberConversionSystems {
public static void main(String[] args) {
//String binary = toBinaryString(number);
Scanner input = new Scanner(System.in);
System.out.println("Number Conversion Systems \n");
// Display the menu
System.out.println("1.\t Decimal to Binary");
System.out.println("2.\t Decimal to Hexadecimal");
System.out.println("3.\t Binary to Decimal");
System.out.println("4.\t Hexadecimal to Decimal \n");
System.out.println("Your choice?");
//Get user's choice
int choice = input.nextInt();
switch (choice) {
case 1: System.out.println("\nEnter Decimal Number");
break;
case 2: System.out.println("\nEnter Decimal Number");
break;
case 3: System.out.println("\nEnter Binary");
break;
case 4: System.out.println("\nEnter Hexadecimal");
break;
default:
System.out.println("\nInvalid choice. Please choose a number between 1 and 4.");
choice = input.nextInt();
break;
}
if (choice == 1) {
int number = input.nextInt();
String binary = toBinaryString(number);
binary = recursive(number);
System.out.printf("Decimal to Binary (%d) = %s", number, binary);
}
else if (choice == 2) {
int number2 = input.nextInt();
String hexadecimal = toHexString(number2);
hexadecimal = recursiveDecHex(number2);
System.out.printf("Decimal to Hexadecimal (%d) = %s ", number2, hexadecimal);
}
else if (choice == 3 ) {
String binary2 = input.next();
int decimal = toDecimalUsingParseInt(binary2);
decimal = recursiveBin(binary2);
System.out.printf("\n2. Binary to decimal - recursive(%s) = %d ", binary2, decimal);
}
else {
String hex = input.next();
int decimal = toHexUsingParseInt(hex);
decimal = recursiveHexDec(hex);
System.out.printf("Hexadecimal to Decimal (%s) = %d ", hex, decimal);
}
input.close();
}
private static String toBinaryString(int number) {
return Integer.toBinaryString(number);
}
private static String toHexString(int number) {
return Integer.toHexString(number);
}
private static int toDecimalUsingParseInt(String binaryNumber) {
return Integer.parseInt(binaryNumber, 2);
}
private static int toHexUsingParseInt(String number) {
return Integer.parseInt(number, 16);
}
private static String recursive(int number) {
StringBuilder builder = new StringBuilder();
if (number > 0) {
String binaryNumber = recursive(number / 2);
int digit = number % 2;
builder.append(binaryNumber + digit);
}
return builder.toString();
}
private static String recursiveDecHex(int number) {
StringBuilder builder = new StringBuilder();
if (number > 0) {
String hexNumber = recursiveDecHex(number / 16);
String hexCode = "0123456789ABCDEF";
int hexDigit = number % 16;
builder.append(hexNumber + hexCode.charAt(hexDigit));
}
return builder.toString();
}
private static int recursiveBin(String binaryNumber) {
int decimal = 0;
int length = binaryNumber.length();
if (length > 0) {
String substring = binaryNumber.substring(1);
int digit = Character.getNumericValue(binaryNumber.charAt(0));
decimal = digit * (int) Math.pow(2, length - 1) + recursiveBin(substring);
}
return decimal;
}
private static int recursiveHexDec(String hexNumber) {
int decimal = 0;
String hexCode = "0123456789ABCDEF";
hexNumber = hexNumber.toUpperCase();
int length = hexNumber.length();
if (length > 0) {
char ch = hexNumber.charAt(0);
int digit = hexCode.indexOf(ch);
String substring = hexNumber.substring(1);
decimal = digit * (int) Math.pow(16, length - 1) + recursiveHexDec(substring);
}
return decimal;
}
}
When I choose an invalid number (Number that is not in between 1 and 4), the programme will then show "Invalid choice. Please choose a number between 1 and 4", and when I enter a valid number after that, the programme just stops running.
It does not ask me to enter a decimal number if, for example, I choose '1'. What am I missing?
You have no loop, where you try it again and again until a vaild number is entered.
Try this one:
int choice = -1;
while (choice < 0 || choice > 4) {
choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("\nEnter Decimal Number");
break;
case 2:
System.out.println("\nEnter Decimal Number");
break;
case 3:
System.out.println("\nEnter Binary");
break;
case 4:
System.out.println("\nEnter Hexadecimal");
break;
default:
System.out.println("\nInvalid choice. Please choose a number between 1 and 4.");
break;
}
}
But keep in mind, that there is no escape from the loop beside enterin a correct number.
You are waiting for a new entry in the default of the switch. So it just sits there until you put one in.
You could do that part before the switch more easily:
boolean badEntry = true;
do{
System.out.println("Your choice?");
int choice = input.nextInt();
if (( choice<1 )|| (choice>4)) {
System.out.println("\nInvalid choice. Please choose a number between 1 and 4.");
} else {
badEntry = false;
}
}
while (badEntry);
Your program doesn't stop. It's actually waiting for input after you enter the valid number. If you don't believe me, try entering another number after you enter the valid choice. For me, it worked something like this.
Number Conversion Systems
1. Decimal to Binary
2. Decimal to Hexadecimal
3. Binary to Decimal
4. Hexadecimal to Decimal
Your choice?
5
Invalid choice. Please choose a number between 1 and 4.
1
23
Decimal to Binary (23) = 10111
However, by the time you've reached the point in your program where you enter a valid choice, the part that prints out the message such as "Enter decimal number" has already passed; which is why you're not getting that message.

Validation error in code

I am experiencing trouble in the creation of my reverse polish notation calculator with my validation code. I need the calculator to accept the two shift operators (<< and >>) as part of the calculations. The following snippets of code is the validation part and also the calculation.
public static boolean isInt(String userinput) {
try {
Integer.parseInt(userinput); // Try to parse. Makes sure that the values entered are actual numbers
return true; // Boolean value to show if the equation entered is valid or not
} catch (NumberFormatException e) {
System.out.println("Please enter a valid expression!");
invalidlines++;
return false;
}
}
public static boolean isValidLine(String line) {
line = line.trim();
if (line.length() <= 4) { // Trims the lines down to 4 and ensures there is no spaces being included
return false;
} else {
String[] calcarray = new String[3];
calcarray = line.split(" ");
String operators = new String("[+\\-\\*\\/\\<<\\>>\\%\\&\\|]"); // Validator using regular expressions to check the operator used
if (isInt(calcarray[0].toString()) && isInt(calcarray[1].toString()) && calcarray[2].matches(operators)) { // Checks that the operator in the string matches the ones in the regular expression
return true;
} else {
return false;
}
}
}
below is the calculator part:
String keyboardInput = new String();
Scanner kbScan = new Scanner(System.in);
int answer = 0;
while (true) {
display("Please enter an equation");
keyboardInput = kbScan.nextLine();
if (isValidLine(keyboardInput)) {
String[] equation = new String[3]; // We know that this is only going to contain 3 to be valid
equation = keyboardInput.split(" "); // split this up, as it's stored with the spaces.
int num1 = Integer.parseInt(equation[0]);
int num2 = Integer.parseInt(equation[1]);
switch (equation[2]) { // This case switch checks the third position of the
// string to decide which operator is being used. It then works out the
// answer and breaks to the next instruction
case ("+"):
answer = num1 + num2;
break;
case ("-"):
answer = num1 - num2;
break;
case ("/"):
answer = num1 / num2;
break;
case ("*"):
answer = num1 * num2;
break;
case ("<<"):
answer = num1 << num2;
break;
case (">>"):
answer = num1 >> num2;
break;
case ("%"):
answer = num1 % num2;
break;
case ("|"):
answer = num1 | num2;
break;
case ("&"):
answer = num1 & num2;
break;
}
display("Your post fix expression: " + equation[0] + " " + equation[1] + " " + equation[2]);
display("Your calculation: " + equation[0] + " " + equation[2] + " " + equation[1] + " = " + answer);
} else {
display("The equation you entered is invalid");
}
}
Whenever a valid expression is entered the following error is shown in the console:
Enter F for file calculator or K for keyboard input
k
Please enter an equation
10 2 <<
The equation you entered is invalid
Please enter an equation
And I cannot figure out which part of my validation is wrong for these expressions.
Problem is with your operators regex.
User rather something like:
("\\+|\\-|\\*|\\/|<<|>>|\\%|\\&|\\|")

I can't figure out my simple Java homework

I have this programming assignment that converts between meters and feet, and between kilograms and pounds. When I tell the program I want to convert weight (by entering "w" when prompted), it gives me my the following error:
Error: Too many input characters error.
I worked on this for a long time, but can't figure it out. Can someone please tell me how to make the weight conversion work like the length conversion?
import java.util.Scanner;
/**
* This class..
*/
public class UnitConversion3b
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String maxInputWarning = "\nError: Too many input characters."
+ "\nProgram is now terminating.";
String lengthOrWeight;
final double LENGTH_CONVERSION_FACTOR = 3.2808399;
final double WEIGHT_CONVERSION_FACTOR = 2.20462;
String whichWeightConversion = "empty" , whichLengthConversion = "empty";
double feet = 0, meters = 0, pounds =0 , kilograms = 0;
double metersConvertedToFeet, feetConvertedToMeters;
double poundsConvertedToKilograms, kilogramsConvertedToPounds;
System.out.println("");
System.out.print("What kind of value would you like to convert?");
System.out.print("\nEnter L for length, or W for weight: ");
lengthOrWeight = keyboard.nextLine();
if (lengthOrWeight.length() > 1 ) {
System.out.println(maxInputWarning);
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if ((!(lengthOrWeight.equalsIgnoreCase("l"))
&& (!(lengthOrWeight.equalsIgnoreCase("w"))))){
System.out.println("\nError: Unrecognized conversion type."
+ "\nProgram is now terminating.");
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if (lengthOrWeight.equalsIgnoreCase("l")){
System.out.println("\nConverting feet or meters?");
System.out.print("Enter F to convert feet, or M for meters: ");
whichLengthConversion = keyboard.nextLine();
}
if (whichLengthConversion.length() > 1 ) {
System.out.println(maxInputWarning);
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if ((!(whichLengthConversion.equalsIgnoreCase("f"))
&& (!(whichLengthConversion.equalsIgnoreCase("m"))))){
System.out.println("\nError: Unrecognized unit of "
+ "measurement.\nProgram is now terminating." );
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if (whichLengthConversion.equalsIgnoreCase("f")){
System.out.print ("Enter the number of feet to"
+ " convert to meters: ");
feet = keyboard.nextDouble();
feetConvertedToMeters = feet / LENGTH_CONVERSION_FACTOR;
System.out.println("The number of meters in " + feet +
" feet is " + feetConvertedToMeters + ".");
keyboard.nextLine();
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if (whichLengthConversion.equalsIgnoreCase("m")){
System.out.print ("Enter the number of meters to"
+ " convert to feet: ");
meters = keyboard.nextDouble();
metersConvertedToFeet = meters * LENGTH_CONVERSION_FACTOR;
System.out.println("The number of feet in " + meters +
" meters is " + metersConvertedToFeet + ".");
keyboard.nextLine();
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
}
if (lengthOrWeight.equalsIgnoreCase("w")){
System.out.println("Converting pounds or kilograms?");
System.out.print("Enter P to convert pounds, or K for kilograms: ");
whichWeightConversion = keyboard.nextLine();
}
if (whichWeightConversion.length() > 1 ) {
System.out.println(maxInputWarning);
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if ((!(whichWeightConversion.equalsIgnoreCase("p"))
&& (!(whichWeightConversion.equalsIgnoreCase("k"))))){
System.out.println("\nError: Unrecognized unit of "
+ "measurement.\nProgram is now terminating." );
System.out.print("Press Enter to continue ... ");
return;
} else if (whichWeightConversion.equalsIgnoreCase("p")){
System.out.println("Enter the number of pounds to"
+ " convert to kilograms:");
pounds = keyboard.nextDouble();
poundsConvertedToKilograms = pounds / WEIGHT_CONVERSION_FACTOR;
System.out.println("The number of pounds in " + kilograms +
" kilograms is " + poundsConvertedToKilograms + ".");
keyboard.nextLine();
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if (whichLengthConversion.equalsIgnoreCase("k")){
System.out.print ("Enter the number of kilograms to"
+ " convert to pounds: ");
kilograms = keyboard.nextDouble();
kilogramsConvertedToPounds = kilograms * WEIGHT_CONVERSION_FACTOR;
System.out.println("The number of pounds in " + pounds +
"pounds is " + kilogramsConvertedToPounds + ".");
keyboard.nextLine();
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else{
return;
}
}
}
You made lots of errors by not changing the code while copy pasting the logic from one place to the other. Your code can be improved a lot by reducing the repetitions and I will be more optimistic in my 'if' 'else' conditions to capture the right cases first and leaving all the wrong cases to the end...Below is the working version of your code modified slightly by fixing the typos and order of the logic.
import java.util.Scanner;
public class UnitConversion3b {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String maxInputWarning = "\nError: Too many input characters."
+ "\nProgram is now terminating.";
String lengthOrWeight;
final double LENGTH_CONVERSION_FACTOR = 3.2808399;
final double WEIGHT_CONVERSION_FACTOR = 2.20462;
String whichWeightConversion = "empty", whichLengthConversion = "empty";
double feet = 0, meters = 0, pounds = 0, kilograms = 0;
double metersConvertedToFeet, feetConvertedToMeters;
double poundsConvertedToKilograms, kilogramsConvertedToPounds;
System.out.println("");
System.out.print("What kind of value would you like to convert?");
System.out.print("\nEnter L for length, or W for weight: ");
lengthOrWeight = keyboard.nextLine();
if (lengthOrWeight.length() > 1) {
System.out.println(maxInputWarning);
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if ((!(lengthOrWeight.equalsIgnoreCase("l")) && (!(lengthOrWeight
.equalsIgnoreCase("w"))))) {
System.out.println("\nError: Unrecognized conversion type."
+ "\nProgram is now terminating.");
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if (lengthOrWeight.equalsIgnoreCase("l")) {
System.out.println("\nConverting feet or meters?");
System.out.print("Enter F to convert feet, or M for meters: ");
whichLengthConversion = keyboard.nextLine();
if (whichLengthConversion.length() > 1) {
System.out.println(maxInputWarning);
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if ((!(whichLengthConversion.equalsIgnoreCase("f")) && (!(whichLengthConversion
.equalsIgnoreCase("m"))))) {
System.out.println("\nError: Unrecognized unit of "
+ "measurement.\nProgram is now terminating.");
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if (whichLengthConversion.equalsIgnoreCase("f")) {
System.out.print("Enter the number of feet to"
+ " convert to meters: ");
feet = keyboard.nextDouble();
feetConvertedToMeters = feet / LENGTH_CONVERSION_FACTOR;
System.out.println(feet + " Feet in Meters is "
+ feetConvertedToMeters + ".");
keyboard.nextLine();
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if (whichLengthConversion.equalsIgnoreCase("m")) {
System.out.print("Enter the number of meters to"
+ " convert to feet: ");
meters = keyboard.nextDouble();
metersConvertedToFeet = meters * LENGTH_CONVERSION_FACTOR;
System.out.println(meters + " Meters in Feet is "
+ metersConvertedToFeet + ".");
keyboard.nextLine();
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
}
}
else {
System.out.println("Converting pounds or kilograms?");
System.out.print("Enter P to convert pounds, or K for kilograms: ");
whichWeightConversion = keyboard.nextLine();
if (whichWeightConversion.length() > 1) {
System.out.println(maxInputWarning);
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if ((!(whichWeightConversion.equalsIgnoreCase("p")) && (!(whichWeightConversion
.equalsIgnoreCase("k"))))) {
System.out.println("\nError: Unrecognized unit of "
+ "measurement.\nProgram is now terminating.");
System.out.print("Press Enter to continue ... ");
return;
} else if (whichWeightConversion.equalsIgnoreCase("p")) {
System.out.println("Enter the number of pounds to"
+ " convert to kilograms:");
pounds = keyboard.nextDouble();
poundsConvertedToKilograms = pounds / WEIGHT_CONVERSION_FACTOR;
System.out.println(pounds + " Pounds in Kilograms is "
+ poundsConvertedToKilograms + ".");
keyboard.nextLine();
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
} else if (whichWeightConversion.equalsIgnoreCase("k")) {
System.out.print("Enter the number of kilograms to"
+ " convert to pounds: ");
kilograms = keyboard.nextDouble();
kilogramsConvertedToPounds = kilograms
* WEIGHT_CONVERSION_FACTOR;
System.out.println(kilograms + " Kilograms in Pounds is "
+ kilogramsConvertedToPounds + ".");
keyboard.nextLine();
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
}
}
}
}
You're missing a right curly-brace after your meters-to-feet case.
There are some other curly-brace issues throughout your code -- for example, on line 47, there's a right brace where you don't want one. Check over your block structure and, in each case, make sure you're opening and closing blocks where it makes logical sense to do so.
My professor makes us seperate our main class from the Class that is doing the work. It helps a lot. I know it seems like a lot of extra work, but if you pulled your SOPs/inputs out into a DemoMain class and then had your UnitConversion3b class seperate it would be a lot easier to read. Also, I know a lot of people put their {'s right after the close of a paren, but honestly I find my own code a lot easier to read if I drop my opening { down a line. I think your logic is good statement wise, but it's so hard to tell with the brace issues. I think you have some hanging if issues, where you mean to have some of the statements inside a conditional but they are actually outside :-/
Try getting rid of
(!(lengthOrWeight.equalsIgnoreCase("l"))
&& (!(lengthOrWeight.equalsIgnoreCase("w"))))){
and just putting the following block in the else
else{
System.out.println("\nError: Unrecognized conversion type."
+ "\nProgram is now terminating.");
System.out.print("Press Enter to continue ... ");
keyboard.nextLine();
return;
}
It might not help but it will make things clearer.
Also you don't need to check length when you can do line.equalsIgnoreCase("l"), if the input is longer it will not be equal.
The reason why it gives you that error is because Scanner's nextLine() method returns the line as well as the newline character ('\n') that ends the line.
Try this line instead, using String's trim() method to cut off all whitespace from either end :
lengthOrWeight = keyboard.nextLine().trim();
OK, so here is an example of two classes, a main demo class and the actual working class:
TestMain.java goes like this:
import java.util.Scanner;
public class TestMain
{
public static void main(String[] args)
{
float theValue;
float theAnswerIs;
char getLengthOrWeight;
String theValueAsString;
boolean lOrW; //length or width
boolean fOrM; //feet or meters
boolean pOrK; //pounds or kilos... it's a CS joke haha
char getFeetOrMeters;
char getPoundsOrKilos;
//Set up a Scanner instance called keyboard
Scanner keyboard = new Scanner(System.in);
UnitConversion3b converterInstance = new UnitConversion3b();
//Request user for the number to convert
System.out.println("What is the value you will be converting?");
theValueAsString = keyboard.nextLine();
//convert that value and trap
theValue = floatToString(theValueAsString);
//Request user for length or weight conversion
System.out.println("What kind of value would you like to convert?");
System.out.println("Enter L for length, or W for weight: ");
//variable = console.next().charAt(0);
getLengthOrWeight = keyboard.next().charAt(0);
lOrW = converterInstance.lengthOrWeight(getLengthOrWeight);
//create a new UnitConversion3B object and pass it the L or W or bad string the user inputs
//if(true) then user asked for length
if(lOrW)
{
System.out.println("\nConverting feet or meters?");
System.out.print("Enter F to convert feet to meters, or M for meters to feet: ");
//set our main's feetOrMeters variable to the value received when we ask our
//converterInstance the question whichLengthConversion?
getFeetOrMeters = keyboard.next().charAt(0);
fOrM = converterInstance.feetOrMeters(getFeetOrMeters);
//if(fOrM) aka user asked for a length conversion in feet, let's convert it:
if(fOrM)
{
theAnswerIs = (float) (theValue * 3.28083);
System.out.println("The answer is: " + theAnswerIs + " feet.");
}
//if(!fOrM) aka user asked for a length conversion in meters, let's convert it:
if(!fOrM)
{
theAnswerIs = (float) (theValue * 0.3048);
System.out.println("The answer is: " + theAnswerIs + " feet.");
}
//bad input should be trapped in the feetOrMeters function of the converterInstance
}
//if(false) then user asked for weight
else if(!lOrW)
{
System.out.println("Converting pounds or kilograms?");
System.out.print("Enter P to convert pounds to kilos, or K for kilograms to pounds: ");
getPoundsOrKilos = keyboard.next().charAt(0);
pOrK = converterInstance.poundsOrKilos(getPoundsOrKilos);
//if(pOrK) aka user asked for a pounds to kilos conversion, let's convert it:
if(pOrK)
{
theAnswerIs = (float) (theValue * 0.45359237);
System.out.println("The answer is: " + theAnswerIs + " feet.");
}
//if(!pOrK) aka user asked for a kilos to pounds conversion, let's convert it:
if(!pOrK)
{
theAnswerIs = (float) (theValue * 2.20462262);
System.out.println("The answer is: " + theAnswerIs + " feet.");
}
//bad input should be trapped in the poundsOrKilos function of the converterInstance
}
}
private static float floatToString(String theValueAsString) {
// thanks for this method from http://devdaily.com/java/edu/qanda/pjqa00013.shtml
float f = 0;
try
{
f = Float.valueOf(theValueAsString.trim()).floatValue();
}
catch (NumberFormatException nfe)
{
System.out.println("NumberFormatException: " + nfe.getMessage());
}
return f;
}
}
and UnitConversion3b.java goes like:
public class UnitConversion3b
{
private boolean lengthOrWeightSwitch;
boolean feetOrMeters;
final double LENGTH_CONVERSION_FACTOR = 3.2808399;
final double WEIGHT_CONVERSION_FACTOR = 2.20462;
boolean poundsOrKilograms;
public UnitConversion3b(String getLengthOrWeight) {
if(getLengthOrWeight == "W")
lengthOrWeightSwitch = true;
else if(getLengthOrWeight == "L")
lengthOrWeightSwitch = false;
else
{
badInput();
}
}
public boolean getConversionType()
{
return lengthOrWeightSwitch;
}
public boolean whichLengthConversion(String whichLength)
{
if(whichLength == "F")
feetOrMeters = true;
else if(whichLength == "M")
feetOrMeters = false;
else
{
badInput();
}
return feetOrMeters;
}
public boolean whichWeightConversion(String whichWeight)
{
if(whichWeight == "P")
poundsOrKilograms = true;
else if(whichWeight == "K")
poundsOrKilograms = false;
else
{
badInput();
}
return poundsOrKilograms;
}
public void badInput()
{
System.out.println("Invalid input");
System.exit(0);
}
public String valueToFeet(float theValue) {
//assumes value entered need to be converted from meters to feet
return "" + (theValue*LENGTH_CONVERSION_FACTOR);
}
public String valueToMeters(float theValue) {
//assumes value entered need to be converted from feet to meters
return "" + (theValue/LENGTH_CONVERSION_FACTOR);
}
public String valueToPounds(float theValue) {
// assumes value entered needs to be converted to pounds
return ""+ (theValue * WEIGHT_CONVERSION_FACTOR);
}
public String valueToKilos(float theValue) {
// TODO Auto-generated method stub
return ""+ (theValue / WEIGHT_CONVERSION_FACTOR);
}
public void setConversionType(char getLengthOrWeight) {
if(getLengthOrWeight == 'L')
lengthOrWeightSwitch = true;
if(getLengthOrWeight == 'W')
lengthOrWeightSwitch = false;
else
badInput();
}
public boolean lengthOrWeight(char getLengthOrWeight) {
if(getLengthOrWeight == 'L')
return true;
if(getLengthOrWeight == 'W')
return false;
return false;
}
public boolean feetOrMeters(char getFeetOrMeters) {
if(getFeetOrMeters == 'F')
return true;
if(getFeetOrMeters == 'M')
return false;
//these functions return false under 'false' conditions... work on the logic :-)
return false;
}
public boolean poundsOrKilos(char getPoundsOrKilos) {
if(getPoundsOrKilos == 'P')
return true;
if(getPoundsOrKilos == 'K')
return false;
//these functions return false under 'false' conditions... work on the logic :-)
return false;
}
}
Now please note, even if I pasted this correctly you are going to get a worse than bad score on your assignment if you turn in this code. It compiles and runs, but it ignores the max char# input you seemed to have constrained on your assignment. Probably there are other issues, howver, I think it is somewhat followable code. I would probably want to break it even further into more classes, but I hope this helps.
I know this may sound a little nutty, but it works: Imagine your user input as a little animal and you have set a trap for it. You need to catch the animal and do something to it. For our animal lovers' sake, let's say you need to catch it, tranquilize it, weigh it, and put a radio collar on it and then release it relatively unharmed provided it is of type Cougar. So, our trap is a multi-function trap. Whatever enters it, a value will be produced.
WHAM!!! Something is in the trap. Luckily, our trap is automatic. If it doesn't land a float value, then the trap opens and it leaves. It isn't a Cougar.
OK, the trap is still closed. It must be a Cougar. We can work on it.
Now, we ask the guy wearing the Banana Republic gear with the big Nikon around his neck for some help. We have this Float value in the trap. Now, we ask the Scientist in the Banana Repubic gear what our number means.
"Hey, Scientist Guy, what does the number in our trap mean?"
If "It's the length", he answers:
This is the length of the Cougar in feet, I need it it converted to meters...
This is the length of the Cougar in meters, I need it it converted to feet...
If "it's the weight", he answers:
This is the weight in pounds, I need it converted to kilos...
This is the weight in kilos, I need it converted to pounds...
You may find that, when you think about it, your Teacher was asking 'how do you set up the problem'? In other words, by asking the user for the value first, you can cut down on the amount of questions the program has to answer.

Categories