I am trying to create a program that translates English to PigLatin. I have most of the components, but if I enter in more than one word, it only translates the first word. Where is the issue and how do I fix it.
public class PigLatin{
public static String translate(String phrase){
String [] returnArray=phrase.split(" ");
String [] translateArray=new String [returnArray.length];
for(int i=0;i<returnArray.length;i++){
translateArray[i]=translateWord(returnArray[i]);
}
return StringLib.join(translateArray, " ");//translated Array
}
public static String translateWord(String word) {
String tword=word;
int indexVowel=indexOfFirstVowel(tword);
if(indexOfFirstVowel(tword)==0){
tword=tword+"yay";
}
else {
tword=tword.substring(indexOfFirstVowel(tword),tword.length())+tword.substring(0,indexOfFirstVowel(tword))+"ay";
}
return tword;
}
public static int indexOfFirstVowel(String word) {//check where the first vowel is
String vowels = "aeiouy";
String loweredWord=word.toLowerCase();
for (int index=0;index<loweredWord.length();index++){
if(vowels.contains(String.valueOf(loweredWord.charAt(index)))){
return index;
}
}
return -1;
}
public static void main(String [] args){
Scanner inp=new Scanner(System.in);
System.out.println("Please enter a phrase:");
String trans=translate(inp.next());
System.out.println("Here is your phrase in Pig Latin.");
System.out.println(trans);
}
String.join translates the array into a String and here is that code
public class StringLib {
public static String join(String[] strs, String sep) {
String joined = "";
if (strs.length > 0) {
joined = strs[0];
for (int i = 1; i < strs.length; i++) {
joined = joined + sep + strs[i];
}
}
return joined;
}
Change this line in your main method
String trans = translate(inp.next());
Into
String trans = translate(inp.nextLine());
Related
I'm trying to get the number of matched words in an ArrayList in my Java program
This is the whole thing: The problem is with the numMatch class:
import java.util.*;
public class WordPairsList {
private ArrayList<WordPair> allPairs;
public WordPairsList(String[] words)
{
allPairs = new ArrayList<WordPair>();
for (int i = 0; i < words.length - 1; i++){
for (int j = i + 1; j < words.length; j++){
if (j == i){
allPairs.add( new WordPair(words[i], words[j]));
}
}
}
}
public int numMatches() {
/* in here I need to have a for loop that goes through the ArrayList allPairs and for
each WordPair in allPairs, it checks to see if its first word (using the getFirst() method)
equals the second word (using the getSecond() method). If there is a match, it increments a
counter which it returns at the end of the method. To test this method, add another “there” into
the words array and then uncomment the call to numMatches().
*/
return 0;
}
public String getFirst() {
return allPairs.getFirst();
}
public String getSecond() {
return allPairs.getSecond();
}
public String toString() {
return allPairs.toString();
}
public static void main(String[] args) {
String[] words = {"Hi", "there", "Tyler", "Sam"};
WordPairsList list = new WordPairsList(words);
System.out.println(list);
//For second part below, uncomment this test:
System.out.println("The number of matched pairs is: " + list.numMatches());
}
}
class WordPair {
private String word1;
private String word2;
public WordPair(String w1, String w2) {
word1 = w1;
word2 = w2;
}
public String getFirst() {
return word1;
}
public String getSecond() {
return word2;
}
public String toString() {
return "(" + word1 + ", " + word2 + ")";
}
}
So I need help with how to call the getFirst() and getSecond() Methods and how to compare them using a for loop! I also don't know how to set a counter to count how many similar words are there! can you please help me!
Thanks!
Not sure if this is what you need, but this will iterate over the list of wordpairs and count them:
import java.util.*;
class WordPairsList {
//can be final and List interface
private final List<WordPair> allPairs;
public WordPairsList(String[] words)
{
allPairs = new ArrayList<>();
//As I understood it you want to take the input and generate word pair from every two words?
for (int i = 0; i < words.length - 1; i += 2){
allPairs.add( new WordPair(words[i], words[i+1]));
}
}
public int numMatches() {
//initialize your count variable
int count = 0;
//loop over your word pairs (if your java version doesn't support this, use a for(int i = 0....) loop as seen above
for (WordPair wordPair : allPairs) {
///debug print
System.out.println("Testing: "+ wordPair.toString());
//check if pair.getfirst equals pair.getsecond
if(wordPair.getFirst().equals(wordPair.getSecond())){
//increase count
count += 1;
}
}
//return count
return count;
}
public static void main(String[] args) {
String[] words = {"Hi", "there", "Tyler", "Sam", "Bob", "Bob"};
WordPairsList list = new WordPairsList(words);
System.out.println("The number of matched pairs is: " + list.numMatches());
}
}
class WordPair {
private final String word1;
private final String word2;
public WordPair(String w1, String w2) {
word1 = w1;
word2 = w2;
}
public String getFirst() {
return word1;
}
public String getSecond() {
return word2;
}
public String toString() {
return "(" + word1 + ", " + word2 + ")";
}
}
String[] enc=new String[]{"w","e","l","c","o","m"};
String[] cod=new String[] {"111","10","00","110","010","011"};
String real="";
int sindex=0;
int eindex=1;
String cdd="111100011001001110";
StringBuilder code=new StringBuilder(cdd);
String temp;
for(int i=0;i<code.length();i++){
temp=code.substring(sindex, eindex++);
if(Arrays.asList(cod).contains(temp)){
int j=Arrays.asList(cod).indexOf(temp);
int z=code.indexOf(temp);
StringBuilder y = code.delete(z, z+temp.length());
temp=y.toString();
real+=enc[j];
System.out.println(y);
}
}
I have these two arrays enc[] and cod[], contains characters and codes respectively what i want to do is just check each value of cod array in cdd string and replace it with its respective String from enc[]...
By running this code i am getting only "w" while the result was suppose to be "welcome".
Try this code - i have refactored yours :)
public class enc {
private static boolean valueFound=false;
public static void main(String[] args) {
String[] enc=new String[]{"w","e","l","c","o","m"};
String[] cod=new String[] {"111","10","00","110","010","011"};
String real="";
int sindex=0;
int eindex=1;
String cdd="111100011001001110";
do {
for (int i = 0; i < cod.length; i++) {
if (cdd.startsWith(cod[i])) {
real += enc[i];
cdd = cdd.substring(cod[i].length());
valueFound = true;
} else {
valueFound = false;
}
}
}
while(valueFound);
System.out.println(real);
}
}
I need your help in adding whitespace before a string as I need to format the String value to be in a specific position in the page. For example:
System.out.println(" Hello Word!!");
The above will give 10 spaces before the String which I did them manual, but is there any other way to specify the space before the String other than adding manual spaces?
Consider this as your code....
public static void main(String[] args) {
String hello = "hello";
Brute b = new Brute();
System.out.println( b.addspace(1,hello));
}
String addspace(int i, String str)
{
StringBuilder str1 = new StringBuilder();
for(int j=0;j<i;j++)
{
str1.append(" ");
}
str1.append(str);
return str1.toString();
}
This will add desired no of spaces in the string at its beginning...
Just pass your input String and no of spaces needed....
As addspace(<no_of_spaces>,<input_string>);
String newStr = String.format("%10s", str);
String str = "Hello Word!!";
String.format("%1$" + (10 + str.length()) + "s", str);
Result:
| Hello Word!!|
10 whitespaces added
You can write your own fumction:
public static void main(String[] args) {
String myString = "Hello Word!!";
System.out.println(getWhiteSpace(10)+myString);
}
private static String getWhiteSpace(int size) {
StringBuilder builder = new StringBuilder(size);
for(int i = 0; i <size ; i++) {
builder.append(' ');
}
return builder.toString();
}
This may be useful to you,
String s = "%s Hellow World!";
StringBuilder builder = new StringBuilder();
for(int i=0;i<10;i++){
builder.append(" ");
}
System.out.println(s.format(s,builder.toString()));
You can change the modify the count of space in the for loop.
import java.io.*;
import java.util.*;
class spaceBeforeString
{
public static void main(String args[])
{
String str="Hello";
for(int i=0;i<10;i++)
{
str=" "+str;
}
System.out.println(str);
}
}
import java.util.*;
import java.io.*;
class AddSpaceDemo
{
String str;
int noOfSpaces;
Scanner sc=new Scanner(System.in);
void getInput()
{
System.out.println("Enter the string before which the space is to be added: ");
str=sc.next();
System.out.println("Enter the no. of spaces to be added before the string: ");
noOfSpaces=sc.nextInt();
}
String addSpaceBefore()
{
for(int i=0;i<noOfSpaces;i++)
{
str=" "+str;
}
return str;
}
}
class AddSpace
{
public static void main(String args[])
{
String s;
AddSpaceDemo a=new AddSpaceDemo();
a.getInput();
s=a.addSpaceBefore();
System.out.println("String after adding whitespace before string: ");
System.out.println(s);
}
}
I'm making a basic Java POS System. You set how many characters fits on the paper width and it align both to the left and to the right.
public class Main {
int width = 32;
public static void main(String[] args) {
String dash = "--------------------------------";
String item = "COMPANY NAME";
String price = "00.00";
String string = alignment(item, price);
String description = "123-456-7890";
String tax = "0.00";
String string2 = alignment(description, tax);
System.out.println(dash);
System.out.println(string);
System.out.println(string2);
}
private static String alignment(String item, String price) {
String s = "";
s += item;
int x = 0;
while(x < width - item.length() - price.length()) {
s += " ";
x++;
}
s += price;
return s;
}
}
I am trying to solve an excercise about a method that returns a new string in which the uppercase letters are changed to lowercase and lowercase letters are changed to uppercase.
It just return the first character of the string, i don't know what keeps causing it.
Here is my code:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a string: ");
String s = input.nextLine();
System.out.print("The new string is: " + swapCase(s));
}
public static String swapCase(String s) {
for (int i = 0; i < s.length(); i++) {
if (Character.isLowerCase(s.charAt(i))) {
s = String.valueOf(Character.toUpperCase(s.charAt(i)));
} else if (Character.isUpperCase(s.charAt(i))) {
s = String.valueOf(Character.toLowerCase(s.charAt(i)));
}
}
return s;
}
}
You are redefining the String s every iteration of your loop. You will want to concatenate your new chararcters to form a final case-swapped string.
public static String swapCase(String s) {
String swapped = "";
for (int i = 0; i < s.length(); i++) {
if (Character.isLowerCase(s.charAt(i))) {
swapped += String.valueOf(Character.toUpperCase(s.charAt(i)));
} else if (Character.isUpperCase(s.charAt(i))) {
swapped += String.valueOf(Character.toLowerCase(s.charAt(i)));
}
}
return swapped;
}
I want to count the spaces in a string:
public class SongApp {
public static void main(String[] args) {
String word = "a b c";
int i =0,spaceCount=0;
while(i<word.length()){
char temp = word.charAt(i);
System.out.println(temp);
if(" ".equals(temp)){
spaceCount++;
}
i++;
}
System.out.println("Spaces in string: "+spaceCount);
}
}
When I replace the if statement with if(temp.equals(" ")), I get a "cannot invoke(String) on the primitive type char.
I don't understand why this won't work.
It won't work because you are calling a method of Class String (equals()) on a value which is of primitive type 'char'. You are trying to compare a 'char' with a 'String'.
You must compare between 'char's and since it's a primitive value you need to use '==' boolean compare operator like:
public class SongApp {
public static void main(String[] args) {
String word = "a b c";
int i = 0,
spaceCount = 0;
while( i < word.length() ){
if( word.charAt(i) == ' ' ) {
spaceCount++;
}
i++;
}
System.out.println("Spaces in string: "+spaceCount);
}
}
You can use the replace function for String to replace all the spaces(" ") with no spaces("") and get the difference between the lengths before and after calling the replace function.
Go through this example:
class Test{
public static void main(String args[]){
String s1 = "a b c";
int s1_length = s1.length();
System.out.println(s1_length); // 5
String s2 = s1.replace(" ","");
int s2_length = s2.length();
System.out.println(s2_length); // 3
System.out.println("No of spaces = " + (s1_length-s2_length)); // No of spaces = 2
}
}
You can use commons-lang.jar to calculate this.
`public class Main {
public static void main(String[] args) {
String word = "a b c";
System.out.println("Spaces in string: " + StringUtils.countMatches(word," "));
}
}`
The source of "StringUtils.countMatches" is below:
public static int countMatches(String str, String sub) {
if (isEmpty(str) || isEmpty(sub)) {
return 0;
}
int count = 0;
int idx = 0;
while ((idx = str.indexOf(sub, idx)) != INDEX_NOT_FOUND) {
count++;
idx += sub.length();
}
return count;
}
public class CountSpace {
public static void main(String[] args) {
String word = "a b c";
String data[];int k=0;
data=word.split("");
for(int i=0;i<data.length;i++){
if(data[i].equals(" ")){
k++;
}
}
System.out.println(k);
}
}