Taking int input and parsing into char - java

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;
}

Related

Checking if a String is a number using switch

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();

.hasNextInt() in switch statement

I'm basically trying to validate so that you can only enter an Integer. This is what I have at the moment, but if I type letters it goes through the switch and just leaves the result as blank.
I want it so that if anything other than an integer is entered it will go to default in the switch.
Any help would be great. Thanks!
while(loop && kb.hasNextInt())
{
choice = kb.nextInt();
switch(choice)
{
case 1 :
language = "FRENCH";
loop = false;
break;
case 2 :
language = "GERMAN";
loop = false;
break;
case 3 :
language = "SPANISH";
loop = false;
break;
default :
System.out.println("That is not a correct choice. Please try again!");
break;
}
}
If the next input is not an integer,
then .hasNextInt() will return false,
and therefore the loop will terminate early.
If you want to allow text input and respond to it,
then you need to read line by line, text instead of numbers,
and parse the line read with Integer.parseInt.
If the line cannot be parsed, you will get a NumberFormatException.
You can catch it, and handle appropriately.
while (loop && scanner.hasNextLine()) {
String line = scanner.nextLine();
try {
choice = Integer.parseInt(line);
} catch (NumberFormatException e) {
System.out.println("That is not an integer. Please try again!");
continue;
}
switch (choice) {
case 1:
language = "FRENCH";
loop = false;
break;
case 2:
language = "GERMAN";
loop = false;
break;
case 3:
language = "SPANISH";
loop = false;
break;
default:
System.out.println("That is not a correct choice. Please try again!");
break;
}
}
This is because a letter will cause your while(loop && kb.hasNextInt()) to be false. I suggest put an if statement with the hasNextInt() within the while loop.
Example (using a while loop instead of if statement to really try getting the number):
while(loop)
{
// validate int using while loop
while(!kb.hasNextInt())
{
System.out.println("you must enter a number! ");
kb.next();
}
choice = kb.nextInt();
switch(choice)
{
case 1 :
language = "FRENCH";
loop = false;
break;
case 2 :
language = "GERMAN";
loop = false;
break;
case 3 :
language = "SPANISH";
loop = false;
break;
}
}
System.out.println("Thank You " + studentID + " you have been registered for " + language);
This code will blow before it even begins if the user did not enter a number as the while required kb.hasNextInt() to be true (have a number) to even run.
What I do is that I usually put the validation around where I receive the input:
int choice;
Boolean retry = null;
while(retry == null) {
try{
String input = scanner.nextLine();
choice = Integer.parseInt(input);
retry = false;
}catch(NumberFormatException e){
System.out.println("Please enter a number from 1 to 4.");
}
}
switch(choice){
case 1:
// Do stuff
break;
case 2:
// Do stuff
break;
case 3:
// Do stuff
break;
case 4:
// Do stuff
break;
default:
System.out.println("Something went wrong!");
}

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
}

Switch statement + user input

Thanks for taking your time to help me. I need this switch statement to only accept ints 1-4. Any others entered will ask for input again. Entering 5 will quit the system.
System.out.println("A random numbers list has been generated for you:\n ");
System.out.println("Choose an option:\n1)Form list to be heapified.\n2)Enqueue the integer 10" +
"\n3)Dequeue the integer 10.\n4)Print the updated heap.\n5)Quit the system \n>>");
Scanner scanner = new Scanner( System.in );
int var = 0;
String input = scanner.next();
int answer = Integer.parseInt(input);
do{
input = scanner.next();
answer = Integer.parseInt(input);
var = answer;
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
}
}while(var ==1 || var==2 || var==3
|| var==4);
I cant seem to get it right. Keep making it worse.
Edited:
do{
String input = scanner.next();
int answer = Integer.parseInt(input);
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
h.pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
h.dequeue();//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default: input = scanner.next();
break;
}
}while(var!=5)
;
Try adding a "default:" statement, like this:
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default:
*Add whatever code you want to execute if its greater then or equal to 5 here!*
}while(var ==1 || var==2 || var==3
|| var==4);
You can set a 'default' case.
default: doSomething();
break;
This will be invoked when a user enters a value that isn't one of your cases.
} while (answer != 5);
This should make the loop break when 5 is entered.
EDIT:
Also, you need to switch on the answer variable instead of 'var'
switch(answer) {
You don't need to put it in a loop. The use case is simple:
For 1-4 : do something and then return
For 5: quit/return Everything
else: ask for input again
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int answer = Integer.parseInt(scanner.next());
switch(answer) {
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
case 5:
return; // System.exit(0) or quit however you want to
default:
answer = Integer.parseInt(scanner.next());
}
}

Convert Hexadecimal number to decimal in Java (Android)

As in the title above. I want take the hex number from an EditText
EditText number = (EditText) findViewById (R.id.etDisplay);
Editable stringEditable = number.getText().toString;
String nuovo = stringEditable.toString();
I want to convert nuovo to a decimal number.
int i = Integer.parseInt(nuovo, 16);
int i = Integer.parseInt(nuovo,16);
The accepted answer will work in some cases, but if your number may be bigger than Integer.MAX_VALUE, you may want to use something like this:
public static long hexToLong(String hex) {
return Long.parseLong(hex, 16);
}
Try Integer.parseInt(nuovo,16).
Here's a small demo for you. It uses the java.util.Scanner and coverts it.
import java.util.Scanner;
public class hex {
static long dec=0;
static long squ(int i)
{
long pow=16;
if(i==0)
{
return 1;
}
else if(i==1)
{
return pow;
}
else
{
for(int k=2;k<=i;k++)
{
pow=pow*16;
}
return pow;
}
}
public static void main(String[] args) {
Scanner so=new Scanner(System.in);
System.out.println("enter the hexa decimal no");
String hx=so.next();
hx.toLowerCase();
char c[]=hx.toCharArray();
int j=c.length;
int x=j;
int i=0;
j--;
while(j>=0)
{
if(c[j]=='a'|c[j]=='b'|c[j]=='c'|c[j]=='d'|c[j]=='e'|c[j]=='f'|c[j]=='1'|c[j]=='2'|c[j]=='3'|c[j]=='4'|c[j]=='5'|c[j]=='6'|c[j]=='7'|c[j]=='8'|c[j]=='9')
{
j--;
}
else
{
i++;
break;
}
}
if(i>0)
{
System.out.println("its not hex decimal no");
}
else
{
System.out.println("it s hex decimal no");
x--;
int xy=0;
while(x>=0)
{
long z=squ(xy);
++xy;
char r=c[x];
String s=""+r;
switch(s)
{
case "a": dec=dec+(10*z);
break;
case "b": dec=dec+(11*z);
break;
case "c": dec=dec+(12*z);
break;
case "d": dec=dec+(13*z);
break;
case "e": dec=dec+(14*z);
break;
case "f": dec=dec+(15*z);
break;
case "1": dec=dec+(1*z);
break;
case "2": dec=dec+(2*z);
break;
case "3": dec=dec+(3*z);
break;
case "4": dec=dec+(4*z);
break;
case "5": dec=dec+(5*z);
break;
case "6": dec=dec+(6*z);
break;
case "7": dec=dec+(7*z);
break;
case "8": dec=dec+(8*z);
break;
case "9": dec=dec+(9*z);
break;
case "0": dec=dec+(0*z);
break;
default:System.out.println("cant find****"+s);
break;
}
x--;
}
System.out.println("final decimal equ is*****"+dec);
}
}
}

Categories

Resources