In my java code the line String st = sc.nextLine(); is not taking input when the code is running and when instead I use sc.next(); the code works properly can you please tell me why sc.nextLine(); is not working
import java.lang.*;
import java.util.*;
/**?Chef wrote some text on a piece of paper and now he wants to know how
many holes are in the text. What is a hole? If you think of the paper as
the plane and a letter as a curve on the plane, then each letter divides
the plane into regions.For example letters "A", "D", "O", "P","R" divide
the plane into two regions so we say these letters each have one hole.
Similarly, letter "B" has 2 holes and letters such as "C", "E", "F","K"
have no holes. We say that the number of holes in the text is equal to
the total number of holes in the letters of the text.
Help Chef to determine how many holes are in the text.
Input
First line contains a single integer T <= 40, the number of test cases.
T test cases follow. The only line of each test case contains a non-empty
text composed only of uppercase letters of English alphabet. The length
of the text is less then 100. There are no any spaces in the input.
Output
For each test case,output a single line containing number of holes in the corresponding txt
Example
Input:
2
CODECHEF
DRINKEATCODE
Output:
2
5
*/
class Holes {
public static void main(String[] args) {
int i, Testcase;
int holes, space = 0, j;
Scanner sc = new Scanner(System.in);
Testcase = sc.nextInt();
for (i = 0; i < Testcase; i++) {
holes = 0;
space = 0;
String st = sc.nextLine();
if (st.length() < 100) {
char[] letter = st.toCharArray();
for (j = 0; j < st.length(); j++) {
if (letter[j] == ' ') {
space++;
}
}
for (j = 0; j < st.length(); j++) {
if (space == 0) {
if (letter[j] == 'A' || letter[j] == 'D'
|| letter[j] == 'O' || letter[j] == 'P'
|| letter[j] == 'R') {
holes = holes + 1;
}
if (letter[j] == 'B') {
holes = holes + 2;
}
}
}
}
if (st == st.toUpperCase() && space == 0) {
System.out.println(holes);
}
}
}
}
As Nighthacks mentioned, Scanner.nextInt will not advance to the next input (Read https://stackoverflow.com/a/13102066/643500)
Try it this way:
public class Holes {
public static void main(String[] args) {
int holes;
Scanner sc = new Scanner(System.in);
int numberOfCases = sc.nextInt(); // Get input as int - not going to
// advance
String[] testCases = new String[numberOfCases];
String line = sc.nextLine(); // Move to next
for (int i = 0; i < numberOfCases; i++) {
line = sc.nextLine();// Read input as line
testCases[i] = line;
}
sc.close();
for (String aCase : testCases) {
holes = 0;
if (aCase.length() < 100 && !aCase.contains(" ")) {
for (int j = 0; j < aCase.length(); j++) {
char letter = aCase.charAt(j);
if (letter == 'A' || letter == 'D' || letter == 'O'
|| letter == 'P' || letter == 'R') {
holes++;
}
if (letter == 'B') {
holes = holes + 2;
}
}
System.out.println(holes);
}
}
}
}
That's because the [Scanner#nextInt] method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine
Workaround:
Either fire a blank Scanner#nextLine call after Scanner#nextInt to consume rest of that line including newline
Check this out.
I'm writing a program in Java where I'm supposed to translate an English sentence to a language similar to pig Latin just with a few different rules.
So far I've written the code, but it only seems to translate one word at a time rather than a whole sentence. can you let me know where I went wrong? Heres my code:
import java.util.Scanner;
public class PartD {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a phrase to convert: ");
String phrase = keyboard.nextLine();
String[] words = phrase.split(" ");
for(int i = 0; i < words.length; i++ ) {
char firstLetter = (words[i].charAt(0));
if (firstLetter == 'a' || firstLetter == 'e' || firstLetter == 'i' || firstLetter == 'o' || firstLetter == 'u'){
String vowel = words[i] +"-eh";
System.out.print(vowel);
}else{
String start = words[i].substring(0,1);
String end = words[i].substring(1,phrase.length());
System.out.print(end + "-" + start + "eh" );
}
}
System.out.println( );
}
}
Im trying to turn a string taken from the user into Pig Latin. I cannot use any special classes, methods, or arrays. I can only use a Scanner to create a object to take the string from the user and .length and .charAt, in addition to any type of looping. (Also cannot use switch statements or the break keyword)
Here is an example of what my output is suppose to be:
Enter a line of text: this is a test.
Input : this is a line of text.
Output: his-tay is-way a-way ine-lay of-way ext-tay.
Here is my code, I can only get my code to work with one word and it must have a space at the end. Only one loop works at a time depending on the loop. Im not sure what to do if I get an entire String.
I know that when the user enters a space that signals a new word, and when they enter a period, that signals the ending.
I had a hard time understanding your code. (It looks like you are trying to do it two ways at once?) Regardless, I believe I was able to understand your question. Here is a compilable and runnable example:
import java.util.Scanner;
public class PigLatin
{
public static void main(String[] args)
{
System.out.print("Enter a line of text: ");
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
System.out.println("\nInput: " + text);
System.out.print("Output: ");
if (text != null && text.length() > 0)
{
int i = 0;
// this iterates through the whole string, stopping at a period or
// the end of the string, whichever is closer
while (i < text.length() && text.charAt(i) != '.')
{
// these three variables only exist in this code block,
// so they will be re-initialized to these values
// each time this while loop is executed
char first = '\0'; // don't worry about this, I just use this value as a default initializer
boolean isFirst = true;
boolean firstIsVowel = false;
// each iteration of this while loop should be a word, since it
// stops iterating when a space is encountered
while (i < text.length()
&& text.charAt(i) != ' '
&& text.charAt(i) != '.')
{
// this is the first letter in this word
if (isFirst)
{
first = text.charAt(i);
// deal with words starting in vowels
if (first == 'a' || first == 'A' || first == 'e' || first == 'E'
|| first == 'i' || first == 'I' || first == 'o' || first == 'O'
|| first == 'u' || first == 'U')
{
System.out.print(first);
firstIsVowel = true;
}
// make sure we don't read another character as the first
// character in this word
isFirst = false;
}
else
{
System.out.print(text.charAt(i));
}
i++;
}
if (firstIsVowel)
{
System.out.print("-tay ");
}
else if (first != '\0')
{
System.out.print("-" + first + "ay ");
}
i++;
}
System.out.print('\n'); //for clean otuput
}
}
}
There are a few comments in there that might help guide you through my logic. This is almost definitely not the most efficient way to do this (even with your limitations), as I only whipped it up as a example of the type of logic you could use.
You could break it up into words, then process the current word when you hit a space or period:
System.out.print("Enter a line of text: ");
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
System.out.println("\nInput: " + text);
System.out.print("Output: ");
String curWord = "";
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ' ' || text.charAt(i) == '.') {
if (curWord.charAt(0) == 'a' || curWord.charAt(0) == 'e' ||
curWord.charAt(0) == 'i' || curWord.charAt(0) == 'o' ||
curWord.charAt(0) == 'u') {
System.out.print(curWord + "-way ");
} else {
for (int j = 1; j < curWord.length(); j++) {
System.out.print(curWord.charAt(j);
}
System.out.print("-" + curWord.charAt(0) + "ay ");
//System.out.print(curWord.substring(1)+"-"+curWord.charAt(0)+"ay ");
}
curWord = "";
} else {
curWord += text.charAt(i);
}
}
At the end of my loop, I am planning on displaying the number of consonants and vowels in the sentence. I was wondering if there was a more efficient way to check how many consonants and vowels are in a given sentence, rather than using an if statement and manually inputting every letter. (key refers to my Scanner which has already been initialized)
Edit: It needs to ignore digits and other special characters, so for example if I write Hello# how 1are you?. There should be 8 vowels and 6 consonants.
System.out.println("Please enter the sentence to analyze: ");
String words = key.nextLine(); //the sentence the user inputs
int c = 0; //# of consonants
int v = 0; //# of vowels
int length = words.length(); //length of sentence
int check; //goes over each letter in our sentence
for(check = 0; check < length; check++){
char a = words.charAt(check);
if(a == 'a' || a == 'A' || a == 'e' || a == 'E' || a == 'i' || a == 'I' || a == 'o'
|| a == 'O' || a == 'u' || a == 'U' || a == 'y' || a == 'Y')
v = v + 1;
else if(a == 'b' || a == 'B' || a == 'c' || a == 'C' || a == 'd' || a == 'D' || a == 'f'
|| a == 'F' || a == 'g' || a == 'G' || a == 'h' || a == 'H' || a == 'j' || a == 'J'
|| a == 'k' || a == 'K' || a == 'l' || a == 'L' || a == 'm' || a == 'M' || a == 'n'
|| a == 'N' || a == 'p' || a == 'P' || a == 'q' || a == 'Q' || a == 'r' || a == 'r'
|| a == 's' || a == 'S' || a == 't' || a == 'T' || a == 'v' || a == 'V' || a == 'w'
|| a == 'W' || a == 'x' || a == 'X' || a == 'z' || a == 'Z')
c = c + 1;
}
Use Character.isLetter(ch) to determine if the character is a vowel or a consonant, then check to see if the character in question is in the set of vowels.
One way to create the set of vowels:
Set<Character> vowels = new HashSet<Character>();
for (char ch : "aeiou".toCharArray()) {
vowels.add(ch);
}
And to increment v or c:
if (Character.isLetter(a)) {
if (vowels.contains(Character.toLowerCase(a))) {
v++;
} else {
c++;
}
}
Assuming you already have a letter (vowel or consonant, not a digit nor a symbol or anything else), then you can easily create a method to define if the letter is a vowel:
static final char[] vowels = { 'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U', 'y', 'Y' };
public static boolean isVowel(char c) {
for (char vowel : vowels) {
if (c == vowel) {
return true;
}
}
return false;
}
public static boolean isConsonant(char c) {
return !isVowel(c);
}
Note that I set Y and y as vowels since seems that they are in your language. In Spanish and English, Y is a consonant (AFAIK).
You can easily check if the char is a letter or not using Character#isLetter.
So, your code would become into:
for(check = 0; check < length; check++){
char a = words.charAt(check);
if (Character.isLetter(a)) {
if (isVowel(a)) {
v++;
} else {
c++;
}
}
}
How about something like
String vowels = "aeiouyAEIOUY"; // you can declare it somewhere before loop to
// to avoid redeclaring it each time in loop
//inside loop
if ((a>='a' && a<='z') || (a>='A' && a<='Z')){ //is letter
if (vowels.indexOf(a)!=-1) //is vowel
v++;
else //is consonant
c++;
}
I am sure this can be improved upon, but I'll throw it in the ring anyways.
Remove non-characters from the sentence, lowercase it, then convert to a char array and compare it to a char array of vowels that are all lowercase.
String myText = "This is a sentence.";
int v = 0;
char[] vowels = {'a','e','i','o','u'};
char[] sentence = myText.replaceAll("[^a-zA-Z]","").toLowerCase().toCharArray();
for (char letter : sentence) {
for (char vowel : vowels) {
if (letter == vowel) {
v++;
}
}
}
System.out.println("Vowels:"+ v);
System.out.println("Consonants:" + (sentence.length -v));
One easy way would be to create 2 lists:
one contains vowels (a, e, i, o, u)
the other contains consonants
Then you iterate over each character in the Java string.
See a sample below:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Counter {
public static void main(String[] args) {
String test = "the fox is in the woods";
test = test.toLowerCase();
List<Character> vowels = new ArrayList<Character>();
vowels.addAll(Arrays.asList(new Character[]{'a', 'e', 'i', 'o', 'u'}));
List<Character> consonants = new ArrayList<Character>();
consonants.addAll(Arrays.asList(new Character[]{'b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'}));
int vcount = 0;
int ccount = 0;
for (int i = 0; i < test.length(); i++){
Character letter = test.charAt(i);
if (vowels.contains(letter)){
vcount ++;
} else if (consonants.contains(letter)){
ccount++;
}
}
System.out.println(vcount);
System.out.println(ccount);
}
}
You can do a range check to make sure it is a letter, then check if it one of the vowels:
if( ( a >= 'a' && a<= 'z' ) || ( a >= 'A' && a <= 'Z' ) )
{
// is letter
switch( a )
{
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'U': case 'u':
++v;
break;
default: // don't list the rest of the characters since we did the check in the if statement above.
++c;
}
}
Oh, there's certainly a much more readable way to do it. Not sure if that meets the "better" definition.
As a start, I'd suggest that you encapsulate what you have into methods that you can write once and call anywhere:
package misc;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ParseUtils get counts of vowels and consonants in sentence
* #author Michael
* #link https://stackoverflow.com/questions/24048907/how-can-i-check-how-many-consonants-and-vowels-there-are-in-a-sentence-in-java
* #since 6/4/2014 6:57 PM
*/
public class ParseUtils {
private static final String VOWEL_PATTERN_STR = "(?i)[aeiou]";
private static final Pattern VOWEL_PATTERN = Pattern.compile(VOWEL_PATTERN_STR);
private static final String CONSONANT_PATTERN_STR = "(?i)[b-df-hj-np-tv-z]";
private static final Pattern CONSONANT_PATTERN = Pattern.compile(CONSONANT_PATTERN_STR);
private ParseUtils() {}
public static void main(String[] args) {
for (String arg : args) {
System.out.println(String.format("sentence: '%s' # letters: %d # vowels: %d # consonants %d", arg, arg.length(), getNumVowels(arg), getNumConsonants(arg)));
}
}
public static int getNumVowels(String sentence) {
return getMatchCount(sentence, VOWEL_PATTERN);
}
public static int getNumConsonants(String sentence) {
return getMatchCount(sentence, CONSONANT_PATTERN);
}
private static int getMatchCount(String s, Pattern p) {
int numMatches = 0;
if ((p != null) && (s != null) && (s.trim().length() > 0)) {
Matcher m = p.matcher(s);
while (m.find()) {
++numMatches;
}
}
return numMatches;
}
}
Split the String by whitespaces and and Calculate only the number of Vowels. Then Number of consonants = Length of Sentence - No. of Vowels.
Detailed Code:
System.out.println("Please enter the sentence to analyze: ");
int v = 0;
int c = 0;
String string = key.nextLine(); //the sentence the user inputs
String[] stringArray = string.split(" ");
for(int i=0;i<stringArray.length;i++)
{
for(int j= 0; j<string.length(); j++)
{
char a = string.charAt(j);
if(a == 'a' || a == 'A' || a == 'e' || a == 'E' || a == 'i' || a == 'I' || a == 'o'
|| a == 'O' || a == 'u' || a == 'U' || a == 'y' || a == 'Y')
v = v + 1;
}
c= c+(stringArray.length)-v;
}
System.out.println("Vowels:"+v+" and Consonants:"+c);
One way to do it is to get rid of the non-letters, then vowels and consonants, and get the length of what is left:
public class CountChars {
public static final String CONSONANTS = "[BCDFGHJKLMNPQRSTVWXYZ]";
public static final String VOWELS = "[AEIOU]"; // considering Y a consonant here
public static final String NOT_LETTERS = "[\\W_0-9]";
public static void main(String[] args) {
String words = "How can I check how many consonants and vowels there are in a sentence in Java?";
String letters = words.toUpperCase().replaceAll(NOT_LETTERS, "");
System.out.println("Letters: " + letters.length());
String vowels = letters.replaceAll(CONSONANTS, "");
System.out.println("Vowels: " + vowels.length());
String consonants = letters.replaceAll(VOWELS, "");
System.out.println("Consonants: " + consonants.length());
}
}
Here is the best way of doing this:
public static void checkVowelsAndConsonants(String s){
System.out.println("Vowel Count: " + (s.length() - s.toLowerCase().replaceAll("a|e|i|o|u|", "").length()));
//Also eliminating spaces, if any for the consonant count
System.out.println("Consonant Count: " + (s.toLowerCase().replaceAll("a|e|i|o| |u", "").length()));
}
I need to write a program that takes a string, and prints out the string text with all the vowels removed, except when a word starts with it.
The code I've written is halfway there, but I cannot figure out why it will not return the whole string and it does not remove all the vowels. Say I input the phrase "Desirable property area". The program prints the string, "Dirlp" instead of "Dsrbl prprty ar "
Can anybody advise on how I can improve the code to make this work? Thank you!
Here is my code:
public static void main (String [] args)
{
Scanner in = new Scanner (System.in);
System.out.print ("Enter some text, then hit enter: ");
String text = in.nextLine();
takeOutVowel (text);
System.out.println ();
}
static void takeOutVowel (String s)
{
char ch = s.charAt(0); //character to be printed
System.out.print (ch);
int nextCh = 1; //determines the position of the next character
int increase = 1; //increase is how much i will increase by in the for loop; takes the position of vowels into //consideration so they can be skipped
for (int i = 1; i <= s.length(); i += increase)
{
ch = s.charAt (nextCh);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
nextCh++;
ch = s.charAt (nextCh);
while (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
{
nextCh++;
ch = s.charAt (nextCh);
if (nextCh >= s.length())
{
ch = ' ';
break;
}
}
}
System.out.print (ch);
nextCh++;
ch = s.charAt (nextCh);
if (ch == ' ') //if the previous position was a space, then this will allow for the vowel to be printed
{
System.out.print ("" + ch + s.charAt(nextCh + 1));
nextCh++;
}
increase = nextCh;
}
Thanks for all the answers so far - very helpful! I'm not allowed to use arrays or anything not covered yet, so I've amended the code to what it is below. It compiles fine but when I run the program and enter the Scanner text, I get a message that says
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 27
at java.lang.String.charAt(String.java:686)
at Vowels.noVowels(Vowels.java:20)
at Vowels.main(Vowels.java:11)
I can't figure what the problem is now. Thank you again for all the help!
import java.util.*;
class Vowels
{
public static void main (String [] args)
{
Scanner in = new Scanner (System.in);
System.out.print ("Enter some text, then hit enter: ");
String text = in.nextLine();
System.out.println (noVowels(text));
}
static String noVowels (String s)
{
String noVowels = "" + s.charAt(0); //Starts a new string with the first character of the input text
for (int i = 1; i <= s.length(); i++)
{
if (isVowel(s.charAt(i)) && s.charAt(i-1) != ' ') //if the character is a vowel and it's previous character wasn't a space, then this is a vowel to be replaced
{
noVowels = noVowels.concat("");
}
else
{
noVowels = noVowels.concat("" + s.charAt(i));
}
}
return noVowels;
}
static boolean isVowel (char ch)
{
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
return true;
}
else
{
return false;
}
}
}
You can solve this problem easily. Iterate over String and check the vowel. If no vowel than append the result. Try
static void takeOutVowel(String s) {
StringBuilder res = new StringBuilder();
String[] words = s.split(" +");
for (String word : words) {
res.append(word.charAt(0)); //Skip the first char
for (int i = 1; i < word.length(); i++) {
char ch = word.charAt(i);
if (!isVowel(ch)) { // Check the vowel
res.append(ch);
}
}
res.append(' ');
}
System.out.println(res);
}
static boolean isVowel(char ch){
ch=Character.toLowerCase(ch); // Make it case-insensitive.
return ch=='a' ||ch=='e' ||ch=='i' ||ch=='o' ||ch=='u';
}
You can do this easily with a regular expression as well. The first example demonstrates how to simply remove vowels.
public static void main(String[] args)
{
String noVowels = takeOutVowel("Hello how are you?");
System.out.println(noVowels); // prints "Hll hw r y?"
}
// This will remove all vowels from any String
private static String takeOutVowel(String s)
{
return s.replaceAll("[aeiou]", "");
}
But now to satisfy your requirement of ignoring the first letter of a word if it is a vowel (which means we will ignore it no matter what), you just need to edit the takeOutVowel method a bit.
static String takeOutVowel (String s)
{
// split your string so we can examine each word separately
String[] words = s.split(" ");
String noVowels = "";
for (int i = 0; i < words.length; i++){
char firstChar = words[i].charAt(0);
String temp = words[i].substring(1, words[i].length()).replaceAll("[aeiou]", "");
noVowels += firstChar + temp + " ";
}
return noVowels;
}
This works for your following requirement - Remove all vowels except for when the word starts with a vowel.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter some text, then hit enter: ");
String text = in.nextLine();
takeOutVowel(text);
System.out.println();
}
static void takeOutVowel(String s) {
String[] array = s.split(" "); // Split sentence into words and store them in an array.
StringBuilder finalString = new StringBuilder();
for (String word : array) { //For each word in the array
char ch = word.toLowerCase().charAt(0); //check if the lower case first character is a vowel.
if(ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u'){ // When it is not, replace all the vowels.
finalString = finalString.append(word.replaceAll("[aeiou]", "")).append(" ");
}else{
finalString = finalString.append(ch).append(word.replaceAll("[aeiou]", "")).append(" ");// When it is , replace all the vowels except the first character.
}
}
System.out.println(finalString);
}
}