java not getting output piglatin - java

The following is my code for converting all the words of the sentence into PigLatin, ie "Her food is stolen" to "ERHAY OODFAY ISAY OLENSTAY", but the output which I am getting is ERHAY. Any corrections would be appreciated. Thanks.
public class piglatin
{
public void main(String s)
{
s=s.toUpperCase();
s=s+" ";
int l=s.length();
String word="";
int n=0;
int w=0;//no of words in s(loop1)
int wor=0;//no of words loop2
for(int i=0;i<l;i++)
{char c=s.charAt(i);
if(c==' ')
w++;
}
for(int i=0;i<l;i++)
{ char c=s.charAt(i);
int m=s.indexOf(' '); //length of first word
if(i==0)
{ for(int j=0;j<m;j++)
{char c1=s.charAt(j);
if(c1=='A'||c1=='E'||c1=='I'||c1=='O'||c1=='U')
{n=j;//index of first vowel
j=m;}
}
word=s.substring(n,m)+s.substring(0,n);
System.out.print(word+"AY"+" ");
}
if(c==' '&&wor!=w-1)
{ s=s.substring(m+1,l);
l=s.length();
i=0;
wor++;
}
if(wor==w-1)
i=l+1;
}
}
}

You can simplify it greatly by splitting the sentence on whitespace and processing each word of the resulting array.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = scanner.nextLine();
s = s.toUpperCase();
String[] words = s.split("\\s+");// Split s on whitespace
// Process each word from words[]
for (String word : words) {
int m = word.length(), j;
for (j = 0; j < word.length(); j++) {
char c1 = word.charAt(j);
if (c1 == 'A' || c1 == 'E' || c1 == 'I' || c1 == 'O' || c1 == 'U') {
break;
}
}
String translated = word.substring(j, m) + word.substring(0, j);
System.out.print(translated + "AY" + " ");
}
}
}
A sample run:
Enter a sentence: Her food is stolen
ERHAY OODFAY ISAY OLENSTAY
Alternatively, in addition to using String#indexOf​(int ch), you can use String#indexOf​(String str, int fromIndex) to get all the words of the sentence.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = scanner.nextLine();
s = s.toUpperCase();
// Start from index, 0
int fromIndex = 0, lastPositionOfWhitespace = -1;
for (int i = 0; i < s.length(); i++) {
int indexOfWhitespace = s.indexOf(' ', fromIndex);
String word = "";
if (indexOfWhitespace != -1) {
lastPositionOfWhitespace = indexOfWhitespace;
word = s.substring(fromIndex, indexOfWhitespace);
fromIndex = indexOfWhitespace + 1;
} else {
word = s.substring(lastPositionOfWhitespace + 1);// Last word of the sentence
i = s.length();// To stop further processing of the loop with counter, i
}
int m = word.length(), j;
for (j = 0; j < word.length(); j++) {
char c1 = word.charAt(j);
if (c1 == 'A' || c1 == 'E' || c1 == 'I' || c1 == 'O' || c1 == 'U') {
break;
}
}
String translated = word.substring(j, m) + word.substring(0, j);
System.out.print(translated + "AY" + " ");
}
}
}
A sample run:
Enter a sentence: Her food is stolen
ERHAY OODFAY ISAY OLENSTAY

Related

Java while loop text formatting

Inputs
Hi.
Bye.
#
Actual outputs:
h(1)i(1)
Expected outputs:
h(1) i(1)
b(1) e(1) y(1)
There must be a gap between both items. How do I need to modify my while loop so # will indicate stop?
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
int a[] = new int[26];
Scanner sc = new Scanner (System.in);
String str = sc.nextLine();
for (char ch : str.toCharArray())
if (ch >= 65 && ch <= 90)
a[ch - 65]++;
else if (ch >= 97 && ch <= 122)
a[ch - 97]++;
for (int i = 0; i < 26; i++)
if (a[i] > 0)
System.out.print((char)(i + 97) + "(" + a[i] + ")");
}
}
First question
Seems you just need to add a space at the end of the print. You have this:
System.out.print( (char)(i+97)+ "(" + a[i]+")");
It should be:
System.out.print( (char)(i+97)+ "(" + a[i]+") "); // Added a space at the end.
Or you could also print the space later:
System.out.print( (char)(i+97)+ "(" + a[i]+")");
System.out.print(" ");
Second question
About the while-loop, you could wrap what you have within the loop and should work, something like:
// This will be used for the initial value ONLY, in your example, it should be the "Hi"
String str = sc.nextLine();
while (!str.equals("#")) {
int a[]=new int[26];
for(int i = 0; i<str.length();i++) {
if(str.charAt(i)>=65 && str.charAt(i)<=90) {
a[str.charAt(i)-65]++;
}
else if(str.charAt(i)>=97 && str.charAt(i)<=122) {
a[str.charAt(i)-97]++;
}
}
for(int i=0;i<26;i++) {
if(a[i]>0) {
System.out.print( (char)(i+97)+ "(" + a[i]+")");
}
}
System.out.println(); // Printing new line to split next output
// This will be for the next inputs you have, in your example: "Bye" and "#"
str = sc.nextLine();
}
The space can be added into the print statement.
The loop can end when user enters # character.
Added one extra println to improve appearance.
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
String str = "";
int a[];
Scanner sc = new Scanner(System.in);
while (!(str = sc.nextLine()).equals("#")) {
a = new int[26];
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= 65 && str.charAt(i) <= 90) {
a[str.charAt(i) - 65]++;
} else if (str.charAt(i) >= 97 && str.charAt(i) <= 122) {
a[str.charAt(i) - 97]++;
}
}
for (int i = 0; i < 26; i++) {
if (a[i] > 0) {
System.out.print((char) (i + 97) + "(" + a[i] + ") "); // space added
}
}
System.out.println(""); // looks better with this
}
sc.close();
}
}

print the word which has maximum number of vowel in java

I want to print the word which is containing maximum number of vowel. But Problem is that last word of sentence which is containing maximum number is not print. please help me solve that problem. My code is below.
When i enter input 'Happy New Year', Output is 'Yea' .But i want i output is 'Year'
import java.util.Scanner;
public class Abcd {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter The Word : ");
String sentence = sc.nextLine();
String word = "";
String wordMostVowel = "";
int temp = 0;
int vowelCount = 0;
char ch;
for (int i = 0; i < sentence.length(); i++) {
ch = sentence.charAt(i);
if (ch != ' ' && i != (sentence.length() - 1)) {
word += ch;
ch = Character.toLowerCase(ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
}
} else {
if (vowelCount > temp) {
temp = vowelCount;
wordMostVowel = word;
}
word = "";
vowelCount = 0;
}
}
System.out.println("The word with the most vowels (" + temp + ") is: " + " " + wordMostVowel);
}
}
You cut words at spaces (correct), but you also cut at the last character, even if it's not a space (so this character is never dealt with). And that's not correct.
Here is a possibility:
import java.util.Scanner;
public class Abcd {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the sentence : ");
String sentence = sc.nextLine();
String wordMostVowels = "";
int maxVowelCount = 0;
for (String word : sentence.split(" ")) {
int vowelCount = 0;
for (char c : word.toLowerCase().toCharArray()) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowelCount++;
}
}
if (vowelCount > maxVowelCount) {
maxVowelCount = vowelCount;
wordMostVowels = word;
}
}
System.out.println("The word with the most vowels (" + maxVowelCount + ") is: " + wordMostVowels);
}
}

Array out of Bounds? with string split

Array out of bounds ? i'm trying to perform the output in the picture:
Using this INPUT
"JAVA IS A PROGRAMMING LANGUAGE"
This is my code so far
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input Phrase:");
String s = in.nextLine();
String[] word=s.split(" ");
String rts=" ";
for(int i=0;i<word.length;i++){
if(word[i].length()>=rts.length()){
rts=word[i];
}
}
int thisislength = rts.length();
for (int a = 0; a < thisislength ;a++ ) {
for (int b = 0; b < word.length ;b++ ) {
System.out.print(word[b].charAt(a)+" ");
}
System.out.println();
}
}
}
When the second word reaches its last letter it doesn't continue the for loop, is there any way to continue the loop even if the second word reaches its max length.
< should have been <=. Reversing left and right hand sides makes it more readably I think.
for (int a = 0; a < thisislength; a++) {
System.out.printf("%3d ", a+1);
for (int b = 0; b < word.length; b++) {
if (a >= word[b].length()) {
System.out.print(' ');
} else {
System.out.print(word[b].charAt(a));
}
System.out.print(' ');
}
System.out.println();
}
Or instead of the if-else statement:
for (String w : word) {
System.out.print(a >= w.length() ? ' ' : w.charAt(a));
}
This gives the result you want:
for (int a = 0; a < thisislength ;a++ ){
for (int b = 0; b < word.length ;b++ ){
if(word[b].length() < a + 1){
System.out.print(" ");
}else{
System.out.print(word[b].charAt(a) + " ");
}
}
System.out.println();
}
This line was changed:
if(word[b].length() < a + 1) and not if(word[b].length() < a)
and 2 spaces print in the if statement
TRY THIS SOLUTION HOPE IT WILL HELP YOU :
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
// GET VALUE FROM THE CONSOLE
Scanner in = new Scanner(System.in);
System.out.print("Input Phrase:");
String s = in.nextLine();
// SPLIT STRING TO WORDS
String[] words = s.split(" ");
// CREATE A LIST OF CHAR_ARRAY CALLED : matrix
List<char[]> matrix = new ArrayList<char[]>();
// REFERENCE THE LARGEST WORD IN WORDS ARRAY EX : PROGRAMMING IS THE LARGEST
int max = 0;
// FILL OUR LIST OF ARRAY OF CHARS
for (int b = 0; b < words.length ;b++ ) {
char[] chars = words[b].toCharArray();
max = (chars.length >= max)? chars.length : max ;
matrix.add( chars );
}
// PRINT OUR CHAR
for (int a = 0; a < max ;a++ ) {
for (int b = 0; b < words.length ;b++ ) {
if(a < matrix.get(b).length) {
System.out.print(matrix.get(b)[a]);
System.out.print(" ");
}else {
System.out.print(" ");
System.out.print(" ");
}
}
System.out.println("");
}
}
}

How do you use charAt with an array?

i am having a bit of trouble in implementing charAt with an array. I am a beginner in Java (and this is my only coding experience i suppose).
The objective: To create a program that the user inputs any string, and the total number of vowels are recorded in the output (case sensitive)
example:
Input: charActer
Output:
a = 1
A = 1
e = 1
import java.util.Scanner;
public class HW5 {
public static void main(String[] args) {
String [] alphabets =
{"aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ"};
String vowels = "aAeEiIoOuU";
int found = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: ");
String inputStr = sc.nextLine();
for(int i=0;i<alphabets.length;i++)
{
if(alphabets.charAt[i] == vowels)
*Note: Program is not complete.
You need to check each character of inputStr (dunno what alphabets is about in your code) and see if it can be found in the vowels string.
String vowels = "aAeEiIoOuU";
int found = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: ");
String inputStr = sc.nextLine();
for (int i = 0; i < inputStr.length(); i++) {
if (vowels.indexOf(inputStr.charAt(i)) >= 0) {
found += 1;
}
}
The documentation is helpful if you're having trouble understanding a method or class.
Having said that, there are lots of ways to count vowels in a String.
Your output indicates that you need the counts per vowel per case, and not just the count of all vowels. To do this you will need a map in order to keep track.
Consider something like
String input = "A string with vowels in it";
Map<Character, Integer> counts = new HashMap<≥();
for (int i = 0; i < input.length; i++) {
char c = input.chart(i);
if (c == 'a') {
int tmp = counts.getOrDefault('a', 0);
tmp++;
counts.put('a', tmp);
} else if (c == 'A') {
// same logic as above for uppercase A
} // other else if statements for e, E, i, I, o, O, u, U
}
// the map has all counts per vowel / case
After the map has all counts you can iterate its entry set to print the output you need
for (Map.Entry<Character, Integer> e : counts. entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}
If you only need the number of values without breaking it down into which vowels, consider something like (not tested)
String vowels = "AaEeIiOoUu";
String input = "Hello World!";
int numVowels = 0;
for (int i = 0; i < input.length; i++) {
char c = input.charAt(i);
if (vowels.indexOf(c) >= 0) {
numVowels++;
}
}
// do something with numVowels
--
Break the problem into simple steps
Define the vowels to look for
Initialize your counter variable (numVowels)
Loop through the input string and check each character against the ones defined in 1 (vowels).
For each vowel you find, increment your counter variable.
public class Vowels {
public static void main(String[] args) {
Map<Character, Integer> vowels = new HashMap<>();
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: "); //"charActer";
String str = sc.nextLine();
for (int i = 0; i < str.length(); i++) {
Character c = str.charAt(i);
if (c == 'a'
|| c == 'A'
|| c == 'e'
|| c == 'E'
|| c == 'i'
|| c == 'I'
|| c == 'o'
|| c == 'O'
|| c == 'u'
|| c == 'U') {
if (vowels.containsKey(c)) {
vowels.put(c, vowels.get(c) + 1);
} else {
vowels.put(c, 1);
}
}
}
for (Map.Entry<Character, Integer> entry : vowels.entrySet()) {
System.out.print(entry.getKey() + "=" + entry.getValue() + " ");
}
}}
Input : charActer
Output : a=1 A=1 e=1

How to convert user input string to pig latin?

Im trying to convert a user entered string that starts with a consonant to pig latin buy moving all the consonants to the end of the word till the word starts with a vowel, and then adding "ay" to the end of the word. I have a for loop that's supposed to do this, but for some reason, it outputs nothing. What am i doing wrong here? Im stumped.
Here's the code:
import java.util.Scanner;
public class two {
public static void main(String[] args) {
System.out.println("Please enter a word");
Scanner word = new Scanner(System.in);
String pigLatin = word.nextLine();
while (!pigLatin.equalsIgnoreCase("quit")) {
if (isVowel(pigLatin.charAt(0))) {
pigLatin = (pigLatin + "way");
System.out.println(pigLatin);
}
else {
for (int i = 0; i < pigLatin.length(); i++) {
char firstChar = pigLatin.charAt(0);
pigLatin = pigLatin.substring(1);
pigLatin = pigLatin + firstChar;
if (i >= pigLatin.length())
{
pigLatin = pigLatin + "ay";
System.out.println(pigLatin);
}
}
}
System.out.println("Please enter a word");
pigLatin = word.nextLine();
}
word.close();
}
private static boolean isVowel(char ch) {
char v = Character.toLowerCase(ch);
if (v == 'a' || v == 'e' || v == 'i' || v == 'o' || v == 'u') {
return true;
}
else {
return false;
}
}
}
You need a less than or equal <= on the i otherwise i is never greater than or equal to pigLatin.length().
for (int i = 0; i <= pigLatin.length(); i++) {
char firstChar = pigLatin.charAt(0);
pigLatin = pigLatin.substring(1);
pigLatin = pigLatin + firstChar;
if (i >= pigLatin.length())
{
System.out.println(pigLatin);
}
}
your for loop condition is
i < pigLatin.length()
and you said in if
if(i >= pigLatin.length()){....}
so this condition will never be true , for that reason there is no output,
see below code ,
import java.util.Scanner;
/**
*
* #author rahmat waisi
*/
public class PigLatin {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
while (true) {
// System.out.print("Please enter a word: , Enter [ quit ] for exit : ");
String pigLatin = scanner.nextLine();
if (pigLatin.equals("quit")) {
break;
}
if (isVowel(pigLatin.charAt(0))) {
pigLatin += "ay";
System.out.println(pigLatin);
} else {
String output = "";
int separation_index = findFirstVowel(pigLatin);
if (separation_index ==-1) {
System.out.println(pigLatin+"ay");
continue;
}
output+= pigLatin.substring(separation_index);
output+= pigLatin.substring(0, separation_index) + "ay";
System.out.println(output);
}
}
}
}
private static boolean isVowel(char ch) {
char v = Character.toLowerCase(ch);
return v == 'a' || v == 'e' || v == 'i' || v == 'o' || v == 'u';
}
private static int findFirstVowel(String str) {
for (int i = 0; i < str.length(); i++) {
if (isVowel(str.charAt(i))) {
return i;
}
}
return -1;
}
}
here is some input:
pig
banana
trash
happy
duck
glove
eat
omelet
are
ffff
quit
and their output is:
igpay
ananabay
ashtray
appyhay
uckday
oveglay
eatay
omeletay
areay
ffffay

Categories