mapping a string to its equivalent digits in java [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I am trying to create a program in java which asks the user to enter a string, the number equivalent of the string is then given as the output. eg ABC(2), DEF(3), GHI(4), JKL(5), MNO(6), PQRS(7), TUV(8), WXYZ(9). my code is below. The problem is once the user inputs their string to be converted I get no output(and no errors). I was wondering if someone could have a look and give me some advice. what i am trying to do is turn the string that the user has entered into an array and then use a for loop with nested if statements to go through the array and whatever letter there is in [i] give the equavilent number. but the system.out isnt working?
import java.util.Scanner;
public class keyPad {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter a string:");
Scanner userInput = new Scanner(System.in);
String convertString = userInput.next();
int length = convertString.length();
String[] stringArray = new String[length];
for(int i=0; i<length; i++){
if(stringArray[i] == "a" || stringArray[i] == "b" || stringArray[i] == "c"){
System.out.println("1");
}
if(stringArray[i] == "d" || stringArray[i] == "e" || stringArray[i] == "f"){
System.out.print("2");
}
if(stringArray[i] == "g" || stringArray[i] == "h" || stringArray[i] == "i"){
System.out.print("3");
}
if(stringArray[i] == "j" || stringArray[i] == "k" || stringArray[i] == "l"){
System.out.print("4");
}
if(stringArray[i] == "m" || stringArray[i] == "n" || stringArray[i] == "o"){
System.out.print("5");
}
if(stringArray[i] == "p" || stringArray[i] == "q" || stringArray[i] == "r" || stringArray[i] == "s"){
System.out.print("6");
}
if(stringArray[i] == "t" || stringArray[i] == "u" || stringArray[i] == "v"){
System.out.print("7");
}
if(stringArray[i] == "w" || stringArray[i] == "x" || stringArray[i] == "y" || stringArray[i] == "z"){
System.out.print("8");
}
}
}
}

In your program you take the input from the user but you havent put it in the array you are comparing .The string array is empty.So you are not getting an output.

Instead of using == in your if statements, use string1.equals(string2);
Look at this stackOverflow answer for more: How do I compare strings in Java?
You also need to add the input string into the array which you are checking.

Related

Rules not obeyed by if statement

The below code is supposed to tell the user whether his input is a vowel or consonant or digit less than 1. The program however returns "Vowel" for all capital letters including consonants and whenever a digit is entered "Consonant" is returned. Ex - if a is entered, result = vowel. If b, result = Consonant. If B, result = Vowel (should be Consonant). If 1, result = Consonant(should be Digit) . Any advice would be greatly appreciated. Thanks.
package checkVowelorConstantorNumber;
import java.util.Scanner;
public class Main {
public static void main (String [] args) {
Scanner inp = new Scanner (System.in);
boolean tf = false;
while(tf == false) {
System.out.println("Enter a character which is a - z or A - Z or
less than 1");
char cha = inp.next().charAt(0);
inp.nextLine();
if(Character.isLetter(cha) && cha == 'a'||cha == 'e' || cha == 'i' || cha == 'o' || cha == 'u' || Character.isUpperCase(cha)) {
System.out.println("Vowel");
}
else if(Character.isLetter(cha) && cha != 'a'|| cha != 'e' || cha != 'i' || cha != 'o' || cha != 'u' || Character.isUpperCase(cha)) {
System.out.println("Consonant");
}
else if(Character.isDigit(cha) && cha <= 1 ) {
System.out.println("Digit");
}
else System.out.println("Invalid character");
}
}
}
Your if statement first checks if the given character is a letter and not an a, 1 is neither so that is false, then it checks if 1 is not equal to 'e' causing that statement to be true, thus printing 'Consonant'. You have to make the check for isLetter for every comparison. Therefore i would recommend something like this:
if(Character.isLetter(cha)) {
// Check for vowel or consonant based on letters
} else if(Character.isDigit(cha) && cha <= '1') {
System.out.println("Digit");
} else {
System.out.println("Invalid character");
}
You also should make the if statement for consonant use && instead of ||, since it should be none of the specified chars.
Pay close attention to logical ands (&&), logical ors (||) and parentheses. Consider the following, modified from your code with some comments.
char cha = inp.next().charAt(0);
inp.nextLine();
if (cha.isLetter()) {
// convert to uppercase to simplify the if
char uc = cha.toUpperCase();
if (uc == 'A' || uc == 'E' || uc == 'I' || uc == 'O' || uc == 'U') {
// it's a vowel
} else {
// it's a letter that isn't a vowel (consonant)
}
} else {
// it's not a letter
if (cha.isDigit() && cha < '1') {
// but it is a digit less than 1
} else {
// it's something else (digit not less than '1' or not a digit)
}
}

Java, The loop doesn't start over from the beginning of the program [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I am just finishing my program, but I still have one problem left that I can't seem to find an answer too. I have been looking through already asked questions but I couldn't find something that specifically answers my question in this case. This is a program that lets the user input a string and then it counts how many vowels and consonants etc. And after this the user gets an option to repeat the program and input a new string if he/she press y, the program quits if he/she press n etc. The only thing that is not working is if the user presses y to repeat the program, it then prints out that there are 0 vowels and consonants etc. I know that it is something in the beginning of my code where I have int consonant_count=0 for example, I just can't figure out what to move and where to move it. Ps. this shouldn't be flagged as a duplicate since I didn't know that nextLine was the problem. Here is the code:
import java.util.Scanner;
public class loop2
{
public static void main (String[] args)
{
Scanner inputReader = new Scanner (System.in);
char result='y';
do {
// ’Nytto’-kod:
int vowels_count = 0;
int consonents_count = 0;
int charachters_count= 0;
System.out.println("Skriv in en text");
String str = inputReader.nextLine();
String str2 = str.toLowerCase();
char[] chr = str2.toCharArray();
for(int i=0;i<chr.length;i++)
{
if(chr[i] == 'a' || chr[i]== 'e' || chr[i] == 'i' || chr[i] == 'o' || chr[i] == 'u')
vowels_count++;
else if(chr[i] == '-' || chr[i] == '!' || chr[i] == '?' || chr[i] == ',' || chr[i] == '.' || chr[i] == ':' || chr[i] == ';')
charachters_count++;
else
consonents_count++;
}
System.out.println("Antalet vokaler:"+vowels_count+ " "+"Antalet konsonanter:"+consonents_count+" "+"Antalet interpunktionstecken:"+charachters_count++);
// Kod f ̈or hantering av repetition
System.out.println ("För att upprepa: Skriv y");
System.out.println ("För att avsluta: Skriv n");
String repeat=inputReader.next();// H ̈amta anv ̈andarens svar.
result=repeat.charAt(0);
if(result=='y')
{
continue;
}
else if(result !='y' && result !='n')
{
System.out.println("Du får bara skriva y eller n, försök igen!");
result='y';
}
else
{
System.out.println ("Klart.");
inputReader.close ();
}
}
while (result == 'y'); // Observera semikolon!
}
}
You should use the nextLine() when reading input from the user, this grabs everything including the end of line character '\n' which is what gets left over after your next() call and then nextLine() grabs the '\n' which gives you the counts of 0, 0 for vowels and consonents
Scanner inputReader = new Scanner (System.in);
char result='y';
while(result == 'y')
{
// ’Nytto’-kod:
int vowels_count = 0;
int consonents_count = 0;
int charachters_count= 0;
System.out.println("Skriv in en text");
String str = inputReader.nextLine();
String str2 = str.toLowerCase();
char[] chr = str2.toCharArray();
for(int i=0;i<chr.length;i++)
{
if(chr[i] == 'a' || chr[i]== 'e' || chr[i] == 'i' || chr[i] == 'o' || chr[i] == 'u')
vowels_count++;
else if(chr[i] == '-' || chr[i] == '!' || chr[i] == '?' || chr[i] == ',' || chr[i] == '.' || chr[i] == ':' || chr[i] == ';')
charachters_count++;
else
consonents_count++;
}
System.out.println("Antalet vokaler:"+vowels_count+ " "+"Antalet konsonanter:"+consonents_count+" "+"Antalet interpunktionstecken:"+charachters_count++);
//wrap your play again logic in another do/while where you
// ask for y or n until they enter either one
do {
System.out.println ("För att upprepa: Skriv y");
System.out.println ("För att avsluta: Skriv n");
String repeat=inputReader.nextLine();//read the entire next line <----
result=repeat.charAt(0);
if(result=='y')
{
continue;
}
else if(result !='y' && result !='n')
{
System.out.println("Du får bara skriva y eller n, försök igen!");
}
else
{
System.out.println ("Klart.");
inputReader.close ();
}
} while (result !='y' && result !='n');
}

SyllableCounter counts the Syllables in a word

I am trying to work on a syllable counter that counts the syllables in the string I enter. Here are the instructions. -
Syllables are really useful for a lot of things. They are defined according to the following rules involving
consonants (non-vowels) and vowels (a, e, i, o, u, y):
Starting y omitted:
(a) when words begin with y, we don’t count the starting y as a vowel. (we are
assuming there are no words that start with y followed immediately by a consonant)
Silent e omitted:
(a) when e is the last letter of a word, we’ll assume it is silent, unless the word is café or
entrée (words borrowed from French). (* we’ll ignore all other words to simplify)
For simplification, it may be best to create a new String without this silent e, before
checking for more syllables.
With the silent-e omitted, one-syllable units:
(a) have a single vowel.
(b) have two vowels that are the same letter in succession.
(c) have two vowels in immediate succession that are ei, ie, ea, ou, ey, ay, oy, uy, ai.
(d) have three vowels in immediate succession that are eau, iou (* yes, there are
exceptions to this that we are ignoring here).
With the silent-e omitted, two-syllable units:
(a) two vowels in immediate succession where the vowels are different letters not
following the rule above. For instance, oe, io, oi.
(b) three vowels in immediate succession not following the rule above where the last
vowel is not a silent e. For instance (“eye”) as in “meyer.”
Generate a program called SyllableCounter that counts syllables in a word or sentence (maximum one
line). Assume the user will not use any punctuation. Pseudocode and a testing plan are required.
Do not print in main().
Sample output:
Please enter your word or sentence, followed by a carriage return.
Sally where are you going
Your entry has 7 syllables.
Here is my current code (It compiles, but has a StringIndexOutOfBoundsException -
/*
* SyllableCounter.java
* Prints the number of syllables based on an inputed string
*
* Testing - What should work - All strings with letter characters
* What shouldn't work - Number values
*/
import java.util.Scanner; //import the scanner
public class SyllableCounter //class is SyllableCounter
{
public static void main (String args[]) //main() method header
{
String string = "";
string = getInput(); //call getInput()
int totalCount = calc(string); //call calc()
printOut(totalCount); //call printOut()
}
public static String getInput() //getInput() method
{
Scanner console = new Scanner (System.in); //create an instance of the scanner
System.out.println("Please enter your word or sentence, followed by a carrige return");
String input = console.nextLine(); //get the inputted string and return it
return input;
}
public static int calc (String string)
{
//int finalCount = 0;
//int index = string.indexOf(' ');
return calcWord(string);
}
public static int calcWord(String word) //calc() method
{
int count = 0;
//for loop goes through all charectors
int length = word.length();
for (int i = 0; i<length; i++)
{
if ((word == "entree") || (word == "cafe"))
return 2;
else if (i==0)//if i is 0
{
if (word.charAt(i) == 'a' //if letter is a,e,i,o or u
|| word.charAt(i) == 'e'
|| word.charAt(i) == 'i'
|| word.charAt(i) == 'o'
|| word.charAt(i) == 'u')
count++ ; //count ++
else //else
{} //nothing
}
else if (i==word.length()-1) //else if i is the last letter of the string
{
if ( (word.charAt(i) == 'a') || (word.charAt(i) == 'i') || (word.charAt(i) == 'o') || (word.charAt(i) == 'u') || (word.charAt(i) == 'y') )
//else if letter is a,i,o,u or y (also 2 or 3 in a row)
{
count ++ ;//count ++
}
else //else
{} //nothing
}
else if (word.charAt(word.length()-1) == 'e') {
if (length >= i+2)
if ( word.substring(i,i+3) == "eau"
|| word.substring(i,i+3) == "iou" )
{
count++;
i+=2;
}
else if ( word.substring(i,i+2) == "ei"
|| word.substring(i,i+2) == "ie"
|| word.substring(i,i+2) == "ea"
|| word.substring(i,i+2) == "ou"
|| word.substring(i,i+2) == "ey"
|| word.substring(i,i+2) == "ay"
|| word.substring(i,i+2) == "oy"
|| word.substring(i,i+2) == "uy"
|| word.substring(i,i+2) == "ai" )
{
count++;
i++;
}
else if( word.substring(i, i+2) == "oe"
|| word.substring(i, i+2) == "io"
|| word.substring(i, i+2) == "oi" )
{
count+=2;
i++;
}
}
else {
if (word.charAt(i) =='a'
|| word.charAt(i) == 'e'
|| word.charAt(i) == 'i'
|| word.charAt(i) == 'o'
|| word.charAt(i) == 'u' )
{
count++;
}
}
if (!(word.charAt(word.length()-1) == 'e'))
{
if ( word.substring(i,i+3) == "eau")
{
count++;
i+=2;
}
else if (word.charAt(i) == 'a'
|| word.charAt(i) == 'e'
|| word.charAt(i) == 'i'
|| word.charAt(i) == 'o'
|| word.charAt(i) == 'u' )
{
count++;
}
}
else if (word.charAt(i) == 'a'
|| word.charAt(i) == 'e'
|| word.charAt(i) == 'i'
|| word.charAt(i) == 'o'
|| word.charAt(i) == 'u' )
{
count++;
}
else //else
{} //nothing
}
return count;//return the count
}
public static void printOut(int count) //printOut() method
{
System.out.println(count);
// print the count
}
}
I used the word "foo" as input to your program:
Here (around line 112 for me) :
if (!(word.charAt(word.length()-1) == 'e')){
if ( word.substring(i,i+3) == "eau")
An example of how the above section of code fails is using the word foo:
The char at word length-1 is not e so therefore this condition above will be evaluated. However, when i is equal to 1 i+3 will equal 4. So, 4 is outside the length of "foo" causing the error.
Keep in mind this is just one example of this type of failure. Make sure that whenever you are getting a substring from i to i+n the string being evaluated has i+n chars left.
Manually finding the solution is a lot of work. Regular Expression could be a sweet solution to your problem. Have a look at the link below:
How to calculate syllables in text with regex and Java
Also be reminded that the above reference doesnot consider Y as a syllable, you will have to tweak the regular expression a bit to get the desired output. Plus the vowel "e" needs some checking to be done to get the exact results.

Taking vowels from string. Java

I'm having trouble with this simple exercise. What I have to do is to take the vowels from the string.
This returns all the vowels in the string, but what I want is that if there are multiple letters of same vowel, just return one.For example, using the string "aaa eee iii" should give "a e i".
public static void getVowels(char aChar, String aString){
System.out.print("Your string has the following vowels: ");
for (int i = 0; i < aString.length(); i++){
if ((aString.charAt(i) == 'a') || (aString.charAt(i) == 'e') || (aString.charAt(i) == 'i') || (aString.charAt(i) == 'o') || (aString.charAt(i) == 'u')) {
aChar = aString.charAt(i);
System.out.print(aChar + " ");
}
}
}
I would recommend either adding each vowel found to a HashSet<Character>, or calling aString.contains() with each vowel in turn. You can also use aString.toLowerCase() so that you only have to check for lowercase vowels.
Edit your code as follows:
public static void getVowels(char aChar, String aString)
{
System.out.print("Your string has the following vowels: ");
String vowels="";
for (int i = 0; i < aString.length(); i++)
{
if ((aString.charAt(i) == 'a') || (aString.charAt(i) == 'e') || (aString.charAt(i) == 'i') || (aString.charAt(i) == 'o') || (aString.charAt(i) == 'u'))
{
if(!vowels.contains(String.valueOf(aString.charAt(i))))
vowels+=aString.charAt(i);
}
}
for(int i=0;i<vowels.length();i++)
System.out.print(vowels.charAt(i)+" ");
}
EDIT :
Alternatively,
public static void getVowels(char aChar, String aString){
System.out.print("Your string has the following vowels: ");
char vowels[]={'a','e','e','o','u'};
for (char vowel : vowels)
{
if(aString.indexOf(vowel)>=0)
{
System.out.print(vowel+" ");
}
}
}
Why are you doing for loop? Just check String.IndexOf() and if that character is present print it.
You need to have a string where you keep on adding unique vowels checking before hand whether it exists. The below program will clear your doubt.
public class TestWovel {
public static void main(String[] args) {
String vowel = "aaaeeeiiizncnzcxjswdmmnmxcuuooo";
String uniqueVowels = "";
for(int i=0;i<vowel.length();i++){
char vowelFound = vowel.charAt(i);
if((vowelFound == 'a' || vowelFound == 'e' || vowelFound == 'i' || vowelFound == 'o' || vowelFound == 'u') && (uniqueVowels.indexOf(vowelFound) == -1)){
uniqueVowels+=vowelFound;
}
}
System.out.println(uniqueVowels);
}
}
You could use an integer array whose indexes are ASCII codes. When you see a vowel, check its count in the array. If the count is 0, print the vowel and increase the count. For example, 'a' would be stored in arr[97]:
public static void getVowels(String aString) {
int[] arr = new int[128];
char c;
System.out.print("Your string has the following vowels: ");
for (int i = 0; i < aString.length(); i++){
c = aString.charAt(i);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
if (arr[c] == 0) {
System.out.print(aString.charAt(i) + " ");
arr[c]++;
}
}
}
}

l33t why is it printing three U's

i am having a problem i am making a l33t translator and my translator from English to l33t works for my l33t to English works other then u and what is happening is it is printing three U's i have tryed taking it out of the for loop and it will only print one but it prints it at the start of the word i have tryed putting it at the bottom out of the for and it doesnt even print one. i have also tryed if(phrase.charAt(i) == '|') && phrase.charAt(i+1) == '_' && phrase.charAt(i+2) == '|'). here is what i got.
public static String translateToEnglish(String phrase) {
Scanner scan = new Scanner(System.in);
System.out.println("Hello what pharse would you like to convert in to l33t");
phrase = scan.nextLine();
String NewString = "";
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == '4') {
NewString += "a";
}
if (phrase.charAt(i) == '8') {
NewString += "b";
} else {
if (phrase.charAt(i) == '3') {
NewString += "e";
}
}
if (phrase.charAt(i) == '1') {
NewString += "l";
} else {
if (phrase.charAt(i) == '0') {
NewString += "o";
}
}
if (phrase.charAt(i) == '5') {
NewString += "s";
} else {
if (phrase.charAt(i) == '7') {
NewString += "t";
}
}
if (phrase.contains("|_|")) {
NewString += "u";
}
if (phrase.charAt(i) == '2') {
NewString += "z";
}
if (phrase.charAt(i) == 'c' || phrase.charAt(i) == 'd' || phrase.charAt(i) == 'f' || phrase.charAt(i) == 'g'
|| phrase.charAt(i) == 'h' || phrase.charAt(i) == 'i'
|| phrase.charAt(i) == 'j' || phrase.charAt(i) == 'k' || phrase.charAt(i) == 'm' || phrase.charAt(i) == 'n'
|| phrase.charAt(i) == 'p' || phrase.charAt(i) == 'q'
|| phrase.charAt(i) == 'r' || phrase.charAt(i) == 'v' || phrase.charAt(i) == 'w' || phrase.charAt(i) == 'x'
|| phrase.charAt(i) == 'y') {
NewString += phrase.charAt(i);
}
// if (phrase.charAt(i) == 'c') {
}
System.out.println(NewString);
return phrase;
}
For every char in the word you check if it contains a "u". It will always be true because you don't check at a specific position of the word. You would have to check for a | followed by _ followed by | and then add a "u" instead of generally checking if it's somewhere in the input.
Your if statement for |_| is doing a String#contains comparison and is not elsed. So for every iteration in the loop it will print a u if the phrase contains this sequence of characters.
If you use your alternative of checking each char at i, i+1, i+2 you will firstly have to make sure that your phrase is long enough and then if it is true, in that if statement you will have to make sure you increment i by 3 i.e
if(phrase.length() < i+2
&& phrase.charAt(i) == '|')
&& phrase.charAt(i+1) == '_'
&& phrase.charAt(i+2) == '|')
{
NewString += "u";
i += 2; // Will get the third increment from loop
continue;
}
Also if you make sure the structure is always if..if else...else, the final check where is just replaces with the same character can just be reduced to an else without needing to or together every other character

Categories