I was given to code something similar to piglatin. But I am getting the "ig" of pig in latin. What is wrong with the code?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
String end = "ay";
int i, j;
String word = "";
String[] arr = str.split(" ");
for (j = 0; j < arr.length; j++) {
String indWord = arr[j];
char c = indWord.charAt(0);
for (i = 1; i < indWord.length(); i++) {
word = word + indWord.charAt(i);
}
String res = "";
res = word + c + end + " ";
System.out.print(res);
}
}
}
Axpected:
pig latin ----> igpay atinlay
Actual:
Because you are not clearing the word variable for each iteration... that was hard to see because your indentation is wrong.
Move the String word=""; line to the inside of the for(j=0;j<arr.length;j++){ loop so that the word variable is cleared for every word and you start over (instead of carrying its contents from the last word)
Related
Count vowel in the word for method
public class Methods6 {
public static int countVowel(String words) {
int count = 0;
char[] vowel = {'a', 'e', 'i', 'o', 'u'};
for (int i = 0; i < words.length(); i++) {
char ch = words.charAt(i);
for (char cc : vowel) {
if (ch == cc) {
count++;
}
}
}
return count;
}
**Find max vowel in sentence **
public static String maxVowelWords() {
String sentence = getSentence().toLowerCase();
String words[] = sentence.split(" ");
int maxvowel = CountVowel(words[0]), count;
String maxWord = words[0];
for (int i = 1; i < words.length; i++) {
count = CountVowel(words[i]);
if (count > maxvowel) {
maxvowel = count;
maxWord = words[i] + " ";
}
}
return maxWord;
}}// 2 methods are located in the same Method Class
public class Test {
public static void main(String[] args) {
System.out.println(Methods6.MaxVowelWords());}}
When writing this method, it gives only the first word with the most vowel letters (eg. --------- hello my friend! ----------- just hello, hello and friend -------no!
How can I change the method of this?
Thanks for helps!
The way I interpret this question is that:
Find the word in the supplied String which contains the most vowels
in it.
If one or more words within that very same String contain equal
maximum number of vowels then concatenate the words together
delimited by a whitespace (or whatever).
So, if the String supplied was: "hello my friend" then both words, hello and friend, would be returned from the maxVowelWords() method in the form of (let's say):
hello, friend
Since both hello and friend contain 2 vowels which so happens to be the the max number of vowels in any given word then both words are returned.
If the supplied string however was: "hello my friend - I live on the Mississippi river." then only Mississippi is returned from the method since it is the only word within that String that contains a maximun number of 4 vowels. All other words containing vowels within the string contain a lesser vowel count.
If this is indeed the situation then your method should look something like this:
public static String maxVowelWords() {
String sentence = getSentence();
String words[] = sentence.split(" ");
int maxvowel = 0;
String maxWord = "";
for (int i = 0; i < words.length; i++) {
int count = countVowels(words[i]);
if (count == maxvowel) {
maxvowel = count;
// Ternary Operator is used here to applt the delimiter (", ") if needed,
maxWord += (maxWord.equals("") ? words[i] : ", " + words[i]) + " (" + count + " vowels)";
}
else if(count > maxvowel) {
maxvowel = count;
maxWord = words[i] + " (" + count + " vowels)";;
}
}
return maxWord;
}
Yes, you start your loop from 0 and maxWord String variable should be initialized to hold an empty string (""). Let the for loop do its work. And No, count is not a waste, it's actually a requirement in order to to acquire the maximum vowel count for maxvowel as each string word is placed through the process.
You utilize a method named getSentence() to acquire the String to process and right away you distort that Original String by setting it to all lower case. You really shouldn't do that since the words you return from your maxVowelWords() method will not be the originally supplied words should they happen to have upper case vowels. A small modification to the countVowel() method can take care of that business, for example:
if (Character.toLowerCase(ch) == cc) {
count++;
}
There are few bugs in your code. Try this :
public static String maxVowelWords() {
String sentence = getSentence().toLowerCase();
String words[] = sentence.split(" ");
int maxvowel = 0, count;
String maxWord = "";
for (int i = 0; i < words.length; i++) {
count = countVowel(words[i]);
if (count > maxvowel) {
maxvowel = count;
maxWord = "";
}
if(count == maxvowel){
maxWord = maxWord + words[i]+ " ";
}
}
return maxWord.trim();
}
Suppose you have a String and a CAPITAL letter in that indicates ending of a word. For example, if you have wElovEcakE where E, E and K indicates end of the words wE, lovE and cakE respectively. You need to reverse each word (as you know where it ends). Don’t reverse the String as a whole. To illustrate, if we give wElovEcakE as input output should be EwEvolEkac. See wE became Ew, lovE became Evol and so on....
And the way i tried to approach with ..
import java.util.Scanner;
public class Alternative {
public static void main(String[]args) {
Scanner robo=new Scanner (System.in);
System.out.println("Enter a word ");
String word=robo.nextLine();
char[] array=word.toCharArray();
for(int i =0;i<array.length;i++){
int count =0;
for(int j=0;j<=("EMPTY");j++) // here i am trying to operate a loop where it will work up to the Capital letter.
count ++;
}
//Code incomplete
}
}
}
Above i have mentioned "EMPTY" in the condition part ... i want to operate a loop where my loop will work up to the capital letter , then i will count all the letter that i have counted up to capital letter then last step will be like i will make another loop where i will reverse all the letter where condition for the loop will <=count ;Example:lovE (counted 4 letters i will reverse four times back).
Can you guys help me to write the condition at "EMPTY" part if you think that my approach is correct ..
Can you guys help me to solve the problem in any other way ?
test if this works for you:
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
String textInvert = "";
int indexAnt = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
String wordSplit = word.substring(indexAnt, i + 1);
for (int j = wordSplit.length() - 1; j >= 0; j--)
textInvert += wordSplit.charAt(j);
indexAnt = i + 1;
}
}
System.out.println(textInvert);
Here is my solution with Regex pattern
String[] in = "wElovEcakE".replaceAll("([A-z]+?[A-Z])","$1,").replaceAll(",$","").split(",");
String out = "";
for(String current: in){
StringBuilder temp = new StringBuilder();
temp.append(current);
out+=temp.reverse();
}
System.out.println(out);
Result:
EwEvolEkac
Here is a solution that makes use of the StringBuilder class to hold and reverse each found word.
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word:");
String word = robo.nextLine();
robo.close();
String upperCase = word.toUpperCase(); //used to find uppercase letters
StringBuilder builder = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
char nextChar = word.charAt(i);
builder.append(nextChar);
if (nextChar == upperCase.charAt(i)) {
String subWord = builder.reverse().toString();
System.out.print(subWord); //It's not clear what to do with the found words
builder = new StringBuilder();
}
}
System.out.println();
Example
Enter a word:
makEmorEpiE
EkamEromEip
You can try this solution:
String textInvert = "wElovEcakE";
String revertText = textInvert
.chars().mapToObj(c -> (char) c)
.reduce(new LinkedList<>(Arrays.asList(new StringBuilder())), (a, v) -> {
a.getLast().append(v);
if (Character.isUpperCase(v)) {
a.add(new StringBuilder());
}
return a;
}, (a1, a2) -> a1)
.stream()
.map(s -> s.reverse())
.reduce(StringBuilder::append)
.map(StringBuilder::toString)
.get();
System.out.println(revertText);
public class Alternative {
public static void main(String[] args) {
Scanner robo = new Scanner(System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
char[] array = word.toCharArray();
int count = -1;
for (int i = 0; i < array.length; i++) {
if (Character.isUpperCase(array[i])) { //find the upper case letters in the word
for (int j = i; j > count; j--) //loop through the letters until the last count variable value is encountered
System.out.print(array[j]); //print the reversed values
count = i; //assign the last encountered uppercase letter's index value to count variable
}
}
}
}
i am writing a program that must scramble a word. First I read in the word backwards using .reverse. Then I turned the string into a charArray.I am suppose to create a for loop to figure out if the First letter is "A" and if it is then i have to see if the next letter is not an "A". if its not then i am suppose to swap the two letters. If any of the two letters have a;ready been swapped than they cannot be swapped again.
Some examples are
Input: “TAN” Output: “ATN”
Input: “ALACTRIC” Output:“AALCTRIC”
Input: "Fork" Output:"Fork"
Here is my code so far: i cannot figure out what to put in the for loop. Thank you!
import java.util.Scanner;
public class scrambleWordRetry {
public static void main(String[] args)
{
}
public static String scramble( Random random, String inputString)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a word to scramble.");
inputString = scan.nextLine();
char a[] = inputString.toCharArray();
for( int i=0 ; i<a.length-1 ; i++ )
{
}
return inputString;
}
}
I hope this code is useful for you
Scanner x = new Scanner(System.in);
String str = x.next();
System.out.println("Before Swapping" + str);
str = scramble(str);
System.out.println("After Swapping " + str);
}
public static String scramble(String inputString) {
char s[] = inputString.toCharArray();
for (int i = 1; i < s.length; i++) {
if (s[i] == 'A' || s[i] == 'a') {
char temp = s[i - 1];
s[i - 1] = s[i];
s[i] = temp;
}
}
return new String(s);
}
then if you input 'ALACTRIC' the output will be 'AALCTRIC',
'Tan = aTn',
'fork = fork'.
I have been trying to write a Java program which converts the first letter of every word of a string into a capital letter. Right now it looks like this:
package strings;
import java.util.Scanner;
public class small_cap {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
String st = sc.next();
String str = " " + st;
int j = 0; char chr = ' ';
for (int i = 0; i < str.length(); i++){
j = i + 1;
chr = str.charAt(j);
if (chr == ' '){
char a = Character.toUpperCase(str.charAt(j));
str = str.replace(str.charAt(j), a);
}
else{
char a = Character.toLowerCase(str.charAt(j));
str = str.replace(str.charAt(j), a);
}
}
System.out.println(str);
}
}
Unfortunately I keep on getting the error:
java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:658)
at small_cap.main(small_cap.java:19)
I don't really see any fault in the code. Can someone please point out where I am going wrong?
You were using Scanner.next() rather then Scanner.nextLine() which will read the whole sentence rather then single word.
You are adding extra space in String. Don't know the big reason behind that. It can be done without it.
Let say the Input is : "abc def" which will become " abc def" after adding extra space. Length of string will become : 7
Now for loop will iterate from 0 to 6. But on i = 6 it will try to alter the element on 7th position (since you are doing j=i+1) which will cause string index out of range error.
You are using String.Replace which will replace all matching characters irrespective of their position.
import java.util.Scanner;
public class small_cap {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
String st = sc.nextLine();
String str = " " + st;
int j = 0; char chr = ' ';
for (int i = 0; i < str.length()-1; i++){
j = i+1;
chr = str.charAt(i);
if (chr == ' '){
char a = Character.toUpperCase(str.charAt(j));
str = str.substring(0,j)+a+str.substring(j+1);
}
else{
char a = Character.toLowerCase(str.charAt(j));
str = str.substring(0,j)+a+str.substring(j+1);
}
}
System.out.println(str);
}
}
for (int i = 0; i < str.length(); i++){
j = i + 1;
When i reaches the last valid index length - 1, j will be equal to length, which is out of bounds.
I don't really see the point of the j variable to begin with - did you mean to use i somewhere else inside the loop as well, or should you just make your loop start from 1? Or did you perhaps mean to check the previous character by doing j = i - 1; (in that case make sure you don't read before index 0)
I am working on printing the number of characters taken from a users input. So lets say the user enters here is a random test which totals 17 characters. Here is what I have thus far only printing the words in separate lines.
import java.text.*;
import java.io.*;
public class test {
public static void main (String [] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String inputValue;
inputValue = input.readLine();
String[] words = inputValue.split("\\s+");
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
}
}
}
str.replaceAll("\\s+","");removes all whitespaces in str and assigns the resultant string to str
str.length() returns number of characters in String str
So when you get the input from user, do this
inputValue=inputValue.replaceAll("\\s+","");
System.out.println(inputValue.length());
Change your for...loop to this:
int total = 0;
for (int i = 0; i < words.length; i++) {
total += words[i].length();
}
System.out.println(total);
Essentially, we're looping through the array of words, getting each word's length, then adding that number of characters to the total counter.
I think we can avoid iteration over words length if we assume, string is separated by blanks only. Here is an example:
public static void main(String args[]) {
String test = "here is a random test";
String[] array = test.split("\\s+");
int size = array.length > 0 ? (test.length() - array.length + 1) : test.length();
System.out.println("Size:" + size);
}
to get the total count you have to assign each words count to a variable. Then print it after for loop.
int count =0;
for (int i = 0; i < words.length; i++) {
count = count + words[i].length();
}
System.out.println(count );
Fewmodification done,
length printed for words and user input.
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String inputValue;
inputValue = input.readLine();
String[] words = inputValue.split("\\s+");
System.out.println("Length of user input = " + inputValue.length());
for (int i = 0 ; i < words.length ; i++) {
System.out.println(words[i]);
System.out.println("Length of word = " + words[i].length());
}
}
Output
here is a random test
Length of user input = 21
here
Length of word = 4
is
Length of word = 2
a
Length of word = 1
random
Length of word = 6
test
Length of word = 4
You can do something like this if you are concerned only with whitespaces:
inputValue = input.readLine();
int len = inputValue.replaceAll(" ", "").length(); //replacing won't effect the original string and will also replace spaces.
System.out.println(len);
System.out.println(inputValue);
so the o/p would be for sample you provided:
17
here is a random test