I have an assignment to do. I need to convert alphabets to telephone numbers. Add hyphen after the 3rd number and after every subsequent 4 numbers. Then I need to allow user to keep on entering input.
I've already gotten 3/4 of my codes done. It's not working. I'm only stuck with the part to keep prompting user for input.
This is my java code so far. Please help me and tell me what's wrong with my code. I'm new to Java, please be nice. Thank you!
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
System.out.println("Enter letters: ");
String phonenumber = input.next();
String phone = phonenumber.replaceAll("\\s", " ");
int count = 0;
int prevCount = 0;
while (!phone.equals("#")){
for (int i = 0; i < phone.length(); i++)
{
char letter = Character.toLowerCase(phone.charAt(i));
if (letter == 'a' || letter == 'b' || letter == 'c')
{
System.out.print(2);
count++;
}
if (letter == 'd' || letter == 'e' || letter == 'f')
{
System.out.print(3);
count++;
}
if (letter == 'g' || letter == 'h' || letter == 'i')
{
System.out.print(4);
count++;
}
if (letter == 'j' || letter == 'k' || letter == 'l')
{
System.out.print(5);
count++;
}
if (letter == 'm' || letter == 'n' || letter == 'o')
{
System.out.print(6);
count++;
}
if (letter == 'p' || letter == 'q' || letter == 'r' || letter == 's')
{
System.out.print(7);
count++;
}
if (letter == 't' || letter == 'u' || letter == 'v')
{
System.out.print(8);
count++;
}
if (letter == 'w' || letter == 'x' || letter == 'y' || letter == 'z')
{
System.out.print(9);
count++;
}
if (count == 3 || count - prevCount == 4)
{
System.out.print('-');
prevCount = count;
}
}
System.out.println();
System.out.println("Enter letters: ");
input.nextLine();
}
}
use a loop:
while (true)
{
System.out.println("Enter letters: ");
String phonenumber = input.next();
if something break;
or
while ((String phonenumber = input.next())!=null)
{
// ...
System.out.println("Enter letters: ");
}
Your problem is here :
System.out.println();
System.out.println("Enter letters: ");
input.nextLine(); // you forgot to assign the String returned by nextLine
// into your phone variable
Beside that, you should reset your counters in each iteration of the while loop.
while (!phone.equals("#")) {
int count = 0;
int prevCount = 0;
... your for loop ...
System.out.println();
System.out.println("Enter letters: ");
phone = input.nextLine();
}
Related
I am writing a code that represents an old-fashioned phone keypad. Everything is working fine except for when I try to take a blank space from the user which is supposed to print out the number 0. I've tried Unicode as well with '\u0020' but that didn't work either. In the output If I type a space and hit enter, I get another line so the scanner is not recognizing the blank space as a char that would be my guess. Someone, please help thanks!
import java.util.Scanner;
public class phoneKeypad{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Please enter a letter: ");
char userInput = input.next().charAt(0);
if (userInput == 'a' || userInput == 'b' || userInput == 'c' ||
userInput == 'A' || userInput == 'B' || userInput == 'C')
{
System.out.println(userInput + " is the number 2!");
}
else if (userInput == 'd' || userInput == 'e' || userInput == 'f' ||
userInput == 'D' || userInput == 'E' || userInput == 'F')
{
System.out.println(userInput + " is the number 3!");
}
else if (userInput == 'g' || userInput == 'h' || userInput == 'i' ||
userInput == 'G' || userInput == 'H' || userInput == 'I')
{
System.out.println(userInput + " is the number 4!");
}
else if (userInput == 'j' || userInput == 'k' || userInput == 'l' ||
userInput == 'J' || userInput == 'K' || userInput == 'L')
{
System.out.println(userInput + " is the number 5!");
}
else if (userInput == 'm' || userInput == 'n' || userInput == 'o' ||
userInput == 'M' || userInput == 'N' || userInput == 'O')
{
System.out.println(userInput + " is the number 6!");
}
else if (userInput == 'p' || userInput == 'q' || userInput == 'r' || userInput == 's' ||
userInput == 'P' || userInput == 'Q' || userInput == 'R' || userInput == 'S')
{
System.out.println(userInput + " is the number 7!");
}
else if (userInput == 't' || userInput == 'u' || userInput == 'v' ||
userInput == 'T' || userInput == 'U' || userInput == 'V')
{
System.out.println(userInput + " is the number 8!");
}
else if (userInput == 'w' || userInput == 'x' || userInput == 'y' || userInput == 'z' ||
userInput == 'W' || userInput == 'X' || userInput == 'Y' || userInput == 'Z')
{
System.out.println(userInput + " is the number 9!");
}
else if (userInput == '\u0020')
{
System.out.println("Blank space is the number 0!");
}
else
{
System.out.println(userInput + " could be either a 1 or the character does not exist");
}
input.close();
}
}
Use:
char userInput = input.nextLine().charAt(0);
instead of:
char userInput = input.next().charAt(0);
Use Scanner.nextLine() instead of next() :
char userInput = input.nextLine().charAt(0);
scanner.nextLine() will capture everything in the line, including whitespace.
scanner.next() will not capture whitespace as the delimiter is whitespace by default.
So, try using scanner.nextLine();
import java.util.Scanner;
public class Ariete25Programs {
public static void main(String[] tin) {
char again = 0;
int choose;
if(choose == 7) {
char again7 = 0;
do
{
System.out.println("---Vowels and Consonants---");
String line;
System.out.println("Enter word: ");
line = sc.nextLine();
String vowels = " ", consonants = " ", digits = " ", spaces = " ";
for(int i = 0; i < line.length(); ++i)
{
char ch = line.charAt(i);
if(ch == 'a' || ch == 'e' || ch == 'i'
|| ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I'
|| ch == 'O' || ch == 'U')
{
vowels+=line.charAt(i);
}
else if((ch >= 'a'&& ch <= 'z'))
{
consonants+=line.charAt(i);
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
System.out.println("Try Again? (Y/N)");
again7 = sc.next().charAt(0);
if(again7 == 'n') {
System.out.println("Menu? [y/n]");
again = sc.next().charAt(0);
}
else if(again7 == 'n') {
System.out.println("Thank you for using the programs!");
System.exit(0);
}
}
while(again7 == 'y');
then the result when you choose 7 becomes like this
-----Vowels and Consonants-----
Enter word:
Try again?(Y/N)
can someone help me? I can't seem to figure out the problem in my codes. It keeps on skipping.
I guess you do something like choose = sc.nextInt(); you should try choose = Integer.parseInt(sc.nextLine());
Please replace sc.next().charAt(0) with sc.nextLine().charAt(0).
Documentation:
Scanner.next()
Scanner.nextLine()
Moreover else if(again7 == 'n') is wrong since you already did the same check few lines before, so you'll never execute the code in that else if block
do
{
System.out.println("---Vowels and Consonants---");
String line;
System.out.println("Enter word: ");
line = sc.nextLine();
String vowels = " ", consonants = " ", digits = " ", spaces = " "; // digits and spaces are not used
int end = line.length();
for (int i = 0; i < end; ++i) {
char ch = line.charAt(i);
if(ch == 'a' || ch == 'e' || ch == 'i'
|| ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I'
|| ch == 'O' || ch == 'U') {
vowels += line.charAt(i);
}
else if ((ch >= 'a'&& ch <= 'z')) {
consonants += line.charAt(i);
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
System.out.println("Try Again? (Y/N)");
again7 = sc.nextLine().charAt(0);
if (again7 == 'n') {
System.out.println("Menu? [y/n]");
again = sc.nextLine().charAt(0);
if (again == 'n') {
System.out.println("Thank you for using the programs!");
break;
} else {
// display Menu
}
}
} while(again7 == 'y');
Essentially I am trying to create a Pig Latin converter. However, for this assignment a requirement is to allow the user to enter 'Q' to quit entering in words. I can get the code to compile, but whenever the user enters Q it crashes and throws:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:658)
at mission4aa.Mission4AA.main(Mission4AA.java:38)
I am just completley unsure where to even go about fixing this. I've been trying.
import java.util.Scanner;
public class Mission4AA {
public static void main(String[] args) {
Scanner scanIn = new Scanner(System.in);
String userInput;
int firstVowel = 0;
System.out.println("Welcome to the pig latin translator!");
System.out.println("Please enter a word (Q to exit): ");
do {
userInput = scanIn.next();
userInput = userInput.trim();
userInput = userInput.toLowerCase();
int end = userInput.length();
char a = userInput.charAt(0);
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' )
System.out.println(userInput + "way");
else { //Check for next vowel if the first letter is consonant
for (int i = 1; i < userInput.length(); i++) {
char b = userInput.toLowerCase().charAt(i);
if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u' ) {
firstVowel = i; //Stores the index of the first vowel
break;
}
}
if(userInput.charAt(1) != firstVowel) {
String startString = userInput.substring(firstVowel, end);
String endString = userInput.substring(0, firstVowel) + "ay";
String result = startString + endString;
System.out.println("Translation: " + result);
}
}
System.out.println("Enter another word(Q to exit): ");
} while (!userInput.equalsIgnoreCase("q"));
System.out.println("Thank you");
}
}
Because when you are doing this check
if(userInput.charAt(1) != firstVowel) {
If the user has input a 'q', userInput will only have a 0 term ( Length 1 ). You are effectively trying to get the second character of the users input. To solve your problem, i would do the check for 'q' at the start of the do section ( or simply scrap the do-while concept and use a while(true) loop ). Note that in future you should handle input that is of length 1. But for your issue, something like this would work
do {
userInput = scanIn.next();
userInput = userInput.trim();
userInput = userInput.toLowerCase();
int end = userInput.length();
char a = userInput.charAt(0);
//here
if(userInput.equals("q") || userInput.equals("Q")){
System.out.println("Thank you");
return;
}
//else continue
If the user enters just Q or q - there's no char at index 1, which is why your code throws the java.lang.StringIndexOutOfBoundsException exception.
There are many ways to fix this. In my case, I just converted your do-while to a while(true) and I use break if the input is just Q or q.
// get first input
userInput = scanIn.next();
while(true){
userInput = userInput.trim();
userInput = userInput.toLowerCase();
int end = userInput.length();
char a = userInput.charAt(0);
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' )
System.out.println(userInput + "way");
else { //Check for next vowel if the first letter is consonant
for (int i = 1; i < userInput.length(); i++) {
char b = userInput.toLowerCase().charAt(i);
if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u' ) {
firstVowel = i; //Stores the index of the first vowel
break;
}
}
if(userInput.charAt(1) != firstVowel) {
String startString = userInput.substring(firstVowel, end);
String endString = userInput.substring(0, firstVowel) + "ay";
String result = startString + endString;
System.out.println("Translation: " + result);
}
}
// check next word here - if Q or q, break out and finish
userInput = scanIn.next();
if(userInput.equalsIgnoreCase("q")) {
break;
}
System.out.println("Enter another word(Q to exit): ");
}
Note - you'd need to rearrange your print statements accordingly.
The problem appears to be that you read the user input in the beginning of the loop, thus the condition in your do-while loop checks the previous user input - not the new one.
In addition the else-branch of your if-statement assumes that the input is at least 2 characters long if(userInput.charAt(1) != firstVowel) {...}.
This is what causes the exception as the input "q" reaches the else-branch, but is only of length 1.
You need to make two changes to your code:
You need to read the userinput before checking the loop-condition.
In the else-branch you must check that the input is at least 2 characters long before checking if the second character is a vowel.
Modified code below:
public static void main(String[] args) {
Scanner scanIn = new Scanner(System.in);
String userInput;
int firstVowel = 0;
System.out.println("Welcome to the pig latin translator!");
System.out.println("Please enter a word (Q to exit): ");
userInput = scanIn.next().trim().toLowerCase();
do {
int end = userInput.length();
char a = userInput.charAt(0);
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' )
System.out.println(userInput + "way");
else { //Check for next vowel if the first letter is consonant
for (int i = 1; i < userInput.length(); i++) {
char b = userInput.toLowerCase().charAt(i);
if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u' ) {
firstVowel = i; //Stores the index of the first vowel
break;
}
}
if(end > 1 && userInput.charAt(1) != firstVowel) {
String startString = userInput.substring(firstVowel, end);
String endString = userInput.substring(0, firstVowel) + "ay";
String result = startString + endString;
System.out.println("Translation: " + result);
} else { /* Handle handle input of length 1 */}
}
System.out.println("Enter another word(Q to exit): ");
userInput = scanIn.next().trim().toLowerCase();
} while (!userInput.equalsIgnoreCase("q"));
System.out.println("Thank you");
}
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');
}
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]++;
}
}
}
}