Why doesn't this switch statement work? - java

I seem to forget something or do something wrong, but what? Ans what to do if I want it to say "too small" if the number is less then 1?
public static String doStuff(int num) {
String number;
switch (num) {
case 1:
number = "one";
break;
case 2:
number = "two";
break;
case 3:
number = "thee";
break;
case 4:
number = "four";
break;
default:
number = "Not a day";
break;
}
return number;
}

Can only refer from c#
but you should do fine with something like this:
default:
if (num < 1)
number= "too small";
else
number= "Not a day";
break;

You can not handle it in the switch block, but need to have a check before that like
public static String doStuff(int num){
String number;
if (num<1) {
return "too small";
}
switch(num){
case 1:
number= "o

Related

Converting all letters in the phone number to digits

Im trying to replace each letter with a digit using the international standard letter/number mapping. I got my output to run correctly however, how do get the dashes in the phone number to appear automatically in the output? For example, if I enter 1800Flowers it prints out as 18003569377. How do I get it to print out as 1-800-3569377 without using regular expressions?
import java.util.Scanner;
public class PhoneKeypad {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//while loop keeps the program running until the user enters quit
while (true) {
System.out.println("\nEnter a phone number or quit to exit:");
String phoneNumber = input.next();
if (phoneNumber.equalsIgnoreCase("quit")) {
System.out.print("\nProgrammed by me");
return;
}
//checks if the phone number entered is at least 8 digits
if (phoneNumber.length() < 8) {
System.out.println("Invalid Phone Number");
} else {
System.out.println(getNumber(phoneNumber));
}
}
}
//method converts all letters in the phone number to digits
public static String getNumber(String phoneNumber) {
int keypadNum = 0;
for (int i = 0; i < phoneNumber.length(); i++) {
char letter = phoneNumber.charAt(i);
if (Character.isAlphabetic(letter)) {
letter = Character.toUpperCase(letter);
switch (letter) {
case 'A':
case 'B':
case 'C':
keypadNum = 2;
break;
case 'D':
case 'E':
case 'F':
keypadNum = 3;
break;
case 'G':
case 'H':
case 'I':
keypadNum = 4;
break;
case 'J':
case 'K':
case 'L':
keypadNum = 5;
break;
case 'M':
case 'N':
case 'O':
keypadNum = 6;
break;
case 'P':
case 'Q':
case 'R':
case 'S':
keypadNum = 7;
break;
case 'T':
case 'U':
case 'V':
keypadNum = 8;
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
keypadNum = 9;
break;
default:
System.out.println("Invalid phone number");
}
phoneNumber = phoneNumber.substring(0, i) + keypadNum + phoneNumber.substring(i + 1);
}
}
return phoneNumber;
}
}
Expected Output:
You could use a regular expression with String.replaceAll. Remove the leading one, group the first three digits, the second three digits and the final group of digits. Something like
public static String formatNumber(String phoneNumber) {
if (phoneNumber.startsWith("1")) {
phoneNumber = phoneNumber.substring(1);
}
return phoneNumber.replaceAll("(\\d{3})(\\d{3})(\\d+)", "1-$1-$2-$3");
}
or
public static String formatNumber(String phoneNumber) {
return phoneNumber.replaceAll("1(\\d{3})(\\d{3})(\\d+)", "1-$1-$2-$3");
}
And then call it like
System.out.println(formatNumber(getNumber(phoneNumber)));
I ran it with 1800flowers and got (as expected)
1-800-356-9377
or without regular expressions like
public static String formatNumber(String phoneNumber) {
if (phoneNumber.startsWith("1")) {
phoneNumber = phoneNumber.substring(1);
}
return "1-".concat(phoneNumber.substring(0, 3)) //
.concat("-").concat(phoneNumber.substring(3, 6)) //
.concat("-").concat(phoneNumber.substring(6));
}
Before calling formatNumber, you can remove the dashes to normalize it with something like
public static String removeDashes(String phoneNumber) {
StringBuilder sb = new StringBuilder();
for (char ch : phoneNumber.toCharArray()) {
if (ch != '-') {
sb.append(ch);
}
}
return sb.toString();
}
Then
System.out.println(formatNumber(removeDashes(getNumber(phoneNumber))));

Why isn't my Java switch statement working?

I am trying to do the following for a Java switch method with a series of JUnit Asserts but am stuck on using "less than" and "greater than" for two cases (see string/int error below), and am not sure how to use the ">" and "<" in my cases.
Here is the exercise followed by my code, followed by the error.
/*
Create a method which uses a switch statement to return a String representing the int passed in as a parameter to the method:
• given 1 return "One"
• given 2 return "Two"
• given 3 return "Three"
• given 4 return "Four"
• given an integer > 4, return "Too big"
• given an integer < 1, return "Too small"
*/
#Test
public void switchIntExample() {
assertEquals("One", stringRepInt(1));
assertEquals("Two", stringRepInt(2));
assertEquals("Three", stringRepInt(3));
assertEquals("Four", stringRepInt(4));
assertEquals("Too big.", stringRepInt(>4));
// assertEquals("Too small.", stringRepInt(<4));
}
//Switch statement for above:
public String stringRepInt(int numberSize) {
String numVar = null;
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
//TODO: question on how to do LESS THAN and GREATER THAN:
// error line:
case (numVar > 4):
numVar = "Too big.";
break;
default:
break;
}
System.out.println(numVar);
return numVar;
}
ERROR:
Error:(293, 27) java: bad operand types for binary operator '>'
first type: java.lang.String
second type: int
case statements only support constant expressions (you cannot do less than, or greater than, in a case and you can't test numVar - the String - with less than). You can use an if and something like
public String stringRepInt(int numberSize) {
String numVar = null;
if (numberSize > 4) {
numVar = "Too big.";
} else {
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
default:
break;
}
System.out.println(numVar);
return numVar;
}
You should add it to the default section, so like this:
default:
numVar = "Too Big";
break;
The purpose of the default section is to deal with all cases not dealt with by the switch cases. You should be taking advantage of that (as #GreenMatt and #FredK mentioned in comments) by putting the 'if checks' in the default section, as follows:
public String stringRepInt(int numberSize) {
String numVar = null;
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
default:
if(numberSize > 4)
numVar = "Too big";
break;
}
System.out.println(numVar);
return numVar;
}
Further, you could add else if (numberSize < 1) numVar = "Too small"; under the if statement if you want to check for number's smallest than one. This is also important because it prevents your method from returning null. (Which currently happens if the user enters a value less than 1)
The resulting code is as follows:
public String stringRepInt(int numberSize) {
String numVar = null;
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
default:
if(numberSize > 4)
numVar = "Too big";
else
numVar = "Too small";
break;
}
System.out.println(numVar);
return numVar;
}
In the error line you are comparing String and int.
error line: case (numVar > 4): numVar = "Too big."; break;
you have declared numVar as String and comparing that with int value 4. Please correct that or I think you are trying to compare numberSize with value 4. Convert that String to int and compare it.

How do you place a class in the default package in netbeans for Mac?

My instructor requires us to take the package from our code and make it a default package. The only problem is he taught us how to do that through Windows and I have a MacBook so his way isn't working. I can't figure out how to do it. I've attached the code to the bottom in case that will help.
package romannumeralcalculator;
import java.util.*;
public class RomanNumeralCalculator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int integer;
do {
System.out.print("Please enter an interger from 1 to 5999. Enter a negative number to exit. \n ->");
integer = input.nextInt();
} while (integer >= 6000);
while (integer == 0) {
System.out.println("");
break;
}
String results = "";
int ones = integer % 10;
int tens = (integer / 10) % 10;
int hundreds = (integer / 100) % 10;
int thousands = (integer / 1000) % 1000;
switch (thousands) {
case 1:
results += "M";
break;
case 2:
results += "MM";
break;
case 3:
results += "MMM";
break;
case 4:
results += "MMMM";
break;
case 5:
results += "MMMMM";
break;
default:
System.out.println("");
}
switch (hundreds) {
case 1:
results += "C";
break;
case 2:
results += "CC";
break;
case 3:
results += "CCC";
break;
case 4:
results += "CD";
break;
case 5:
results += "D";
break;
case 6:
results += "DC";
break;
case 7:
results += "DCC";
break;
case 8:
results += "DCCC";
break;
case 9:
results += "CM";
break;
default:
System.out.println("");
}
switch (tens) {
case 1:
results += "X";
break;
case 2:
results += "XX";
break;
case 3:
results += "XXX";
break;
case 4:
results += "XL";
break;
case 5:
results += "L";
break;
case 6:
results += "LX";
break;
case 7:
results += "LXX";
break;
case 8:
results += "LXXX";
break;
case 9:
results += "XC";
break;
default:
System.out.println("");
}
switch (ones) {
case 1:
results += "I";
break;
case 2:
results += "II";
break;
case 3:
results += "III";
break;
case 4:
results += "IV";
break;
case 5:
results += "V";
break;
case 6:
results += "VI";
break;
case 7:
results += "VII";
break;
case 8:
results += "VIII";
break;
case 9:
results += "IX";
break;
default:
System.out.println("");
}
System.out.println(results);
}
}
In the projects tab of Netbeans in the top-left:
Expand the tree for your Project.
Expand the Source Packages folder.
Expand the package with your java file.
Drag the java file from under the package to the Source Packages folder.
A dialog box will pop up with the title Move Class. On that dialog click the Refactor button.
This should be the same procedure in Windows. I am not sure why your professor told you something different.

Number to Word Conversion in Java

I have this homework assignment for this class I'm retaking, the problem I'm running into is that I'm over-thinking the solution. I have to create a program that converts a four digit number to words.
(Example: 1134 becomes "One One Three Four")
I have a basic code, but it's bulky and ugly. I'm also only allowed to use basic if and switch statements, we have to use a switch statement as well.
Am I over thinking this? I can't figure out how to make this code shorter and I only want to use one switch statement without a while loop. Is it even possible or is this as short as it gets.
Here's my code.
import java.util.Scanner;
public class NumberToWords {
public static void main(String[] args) {
//Set up scanner.
Scanner kb = new Scanner(System.in);
//Ask for a 4 digit integer.
System.out.println("Enter a 4 digit number.");
//Store 4 digit number into a variable
int number = kb.nextInt();
//Seperate number into digits.
int digit4 = number%10;
number = number/10;
int digit3 = number%10;
number = number/10;
int digit2 = number%10;
number = number/10;
int digit1 = number%10;
number = number/10;
//Set up a switch statement to read through the number.
switch (digit1)
{
case 1: System.out.print("One ");break;
case 2: System.out.print("Two "); break;
case 3: System.out.print("Three "); break;
case 4: System.out.print("Four "); break;
case 5: System.out.print("Five "); break;
case 6: System.out.print("Six "); break;
case 7: System.out.print("Seven "); break;
case 8: System.out.print("Eight "); break;
case 9: System.out.print("Nine "); break;
case 0: System.out.print("Zero "); break;
default: System.out.print(""); break;
}
switch (digit2)
{
case 1: System.out.print("One ");break;
case 2: System.out.print("Two "); break;
case 3: System.out.print("Three "); break;
case 4: System.out.print("Four "); break;
case 5: System.out.print("Five "); break;
case 6: System.out.print("Six "); break;
case 7: System.out.print("Seven "); break;
case 8: System.out.print("Eight "); break;
case 9: System.out.print("Nine "); break;
case 0: System.out.print("Zero "); break;
default: System.out.print(""); break;
}
switch (digit3)
{
case 1: System.out.print("One ");break;
case 2: System.out.print("Two "); break;
case 3: System.out.print("Three "); break;
case 4: System.out.print("Four "); break;
case 5: System.out.print("Five "); break;
case 6: System.out.print("Six "); break;
case 7: System.out.print("Seven "); break;
case 8: System.out.print("Eight "); break;
case 9: System.out.print("Nine "); break;
case 0: System.out.print("Zero "); break;
default: System.out.print(""); break;
}
switch (digit4)
{
case 1: System.out.print("One ");break;
case 2: System.out.print("Two "); break;
case 3: System.out.print("Three "); break;
case 4: System.out.print("Four "); break;
case 5: System.out.print("Five "); break;
case 6: System.out.print("Six "); break;
case 7: System.out.print("Seven "); break;
case 8: System.out.print("Eight "); break;
case 9: System.out.print("Nine "); break;
case 0: System.out.print("Zero "); break;
default: System.out.print(""); break;
}
}
}
First, write a method to convert a single digit to a word. Something like,
private static String digitToWord(char ch) {
switch(ch) {
case '0': return "Zero";
case '1': return "One";
case '2': return "Two";
case '3': return "Three";
case '4': return "Four";
case '5': return "Five";
case '6': return "Six";
case '7': return "Seven";
case '8': return "Eight";
case '9': return "Nine";
}
return "Unknown (" + ch + ")";
}
Then you can get the String value of your int. And get the four characters from that String. Something like,
int number = kb.nextInt();
String str = String.format("%04d", number);
StringBuilder sb = new StringBuilder();
sb.append(digitToWord(str.charAt(0)).append(' ');
sb.append(digitToWord(str.charAt(1)).append(' ');
sb.append(digitToWord(str.charAt(2)).append(' ');
sb.append(digitToWord(str.charAt(3));
System.out.println(sb.toString());
Or,
String str = String.format("%04d", kb.nextInt());
System.out.printf("%s %s %s %s%n", digitToWord(str.charAt(0)),
digitToWord(str.charAt(1)), digitToWord(str.charAt(2)),
digitToWord(str.charAt(3)));
this might help
public class NumbersInWords {
public static void main(String[] args) {
String number = "153";
int numLength = number.length();
System.out.println(numLength);
String numberToWord = "";
for (int j = 0; j < numLength; j++) {
switch (number.charAt(j)) {
case '1': {
numberToWord = numberToWord + "one";
break;
}
case '2': {
numberToWord = numberToWord + "two";
break;
}
case '3': {
numberToWord = numberToWord + "three";
break;
}
case '4': {
numberToWord = numberToWord + "four";
break;
}
case '5': {
numberToWord = numberToWord + "five";
break;
}
case '6': {
numberToWord = numberToWord + "six";
break;
}
case '7': {
numberToWord = numberToWord + "seven";
break;
}
case '8': {
numberToWord = numberToWord + "eight";
break;
}
case '9': {
numberToWord = numberToWord + "nine";
break;
}
default: {
numberToWord = numberToWord + "zero";
}
}
}
System.out.println(numberToWord);
}
}
Yeah, you can simply do that operation in a for loop, executed 4 times. The division and mod is consistent at 10. Something like
For i = 0; i < 4; i++
Number/10%10
Condition to check number
Save number in array or print
Copy pasting code and names with numbers should be a red flag to use a loop (or something more is worng).
private static final String[] DIGIT_NAMES = new String[] {"Zero ", "One ", "Two ",
"Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine "};
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = 0;
do {
// ask for a 4 digit integer
System.out.println("Enter a 4 digit number: ");
try {
number = input.nextInt();
} catch (InputMismatchException ignore) {
System.out.println("Recieved non integer input");
input.next(); // clear bad input
}
} while (number < 1000 || number > 9999);
String result = "";
while (number != 0) {
result = DIGIT_NAMES[number % 10] + result;
number = number / 10;
}
System.out.println(result);
input.close();
}

something wrong with calculation code?

this code is supposed to recieve two integers and an operation and then calculate the numbers. this is only part of the entire program everything else works but the calculations are wrong. The only correct output that i get when i run the whole thing is the subtraction. Whats wrong with it?
public static double calculate(int operand1, int operand2, char operation)
{
if (operation=='^')
{
return (Math.pow(operand1,operand2));
}
else if(operation=='+')
{
return ((operand1)+(operand2));
}
else if(operation=='-')
{
return (operand1-operand2);
}
else if(operation=='*')
{
return (operand1*operand2);
}
else
{
if (operand2==0)
{
System.out.println("Cant divide by zero");
}
return(operand1/operand2);
}
}
Here is the entire code for the program
import java.util.Scanner;
public class Calculator
{
public static void main(String[] args)
{
printIntro();
Scanner kb = new Scanner(System.in);
String answer = "yes";
while (answer.equals("yes"))
{
System.out.println("Enter your problem");
String fullExpression=kb.nextLine();
fullExpression=fullExpression.replaceAll("\\s","");
int length=fullExpression.length();
char op1=fullExpression.charAt(0);
char op2=fullExpression.charAt(1);
String operation=fullExpression.substring(2,length);
printEnglish(op1,op2,operation);
System.out.println("Type yes to continue");
Scanner kb1 = new Scanner(System.in);
answer=kb1.nextLine();
};
}
/*this methods gets the operands and the operation and
prints the English version: if we call this method
printEnglish(2,3, plus), then this method will output:
Two plus three = 5 */
public static void printEnglish(char op1, char op2, String operation)
{
String resultOp1CharToString=charToString(op1);
String resultOp2CharToString=charToString(op2);
char resultOperationConversion=operationConversion(operation);
double resultCalculate=calculate(op1, op2, resultOperationConversion);
System.out.print(resultOp1CharToString+ operationConversion(operation) + resultOp2CharToString+ "=" + resultCalculate);
/*1. call the method charToString(op1) to convertlish
word for example ‘1’ to one or ‘2’ to two,….
2. call the method operandConversionToNumber(op1) to
get its numeric value. For example if op1 is ‘1’ then
this method call should return the integer value 1
3. call the method operationConversion(operation) to
convert the operation to a mathematical operation. For
example if you call this method with the string plus
then it will return ‘+’
4. finally call the method calculate to get the result
of the operation.*/
}
/*this method prints the numeric version which is 2 *3
=6*/
//public static boolean printNumeric(char op1, char op2, String operation)
//{
/*String resultCharToString=charToString(op1);
String resultCharToString2=charToString(op2);
int resultOperandToNumber=operandConversionToNumber(op1);
int resultOperandToNumber2=operandConversionToNumber(op2);
char resultOperationConversion=operationConversion(operation);
double resultCalculate=calculate(op1, op2, operation); */
//}
/*this method gets a number as a character and returns
its numeric value as an integer. You must use case
statement for this method*/
public static int operandConversiontoNumber(char operand)
{
int numberOperand=0;
switch(operand)
{
case '0':
numberOperand=0;
break;
case '1':
numberOperand=1;
break;
case '2':
numberOperand=2;
break;
case '3':
numberOperand=3;
break;
case '4':
numberOperand=4;
break;
case '5':
numberOperand=5;
break;
case '6':
numberOperand=6;
break;
case '7':
numberOperand=7;
break;
case '8':
numberOperand=8;
break;
case '9':
numberOperand=9;
break;
}
return numberOperand;
}
/*this method gets the operation as a string and
return the equivalent operation in math. For example
if it receives “plus” the it will return ‘+’ */
public static char operationConversion(String s)
{
char operation=0;
if(s.equals("plus"))
{
operation= '+';
}
else if(s.equals("minus"))
{
operation= '-';
}
else if(s.equals("multiply"))
{
operation= '*';
}
else if(s.equals("divide"))
{
operation= '/';
}
else
{
operation= '^';
}
return operation;
}
/*this method recives two numbers and the operation
and returns the result*/
public static double calculate(int operand1, int operand2, char operation)
{
if (operation=='^')
{
return (Math.pow(operand1,operand2));
}
else if(operation=='+')
{
return ((operand1)+(operand2));
}
else if(operation=='-')
{
return (operand1-operand2);
}
else if(operation=='*')
{
return (operand1*operand2);
}
else
{
if (operand2==0)
{
System.out.println("Cant divide by zero");
}
return(operand1/operand2);
}
}
/*this method converst a number character to its
English word for example if this method receives ‘1’
it will return “one” */
public static String charToString(char num)
{
String englishOperand="one";
switch(num)
{
case '0':
englishOperand= "zero";
break;
case '1':
englishOperand="one";
break;
case '2':
englishOperand="two";
break;
case '3':
englishOperand="three";
break;
case '4':
englishOperand= "four";
break;
case '5':
englishOperand= "five";
break;
case '6':
englishOperand= "six";
break;
case '7':
englishOperand= "seven";
break;
case '8':
englishOperand= "eight";
break;
case '9':
englishOperand= "nine";
break;
}
return englishOperand;
}
//this method prints the decription of this program.
public static void printIntro()
{
System.out.println("This program is a calculator, you need to enter two");
System.out.println("single digit numbers and an operation(plus, minus,");
System.out.println("divide, multiply, power) and it outputs its numeric");
System.out.println("and English version. Your operand and operation can be");
System.out.println("separated by space(s) or there could be no spaces");
System.out.println("between them. For example you can enter “23plus” or “2 3 plus”");
}
}
I entered 2 3 plus and i expect 5 but i dont recieve that, but when i enter 2 3 minus i recieve -1
if (operand2==0)
{
System.out.println("Cant divide by zero");
return -1; // some dummy value
}
else
{
return(operand1/operand2);
}
Division will be incorrect as it's doing integer division and you want a double result. It will also throw a divide by zero error because you don't return.
if (operand2 == 0)
{
System.out.println("Cant divide by zero");
return 0; // I guess
}
return (double)operand1 / (double)operand2;
All the rest look like they should work fine.

Categories