Phone numbers in java - java

I've got the code to put a seven letter phrase into a phone number. The hyphen is not returning in the correct spot. I really don't know how to fix this problem. It should return xxx-xxxx and if the phrase is xxxx xxx it returns xxxx-xxx. Please someone help me with this problem!
Code:
import java.util.*;
import java.lang.*;
public class Project1 {
public static char getNumber(char letter) {
char ret = 0;
if (letter== 'A' || letter=='a' || letter== 'B' || letter=='b' || letter=='C' || letter=='c') {
return '2';
}
else if (letter== 'D' || letter=='d' || letter== 'E' || letter=='e' || letter=='F' || letter=='f') {
return '3';
}
else if (letter== 'G' || letter=='g' || letter== 'H' || letter=='h' || letter=='I' || letter=='i') {
return '4';
}
else if (letter== 'J' || letter=='j' || letter== 'K' || letter=='k' || letter=='L' || letter=='l') {
return '5';
}
else if (letter== 'M' || letter=='m' || letter== 'N' || letter=='n' || letter=='O' || letter=='o') {
return '6';
}
else if (letter== 'P' || letter=='p' || letter== 'Q' || letter=='q' || letter=='R' || letter=='r'|| letter=='S' || letter=='s') {
return '7';
}
else if (letter== 'T' || letter=='t' || letter== 'U' || letter=='u' || letter=='V' || letter=='v') {
return '8';
}
else if (letter== 'W' || letter=='w' || letter== 'X' || letter=='x' || letter=='Y' || letter=='y' || letter=='Z' || letter=='z') {
return '9';
}
if (letter == ' ')
return '-';
return ret;
}
public static void main (String[] arg) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a 7 letter phrase: ");
String number = input.nextLine();
for (int i = 0; i < 8; i++) {
System.out.print(getNumber(number.toUpperCase().charAt(i)));
}
}
}

It should return xxx-xxxx and if the phrase is xxxx xxx it returns xxxx-xxx. Please someone help me with this problem!
Here you go! A bit of regex is always good for the soul:
{
String number = input.nextLine();
final StringBuilder builder = new StringBuilder(); // Buffer the sequence.
for (int i = 0; i < 8; i++) {
builder.append(getNumber(number.toUpperCase().charAt(i)));
if (builder.toString().getCharAt(2) != '-') // If the format isn't correct, fix it
System.out.println(builder.toString().replaceFirst("(...)(.).(...)", "$1-$2$3"))
}
}
As seen from CSáµ 's comment, you can use the following universal regex instead, such that the section becomes:
builder.toString().replaceFirst("^\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*$", "$1$2$3-$4$5$6$7");
Edit: Updated regex as \N backreferences does not work in Java.

Here's a quick and dirty solution to your problem.
import java.util.*;
public class Project1 {
public static char getNumber(char letter) {
char ret = 0;
if( letter < 'A' )
{
ret = '0';
}
else if( letter < 'D' )
{
ret = '2';
}
else if( letter < 'G' )
{
ret = '3';
}
else if( letter < 'J' )
{
ret = '4';
}
else if( letter < 'M' )
{
ret = '5';
}
else if( letter < 'P' )
{
ret = '6';
}
else if( letter < 'T' )
{
ret = '7';
}
else if( letter < 'W' )
{
ret = '8';
}
else if( letter <= 'Z' )
{
ret = '9';
}
else
{
ret = '0';
}
return ret;
}
public static void main (String[] arg) {
Scanner input = new Scanner(System.in);
System.out.println( "Please enter a 7 letter phrase: " );
String number = input.nextLine().toUpperCase();
StringBuffer buff = new StringBuffer();
for( int i = 0, j = 0; j < number.length() && i < 7; j++ )
{
char c = number.charAt(j);
if( c != ' ' )
{
if( i == 3 )
{
buff.append( '-' );
}
buff.append( getNumber( c ) );
i++;
}
}
System.out.println( buff );
}
}
Key points:
There is no need to check for lower case if the alpha characters are guaranteed to be uppercase.
There is no need to uppercase the input string on each iteration of the loop. Do it once at the beginning.
I'm ignoring spaces, and always adding a hyphen before I print position 3 (ie the fourth character).
chars can be compared just like numbers, using ranges. This simplifies the amount of code quite a bit (ie. each letter within a range doesn't need to be written down).

Related

Creating an Ubbi Dubbi translator in Java

I'm in an entry java class, and for one of my programs I am expected to create a ubbi dubbi translator, which ads a ub before every vowel and vowel cluster. I cannot figure out how to get my program to run correctly, and also am unsure how to make it exclude the extra vowel included with the cluster. I am not allowed to use Stringbuilder..
public void buttonPressed()
{
String lowerCase = "";
String userInput = input.getText();
Scanner words = new Scanner( userInput );
String ubbiDubbi = "";
//Splits up user input by line
while (words.hasNext()) {
//Converting to lower case.
lowerCase = words.next().toLowerCase();
System.out.println(lowerCase);
}
for (int i = 0; i < lowerCase.length(); i++) {
if (lowerCase.charAt(i+1) == 'a'){
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else if (lowerCase.charAt(i+1) == 'e') {
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else if (lowerCase.charAt(i+1) == 'i'){
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else if (lowerCase.charAt(i+1) == 'o'){
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else if (lowerCase.charAt(i+1) == 'u') {
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else {
ubbiDubbi += lowerCase.charAt(i);
}
To get this translator to work you basically just need to step through each character in the input and write it to the output. In addition if the input is a vowel you need to write "ub" out first, except where the previous character was also a vowel.
One thing which is going to be handy is to be able to identify vowels. Starting by writing a function for this is a good idea. It could look like:
private boolean isVowel(char c) {
return
c == 'a' || c == 'A' ||
c == 'e' || c == 'E' ||
c == 'i' || c == 'I' ||
c == 'o' || c == 'O' ||
c == 'u' || c == 'U';
}
Now that's in place if you look at the translation, we want to step over every character in the input and write it to the output. This could look like this:
private String translate(String raw) {
String translated = "";
for(char c:raw.toCharArray()) {
// some extra stuff needed here
translated += c;
}
return translated;
}
For the extra stuff you need to know if the current character is a vowel and whether the previous character was a vowel so we can add a little to do this:
private String translate(String raw) {
String translated = "";
boolean wasLastCharacterVowel = false; //
for(char c:raw.toCharArray()) {
if(isVowel(c)) {
wasLastCharacterVowel = true;
} else {
wasLastCharacterVowel = false;
}
translated += c;
}
return translated;
}
And finally to ad "ub" where required you can check if the character is a vowel and whether the last character was a vowel:
private String translate(String raw) {
String translated = "";
boolean wasLastCharacterVowel = false;
for(char c:raw.toCharArray()) {
if(isVowel(c)) {
if(!wasLastCharacterVowel) {
translated += "ub";
}
wasLastCharacterVowel = true;
} else {
wasLastCharacterVowel = false;
}
translated += c;
}
return translated;
}
With that in place you just need to hook up the button press action etc. So it might look a little like this:
public class UbbiDubbi {
private boolean isVowel(char c) {
return
c == 'a' || c == 'A' ||
c == 'e' || c == 'E' ||
c == 'i' || c == 'I' ||
c == 'o' || c == 'O' ||
c == 'u' || c == 'U';
}
private String translate(String raw) {
String translated = "";
boolean wasLastCharacterVowel = false;
for(char c:raw.toCharArray()) {
if(isVowel(c)) {
if(!wasLastCharacterVowel) {
translated += "ub";
}
wasLastCharacterVowel = true;
} else {
wasLastCharacterVowel = false;
}
translated += c;
}
return translated;
}
public void buttonPressed() {
String userInput = "";// = input.getText();
Scanner words = new Scanner( userInput );
while (words.hasNext()) {
String lowerCase = words.next().toLowerCase();
String translated = translate(lowerCase);
System.out.println(translated);
}
words.close();
}
public static void main(String...none) {
System.out.println(new UbbiDubbi().translate("The quick brown fox jumps over the lazy aadvark"));
}
}
adding the main method gives an easy way to test out the translation. Hope this helps.

Take a string as input and returns valid if it is composed entirely of the characters A, T, C, and G in Java

So, I have this class that takes a string as an argument and returns valid if it is only composed of the characters A, T, C, and G. This is what I have so far.
public class test {
public static void main(String[] args) {
String s = args[0];
for(int i = 0; i < s.length(); i++) {
char chr = s.charAt(i);
if(chr != 'A' || chr != 'C' || chr != 'T' || chr != 'G') {
System.out.println("invalid");
break;
}
System.out.println("valid");
}
}
}
It is returning invalid for everything when CTGATCG should return valid and DGHAIS should return invalid.
I can't figure out what I'm doing wrong. Any ideas?
You have to change your if-statement from:
if(chr != 'A' || chr != 'C' || chr != 'T' || chr != 'G') {
to
if(chr != 'A' && chr != 'C' && chr != 'T' && chr != 'G') {
Each char is not equal to either A or C or the other ones. In your current version, you are basically excluding everything.
Furthermore, you would print "valid" for every char in your input.
The correct code should look like this:
String s = args[0];
for(int i = 0; i < s.length(); i++) {
char chr = s.charAt(i);
if(chr != 'A' && chr != 'C' && chr != 'T' && chr != 'G') {
System.out.println("invalid");
return;
}
}
System.out.println("valid");
If you want to do more stuff in your program, you should use a boolean variable in this case.
How about this:
public class test {
public static void main(String[] args) {
String s = args[0];
if(!s.matches("[ACGT]+")
System.out.println("invalid");
else
System.out.println("valid");
}
}
You don't need all that code. 1 line is all you need:
public static void main(String[] args) {
System.out.println(args[0].matches("[ACGT]*") ? "valid" : "invalid");
}
This code will perform pretty well too.
You should not use || (OR) in this case, you should use && (AND).
Your condition now means "If the character is not A,C,T,G at the same, it is invalid".

Can't figure out why int is duplicating in Java

I am creatings a simple Java program that in the main class asks for a string (input) and then prints out how many vowels (int count) and consonants are in the string. The number of vowels works perfectly however the number of consonants double, so the string "James" has 2 vowels and 6 consonants according to my program.
public class counter {
vowels p1 = new vowels();
public int con = 0;
public int count() {
String input = p1.getInput();
int i = 0;
int count = 0;
while (i < input.length()){
if (input.charAt(i) == 'a' || input.charAt(i) == 'e' || input.charAt(i) == 'i' || input.charAt(i) == 'o' || input.charAt(i) == 'u') {
count++;
} else if (input.charAt(i) != ' ') {
con++;
}
i++;
}
return count;
}
public int con() {
return con;
}
}
You are using an instance member con for counting the consonants, and you don't initialize it at the beginning of the count method, so multiple calls to that method will result in invalid counts.
seems like you are using
int con=0;
is used for consonant count
so instead of using
else if (input.charAt(i) != ' ') {
con++;
}
simply use
else {
con++;
}
Alternate :
subtract the vowel count from string length
'com = P1.length()-count;'
Try to set the variable con to zero at the begining of the method "count".
con = 0;
I hope it works.
char ch;
for(int i = 0; i < str.length(); i ++)
{
ch = str.charAt(i);
if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||
ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
count ++;
else
con;
}
you had nod consider the case when vowels are in caps I solved this in my code
hope my code helps you in this regard thanks.Happy coding

Cannot find symbol, Java and Strings

I've tried tinkering around with this for awhile and have yet to figure out what its giving me this error. The code is far from complete but I'm just trying to figure out why it says it can't find variable ch1. Any help is greatly appreciated!
public class PhoneNumber {
String phoneNumber;
public PhoneNumber(String num) {
phoneNumber = num;
}
public String decodePhoneNumber() {
// Takes string form phone number and decodes based on number pad
// Find code that makes if statement not care about caps
// so if a || b || c number[cnt] = 1 etc..
for (int cnt = 0; cnt < phoneNumber.length(); cnt++) {
char ch1 = phoneNumber.charAt(cnt);
if (Character.ch1.equalsIgnoreCase("a") || ("b") || ("c")) {
} else if (ch1.equalsIgnoreCase("d" || "e" || "f")) {
} else if (ch1.equalsIgnoreCase("j" || "k" || "l")) {
} else if (ch1.equalsIgnoreCase("m" || "n" || "o")) {
} else if (ch1.equalsIgnoreCase("p" || "q" || "r" || "s")) {
} else if (ch1.equalsIgnoreCase("t" || "u" || "v")) {
} else {
}
}
}
}
You have syntax errors and that is why you cannot find ch1.
Try modifying your code as per this syntax. These changes need to be done in all the conditionals.
if ((ch1 == 'a') || (ch1 == 'b') || (ch1 =='c')) {
If you want to make it work regardless of capital letters then you would need to normalize the input to lower case and then do the character comparison:
char ch1 = phoneNumber.toLowerCase().charAt(cnt);
if (ch1 == 'a' || ch1 == 'b' || ch1 == 'c') {
// Do something
}
...

Java - Converting the characters in a string array depending on whether or not it's a vowel

The method takes in any name and tests whether a character is a vowel or consonant. If it's a vowel, it makes the character uppercase, if it's a consonant, it makes the character lowercase. Any thoughts? I don't know how to add .toUpperCase and .toLowerCase in the if else statements.
public static void parsing(String name[])
{
String temp = name[0];
int i = 0;
for(i = 0; i < temp.length(); i++)
{
if(temp.charAt(i) == 'a' || temp.charAt(i) == 'A' ||
temp.charAt(i) == 'e' || temp.charAt(i) == 'E' ||
temp.charAt(i) == 'i' || temp.charAt(i) == 'I' ||
temp.charAt(i) == 'o' || temp.charAt(i) == 'O' ||
temp.charAt(i) == 'u' || temp.charAt(i) == 'U')
{
System.out.print(temp.charAt(i).toUpperCase);
}//Obviously wrong but I don't know what to do.
else
{
System.out.print(temp.charAt(i).toLowerCase);
}//Obviously wrong but I don't know what to do.
}
To convert a single character use the methods from the Character class:
System.out.print(Character.toUpperCase(temp.charAt(i)));
System.out.print(Character.toLowerCase(temp.charAt(i)));
Create two final arrays - one with the vowels, the second one with the consonants. Then check, whether the current char in the loop is a vowel or consonant and make the appropriate changes.
Your are hitting your head as String is immutable. Rebuild the resulting string.
A (bit suboptimal) solution is:
public static void parsing(String[] names)
{
for (int i = 0; i < names.length; ++i) {
names[i] = chAngEd(names[i]);
}
}
private static String chAngEd(String s) {
String result = "";
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
if (ch == 'a' || ...) {
ch = Character.toUpperCase(ch);
} else {
ch = ...
}
result += ch;
}
return result;
}
public static void parsing(String names[]){
for (int i=0; i<names.length; ++i){
names[i] = capitaliseConsts(names[i]);
}
}
private static String capitaliseConsts(String name){
StringBuilder sb = new StringBuilder();
Character c;
for (int i=0; i<name.length(); ++i){
c = name.charAt(i);
if (c.equalsIgnoreCase('a') ||
c.equalsIgnoreCase('e') ||
c.equalsIgnoreCase('i') ||
c.equalsIgnoreCase('o') ||
c.equalsIgnoreCase('u')){
sb.append(Character.toUpperCase(c));
}
else{
sb.append(Character.toLowerCase(c));
}
}
return sb.toString();
}
String vowelsArray = "aeiuo";
String constantsArray = "uppercase constants";
int stringLength = name.length();
String givenNameCopy = name.ToString();
for(int i = 0; i < stringLength; i++){
if(vowelsArray.contains(givenNameCopy[i]))
then uppercase
else if(constantsArray.contains(givenNameCopy[i]))
then lowercase
else
continue;
hope this helps.

Categories

Resources