Checking if a String is a number using switch - java

I have to make a program which tells if a String that I type in my keyboard is a number, by using a switch. I know how to do it with try and catch, but I don't know how to do it with switch.
Any tips?

You would need to check each characer in the String. Something like this would probably work.
static boolean isNumber(String s) {
if (s == null) {
// Debatable.
return false;
}
int decimalCount = 0;
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
// These are all allowed.
break;
case '.':
if (i == 0 || decimalCount > 0) {
// Only allow one decimal in the number and not at the start.
return false;
}
decimalCount += 1;
break;
default:
// Everything else not allowed.
return false;
}
}
return true;
}

Up to Java7 you can use switch(String) statement.
But here you have enough with switch(int) and a little workaround:
public static void main(String[] args) throws Exception {
String a = "2";
switch (Integer.parseInt(a)) {
default:
System.out.print("is a number");
break;
}
}

This is the solution I got asking to some classmates and thinking it quietly.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner entry = new Scanner(System.in);
String myNumber;
int tf;
myNumber = entry.next();
try {
Double.parseDouble(myNumber);
tf = 1;
}
catch (Exception e) {
tf = 0;
}
switch(tf) {
case 1:
System.out.println("Is a number");
break;
default:
System.out.println("No es un nĂºmero");
break;
}
}
Thanks to the community for being so nice!

I came up with a shorter code BUT it uses regular expressions, which if Halo is just starting with Java, he may have not seen that topic yet. But then it answers the question too so here it is:
Scanner scanner = new Scanner(System.in);
String expression = scanner.nextLine();
String matches = new Boolean(expression.matches("\\d+")).toString();
switch (matches) {
case "true":
System.out.println("IT'S a number");
break;
case "false":
System.out.println("NOT a number");
}
scanner.close();

Related

need help making a looping user input program

I'm making a looping user input program and my problem is that it cannot loop, it always end after displaying the statement "Again?" without asking for an user input again.
Here's the code:
public static void main(String[] args){
String yes;
do{
Scanner scan = new Scanner (System.in);
System.out.print("Enter a number from 1 to 10: ");
int num = scan.nextInt();
switch(num){
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 10:
System.out.print("Ten");
break;
default:
System.out.print ("Invalid Number!");
break;
}
System.out.print("\nAgain? y/n");
yes = scan.nextLine();
}while(yes.equals('y'));
}
}
try to use scanner.next() instead of nextLine.
And at the loop. You defined 'y'. The single quotes there means that this is a char and not a string. For that reason the loop condition is never 'true'.
See the equal of String
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String aString = (String)anObject;
if (coder() == aString.coder()) {
return isLatin1() ? StringLatin1.equals(value, aString.value)
: StringUTF16.equals(value, aString.value);
}
}
return false;
}
The given value is not instance of String => false
PS: You should also try not to define the scanner on every loop cycle ;)

Taking int input and parsing into char

So my main got deleted 2 days ago and my teacher helped me a bit with the switch code. I rebuilt the code yesterday and he was away yesterday and could not help me.
public static void main(String[] args) throws InterruptedException {
do {
try {
System.out.println("Enter your birthYear");
birthYear = Integer.parseInt(input.next());
int length = String.valueOf(birthYear).length();
System.out.println(length);
if (length != 4) {
lengthTest = false;
System.out.println("Invalid Choice");
} else {
lengthTest = true;
}
test = true;
} catch (Exception e) {
System.out.println("Invalid Choice");
}
} while (test == true ^ lengthTest != false);
do {
System.out.println("Please enter a number between 1-4 \n"
+ "1 = AreaOfTriangle \n" +
"----------------------------------\n" +
"2 = HoursToDaysAndHours Calculator \n" +
"---------------------------------- \n" +
"3 = CelciusToFahrenheit Calculator \n" +
"----------------------------------\n" +
"4 = BirthdayGame \r\n" +
"----------------------------------");
try {
choice = Integer.toString(input.nextInt()).charAt(0);
System.out.println(choice);
switch (choice) {
case 1:
aOT.areaOfTriangle();
break;
case 2:
hTDAH.hoursToDaysAndHours();
break;
case 3:
cTF.celciusToFahrenheit();
case 4:
System.out.println("Code not implemented");
break;
case 'e':
repeat = false;
break;
default:
System.out.println("");
break;
}
}catch (Exception e) {
System.out.println("Invalid Awnser");
}
} while (repeat == true);
}
My problem is in my switch case i want to be able to use int's and Char's at the same time. For example i want to use e to exit and and the 4 numbers
You can try to use String as an input paramenter, then any int value or char will be readed correctly without necessity to convert them:
try {
String choice = input.next();
System.out.println(choice);
switch (choice) {
case "1":
aOT.areaOfTriangle();
break;
case "2":
hTDAH.hoursToDaysAndHours();
break;
case "3":
cTF.celciusToFahrenheit();
case "4":
System.out.println("Code not implemented");
break;
case "e":
repeat = false;
break;
default:
System.out.println("");
break;
}
You can't use int and chars at the same time, as you can only use one variable and a variable has to have a type, but:
If you cast a char or Character to int you get values. For example ((int) 'e') evaluates to 101 if I am not mistaken. (Try System.out.println((int) 'e'));
So in your case, you can switch over int values and detect for 1,2,3,4 and 101.
Your default should also throw an exception and you are fine.
Happy Coding
You could just use the char representations of the digits 1-4:
char choice = input.next().charAt(0);
switch (choice) {
case '1':
aOT.areaOfTriangle();
break;
case '2':
hTDAH.hoursToDaysAndHours();
break;
case '3':
cTF.celciusToFahrenheit();
case '4':
System.out.println("Code not implemented");
break;
case 'e':
repeat = false;
break;
default:
System.out.println("");
break;
}

Validate the input using a while loop

I doing a little practice on Computer Science because when I leave the military I want to start taking classes on the basics of java. I'm a little stuck on this question i was wondering if i can get some assistance.
a program that allows the user to enter a character. The only valid values are 'A', 'M', and 'S'. Validate the input using a while loop so that if the user enters any value other than one of those 3 characters, an error message is displayed and the user is prompted for another value. Once the user has finally entered valid data, print the character they entered back to the screen.
You can look into this basic example
import java.util.Scanner;
public class Read {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean isCheck = true;
while (isCheck) {
String str = sc.next();
switch (str) {
case "A":
System.out.println("A");
isCheck = false;
break;
case "M":
System.out.println("M");
isCheck = false;
break;
case "S":
System.out.println("S");
isCheck = false;
break;
default:
System.out.println("Not Valid : Enter next");
isCheck = true;
}
}
}
}
Reading you input within the loop will enforce repetitive reading of input.
public class Read {
public static void main(String[] args) {
boolean isCheck = true;
while(isCheck){
Scanner sc = new Scanner(System.in);
String str = sc.next();
switch (str) {
case "A":
System.out.println("A");
isCheck = false;
break;
case "M":
System.out.println("M");
isCheck = false;
break;
case "S":
System.out.println("S");
isCheck = false;
break;
default:
System.out.println("Not Valid : Enter next.");
isCheck = true;
}
}
}
}

Why do I get this "unreachable statement" error?

I am converting a roman numeral input to it's integer value. In my convertChar method, I keep getting an error that it is an unreachable statement whenever I add a break statement in to the code. I don't know why this is. I'm a new student and I must have done something wrong and I was hoping maybe someone can show me what I did wrong and how to fix it. It must have something to do with the way I set the methods up right? I still get confused on what variables to input so maybe I messed up there but I'm not experienced enough to know exactly what I did wrong. Here is everything I have:
public class RomanNumeralConverter {
public int romanInput() {
return convert(getUserInput());
}
public String getUserInput() {
Scanner numberInput = new Scanner (System.in);
System.out.print("Enter a roman numeral in uppercase: ");
String userInput = numberInput.next();
numberInput.close();
return userInput;
}
public int convert (String userInput) {
int result = 0;
int subtractamount = 0;
int x = userInput.length();
while(x != 0) {
char romanConvert = userInput.charAt(x);
if(x >= 1) {
if(convertChar(romanConvert) >= convertChar(userInput.charAt(x - 1))) {
subtractamount += convertChar(userInput.charAt(x - 1));
}
}
result += convertChar(romanConvert);
x--;
}
result -= subtractamount;
return result;
}
public static char convertChar(char value) {
switch (value) {
case 'I':
return 1;
break;
case 'V':
return 5;
break;
case 'X':
return 10;
break;
case 'L':
return 50;
break;
case 'C':
return 100;
break;
case 'D':
return 500;
break;
case 'M':
return 1000;
break;
default:
System.out.println("Invalid character!");
return 0;
break;
}
return value;
}
public void printValue() {
System.out.println(romanInput());
}
public static void main(String[] args) {
new RomanNumeralConverter().printValue();
}
}
Your problem lies in your switch statement. You can minimize this occurring elsewhere by attempting to have methods return only once (which i think is best practice)
public static char convertChar(char value) {
char result;
switch (value) {
case 'I':
result = 1;
break;
case 'V':
result = 5;
break;
case 'X':
result = = 10;
break;
case 'L':
result = 50;
break;
case 'C':
result = 100;
break;
case 'D':
result = 500;
break;
case 'M':
result = 1000;
break;
default:
System.out.println("Invalid character!");
result = 0;
break;
}
return result
}
In Java, it is a compile error to have statements that will never be reached while execution. In your case, the break statement will never be reached as there is a return statement above it. Also that last return statement will never be reached as you already would have returned in any case by the end of the switch block.
The problem is in your switch statement.
A default case can be thought of like the else in an if-else statement; it will always execute if no other condition in the switch is satisfied. If you are performing a return (or throw) inside of a default case, any code that follows after that will not be reachable.
You have two options:
Change the return statements to only assign a value to result instead, meaning that there's only one point of return from your code, or
Remove the return result from after your switch.

How to convert phonetic phone number to numeric phone number?

public class Driver
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String phoneNumber;
System.out.print("Enter a phonetic phone number: ");
phoneNumber = input.nextLine();
int i = 0;
while (i != phoneNumber.length())
{
char c = phoneNumber.charAt(i);
i++;
if (Character.isDigit(c) == true)
{
phoneNumber = String.valueOf(c);
}
else if (Character.isLetter(c) == true)
{
decode(c);
}
else
{
System.out.println("Improper input");
}
}
System.out.println("Numeric version of phone number: " + phoneNumber);
}
private static String decode(char c)
{
switch (c)
{
case 'A':
case 'B':
case 'C':
return "2";
case 'D':
case 'E':
case 'F':
return "3";
case 'G':
case 'H':
case 'I':
return "4";
case 'J':
case 'K':
case 'L':
return "5";
case 'M':
case 'N':
case 'O':
return "6";
case 'P':
case 'Q':
case 'R':
case 'S':
return "7";
case 'T':
case 'U':
case 'V':
return "8";
case 'W':
case 'X':
case 'Y':
case 'Z':
return "9";
}
return " ";
}
}
Right now my output is only showing the numeric value for the first digit. I'm not exactly sure what I need to do to display the whole string once it is converted from phonetic to numeric. Help would be much appreciated.
You are not changing your phone number actually, you can declare other variable to add changed characters which should be declared outside the loop.
String changedNumber="";//declare outside loop
//...
if (Character.isDigit(c) == true) {
changedNumber += String.valueOf(c);
} else if (Character.isLetter(c) == true) {
changedNumber += String.valueOf(decode(c));
} else {
System.out.println("Improper input");
}
Right now you are directly assigning digit to phoneNumber and you are just calling decode but you are not using returned value.
phoneNumber = String.valueOf(c);
String temp=""
while (i != phoneNumber.length()) {
char c = phoneNumber.charAt(i);
i++;
if (Character.isDigit(c) == true) {
temp += String.valueOf(c);
} else if (Character.isLetter(c) == true) {
temp += decode(c);
} else {
System.out.println("Improper input");
}
}
phoneNumber = temp;
System.out.println("Numeric version of phone number: " + phoneNumber);
The phoneNumber is never changed. You can create a new string called numericPhoneNumber and manipulate it instead.
And the next issue is this line.
phoneNumber = String.valueOf(c);
You are assigning the phoneNumber to the single character. You need to append that. A fixed version would be this.
String numericPhoneNumber = "";
for (char ch : phoneNumber.toCharArray())
{
if (Character.isLetter(ch))
numericPhoneNumber += decode(ch);
else
numericPhoneNumber += ch;
}
There is no need to check for digit, they will be handled by the else block. Hope this helps.
Okay, a couple things. First off, you are not assigning the changes to a new string. Add a temporary string and use += to assign the new changes, or, an even better approach, create a new StringBuilder object and append the changes using the .append() method:
Scanner input = new Scanner(System.in);
String phoneNumber;
System.out.print("Enter a phonetic phone number: ");
phoneNumber = input.nextLine();
StringBuilder sb = new StringBuilder(); //StringBuilder Object
for (int i = 0; i < phoneNumber.length(); i++)
{
if (Character.isLetter(phoneNumber.charAt(i)))
{
sb.append(decode(phoneNumber.charAt(i))); //Nice, easy-to-use append() method, which takes objects of most types
}
else if (Character.isDigit(phoneNumber.charAt(i)))
{
sb.append(phoneNumber.charAt(i));
}
else
{
System.out.println("Improper input");
}
}
System.out.println("Numeric version of phone number: " + sb.toString());
Second thing I should mention, your decode(char c) function, while well written, should convert the parameter to upper case when you use it, just in case someone enters a lowercase letter:
switch (Character.toUpperCase(c))
{
//case statements
}

Categories

Resources