I am writing a Java program that will take a sentence (or phrase) and translate it into a group of objects that the computer can easily read. I wanted to make a simple word separating program, and then extend it later on.
My code is like this:
package Literary;
import java.util.ArrayList;
public class WordParser {
public static String[] getWords(String tempone){
ArrayList<String> temptwo = new ArrayList();
ArrayList<Character> tempthree = new ArrayList();
for (int tempfour = 0; tempfour == tempone.length() - 1; tempfour++){
if (tempone.charAt(tempfour) != ' '){
tempthree.add(tempone.charAt(tempfour));
} else {
temptwo.add(getStringRepresentation(tempthree));
tempthree.clear();
}
}
String[] tempfive = new String[temptwo.size()];
for (int tempfour = 0; tempfour == tempfive.length - 1; tempfour++){
tempfive[tempfour] = temptwo.get(tempfour);
}
return tempfive;
}
/** Courtesy of Vineet Reynolds on StackExchange.
*
* "You can iterate through the list and create the string."
*
* #param list
* #return
*/
public static String getStringRepresentation(ArrayList<Character> list){
StringBuilder builder = new StringBuilder(list.size());
for(int i = 0; i == list.size() + 1; i++)
{
builder.append(list.get(i).charValue());
}
return builder.toString();
}
}
It's supposed to receive a string as an input, and return a list of strings that have been separated by spaces.
But when I run my main class:
import Literary.WordParser;
public class Start {
public static void main(String[] args) {
String x = "There was once a sword in the stone";
String[] tempstring = WordParser.getWords(x);
for (int i = 1; i == tempstring.length; i++){
System.out.println("Word " + i + " : " + tempstring[i]);
}
}
}
The console tells me nothing except run: and BUILD SUCCESSFUL (total time: 1 second).
I'm using Netbeans 8 and Java 1.7 if that helps.
Looks like the problem's here:
for (int i = 1; i == tempstring.length; i++) {
This for loop will run at most once: if tempstring is exactly one String long, it should print out the word.
However, since your test sentence has 8 words, nothing will ever print out (provided WordParser works correctly).
You probably want to change this line to: (note the < between i and tempstring.length.)
for (int i = 1; i < tempstring.length; i++) {
so that it will loop through all the items in tempstring.
You had multiple issues in your code:
1) for loops were not properly made, they would never execute. Use either !=, > or < instead of ==.
2) you don't need a method getWords() nor getStringRepresentation(). Method like that are already implemented in Java.
So the final code should be this:
public class WordParser {
public static String[] getWords(String tempone) {
return tempone.split(" ");
}
public static void main(String[] args) {
String x = "There was once a sword in the stone";
String[] tempstring = WordParser.getWords(x);
for (int i = 0; i < tempstring.length; i++) {
System.out.println("Word " + (i+1) + " : " + tempstring[i]);
}
}
}
Output:
Word 1 : There
Word 2 : was
Word 3 : once
Word 4 : a
Word 5 : sword
Word 6 : in
Word 7 : the
Word 8 : stone
I've also fixed your code that runs the same as above, if you are interested:
import java.util.ArrayList;
public class WordParser {
public static String[] getWords(String tempone) {
ArrayList<String> sarr = new ArrayList<String>();
ArrayList<Character> tempthree = new ArrayList<Character>();
String[] ansarr;
if(tempone.charAt(tempone.length()-1) != ' ')
tempone += " "; //Add white space to the end to catch the last word
for (int i = 0; i < tempone.length(); i++) {
if (tempone.charAt(i) != ' ') {
tempthree.add(tempone.charAt(i));
} else {
sarr.add(tempthree.toString());
tempthree.clear();
}
}
ansarr = new String[sarr.size()];
for (int i = 0; i < ansarr.length; i++) {
ansarr[i] = sarr.get(i);
}
return ansarr;
}
public static void main(String[] args) {
String x = "There was once a sword in the stone";
String[] tempstring = WordParser.getWords(x);
for (int i = 0; i < tempstring.length; i++) {
System.out.println("Word " + (i+1) + " : " + tempstring[i]);
}
}
}
Enjoy! :)
I think you should use String.split(" ") which seems to do the same thing
Change your main method as follows,
and it will work
public static void main(String[] args) {
String x = "There was once a sword in the stone";
String[] tempstring = WordParser.getWords(x);
for (int i = 1; i <= tempstring.length; i++){
System.out.println("Word " + i + " : " + tempstring[i - 1]);
}
}
For the WordParser you could use,
public class WordParser
{
public static String[] getWords(String tempone)
{
return tempone.split(" ");
}
}
First of, I would recommend using the split method to break up a sentence
it is defined as:
public String[] split(String regex, int limit)
and you can simply call
String s1=new String("Random words in a sentence");
String[] words=s1.split(" ");
in order to break the string up into words and you will now have a String
array of five elements where each element consists of a word
In Respect to your question, you are not using the conditional statement correctly
You want to iterate over the elements of the String array WHILE the position
is less than stringname.length, not only if it the position equals the stringname.length
Therefore, you must make the following changes in these parts of your code
For Example:
for (int i = 1; i == tempstring.length; i++)
should have its line changed to
for (int i = 1; i < tempstring.length; i++)
and this problem also occurs in various places in your WordParser.java file
It is useful to remember also that you may often want to start at index 0 instead
of index 1, as java has its' first indice as 0.
Related
I am currently in a Intro to Computer Language class and everyone few lessons I have to develop some minimal programs (we are given 5 different prompts and have to pick three of them to complete). Due to time, I moved on and completed a different program, but I still want to understand what is going wrong with this one.
It is supposed to translate a given phrase into Pig Latin using for loops and different methods (as broken down in their template, which I cannot change, though I know there is a more efficient way). I can get the words in the phrases to translate, but when I print out the array (either by converting it to a string or running a for loop to print each element out separately) some of the elements only print the reference code. Could someone tell me what's going on? Below is the code and then a sample of a few print outs.
import java.util.Arrays;
import java.util.Scanner;
public class PigLatin {
public static void main (String[] args){
Scanner scnr = new Scanner(System.in);
String userWord;
userWord = scnr.nextLine();
userWord = userWord.toLowerCase();
String[] wordArry = userWord.split(" ");
print(wordArry);
}
public static String[] translate(String[] words){
String[] pigLatin = new String[words.length];
for (int i = 0; i < words.length; ++i) {
if (isVowel(words[i].charAt(0)) == true){
pigLatin[i] = words + "ay";
}
else if (words[i].charAt(0) == 'y') {
pigLatin[i] = words[i].substring(findFirstVowel(words[i]), words[i].length()) + words[i].substring(0, findFirstVowel(words[i])) + "ay";
}
else {
pigLatin[i] = words[i].substring(findFirstVowel(words[i]), words[i].length()) + words[i].substring(0, findFirstVowel(words[i])) + "ay";
}
}
return pigLatin;
}
public static int findFirstVowel(String s){
char[] vowList = {'a','e','i','o','u','y'};
for (int i = 1; i < s.length(); ++i) {
for (int j = 0; j < vowList.length; ++j) {
if (s.charAt(i) == vowList[j]) {
return i;
}
}
}
return -1;
}
public static boolean isVowel(char c){
boolean vowel = false;
char[] vowList = {'a','e','i','o','u'};
for (int i = 0; i < vowList.length; ++i) {
if (c == vowList[i]) {
vowel = true;
}
}
return vowel;
}
public static void print(String[] words){
String[] newArry = new String[words.length];
for (int i = 0; i < words.length; ++i) {
newArry[i] = words[i];
}
String finalPrint = Arrays.toString(translate(newArry));
finalPrint = finalPrint.replace("[", "");
finalPrint = finalPrint.replace(",", "");
finalPrint = finalPrint.replace("]", "");
System.out.println(finalPrint);
}
}
Here are some of the printed responses:
Input: the rain in spain stays mainly in the plain
Output: ethay ainray [Ljava.lang.String;#17c68925ay ainspay aysstay ainlymay [Ljava.lang.String;#17c68925ay ethay ainplay
Expected: ethay ainray inay ainspay aysstay ainlymay inay ethay ainplay
Input: you should have stayed with the soup question
OutPut: ouyay ouldshay avehay ayedstay ithway ethay oupsay uestionqay
This print's out correctly
Input: the stuff that dreams are made of
Output: ethay uffstay atthay eamsdray [Ljava.lang.String;#17c68925ay ademay [Ljava.lang.String;#17c68925ay
Expected: ethay uffstay atthay eamsdray areay ademay ofay
I cannot find an answer as to why this is happening. Please let me know if you need any additional information. Thanks!
You have a mistake (typo, likely) in this block:
if (isVowel(words[i].charAt(0)) == true){
pigLatin[i] = words + "ay";
}
It should be instead (note you don't need to compare boolean value with true):
if (isVowel(words[i].charAt(0))) {
pigLatin[i] = words[i] + "ay";
}
Also, you don't need to copy your array in print() method - translate() doesn't modify input array in any way.
Finally, instead of replacing the output of Arrays.toString, you could use String.join, so your print method would look like:
public static void print(String[] words){
System.out.println(String.join(" ", translate(words)));
}
pigLatin[i] = words + "ay";
This line. You are appending string to an array. Change it to:
pigLatin[i] = words[i] + "ay";
Side note 1:
for (int i = 0; i < words.length; ++i) {
newArry[i] = words[i];
}
This loop can be changed to:
System.arraycopy(words, 0, newArry, 0, words.length);
Side note 2:
Splitting on "\\s+" is better. It also takes care of multiple spaces.
Side note 3:
if (isVowel(words[i].charAt(0)) == true) {
This can be simplified as:
if (isVowel(words[i].charAt(0))) {
Side note 4:
for (char value : vowList) {
if (c == value) {
vowel = true;
break;
}
}
Using break for slightly better performance. Also, using foreach loop.
Final side note:
finalPrint = finalPrint.replace("[", "")
.replace(",", "")
.replace("]", "");
Chaining of replace calls.
I have to capitalize the first letter in every word passed into the string. My output is doing that capitalization, but it's not maintaining the format of the original output. For example, string input is "hello world", my output is "HelloWorld", and my desired output should be "Hello World."
I've tried to add spaces where I can throughout the code but nothing works. I think the problem is that when I use toCharArray, it gives me an output with no spaces? So my concatenation result is adding everything in one swoop, versus each word separately?
Or I thought that my code was using string concatenation with my result, and it's not being separated because I have both words going into the same variable.
import java.util.*;
import java.io.*;
class Main {
public static String LetterCapitalize(String str) {
// code goes here
String[] word = str.split(" ");
String result = "";
for(int i = 0; i < word.length; i++) {
char[] charWord = word[i].toCharArray();
for(int j = 0; j < charWord.length; j++ ) {
String cap = word[i].charAt(0) + "";
cap = cap.toUpperCase();
//System.out.print(" ");
result += (j == 0 ? cap : word[i].charAt(j));
}
}
return result;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterCapitalize(s.nextLine()));
}
}
No errors. Just not getting desired output.
When you did String[] word = str.split(" ");, the space between each word is taken out and you are now left with only the words in an array. You should use String.join(" ", word) on the resultant words array to reverse the effects so you get the spaces back.
Instead of going through each word char by char, try this:
for(int i = 0; i < word.length; i++) {
word[i] = word[i].substring(0, 1).toUpperCase() + word[i].substring(1);
}
result = String.join(" ", word);
Try this:
import java.util.*;
class Main {
public static String LetterCapitalize(String str) {
// code goes here
String[] word = str.split(" ");
String result = "";
for(int i = 0; i < word.length; i++) {
result += capitalize(word[i]) + (i != word.length - 1 ? " " : "");
}
return result;
}
private static String capitalize(String s){
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterCapitalize(s.nextLine()));
}
}
You can use the below code.
class Main {
public static String LetterCapitalize(String str) {
// code goes here
String[] word = str.split(" ");
StringBuilder result = new StringBuilder();
for (int i = 0; i < word.length; i++) {
char[] charWord = word[i].toCharArray();
for (int j = 0; j < charWord.length; j++) {
String cap = word[i].charAt(0) + "";
cap = cap.toUpperCase();
//System.out.print(" ");
result.append(j == 0 ? cap : word[i].charAt(j));
}
result.append(" ");
}
return result.toString();
}
public static void main(String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterCapitalize(s.nextLine()));
}
}
Hey guys this is my code for splitting the array first without using any inbuilt functions. It works fine, my question is in the second part.
static String[] split(String ss) {
String[] a = new String[1];
String s = "";
for (int i = 0; i < ss.length(); i++) {
if (ss.charAt(i) == ' ') {
s += ", "
} else {
s += ss.charAt(i);
}
for (int j = 0; j < a.length; j++) {
a[j] = "[" + s + "]";
}
}
return a;
}
I need now to count each letter in a word and give it out also without inbuilt functions as split, chartoarray and so on.
this is to what i came so far.
for example String="This is just an example". it should give out
This=4
is=2
..
static String[][] LettersCount(String[] array) {
int count=0;
String [][] a =new String[array.length][array.length];
String s= "" + Arrays.toString(array);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
count = 0;
} else {
count++;
}
You can use property of character that it has a numerical value after all. Lets use it as index and store the counts in an array. (so we will mimic Map this way)
int[] counter = new int[256] ;// this will hold count of all letters
counter[(int) character]++; // this is how you do the counting
public class JavaArrayLengthTest {
public static void main(String[] args) {
String[] testArray = { "A", "B", "C" };
int arrayLength = testArray.length;
System.out.println("The length of the array is: " + arrayLength);
}
}
I am new to Java and I found a interesting problem which I wanted to solve. I am trying to code a program that reverses the position of each word of a string. For example, the input string = "HERE AM I", the output string will be "I AM HERE". I have got into it, but it's not working out for me. Could anyone kindly point out the error, and how to fix it, because I am really curious to know what's going wrong. Thanks!
import java.util.Scanner;
public class Count{
static Scanner sc = new Scanner(System.in);
static String in = ""; static String ar[];
void accept(){
System.out.println("Enter the string: ");
in = sc.nextLine();
}
void intArray(int words){
ar = new String[words];
}
static int Words(String in){
in = in.trim(); //Rm space
int wc = 1;
char c;
for (int i = 0; i<in.length()-1;i++){
if (in.charAt(i)==' '&&in.charAt(i+1)!=' ') wc++;
}
return wc;
}
void generate(){
char c; String w = ""; int n = 0;
for (int i = 0; i<in.length(); i++){
c = in.charAt(i);
if (c!=' '){
w += c;
}
else {
ar[n] = w; n++;
}
}
}
void printOut(){
String finale = "";
for (int i = ar.length-1; i>=0;i--){
finale = finale + (ar[i]);
}
System.out.println("Reversed words: " + finale);
}
public static void main(String[] args){
Count a = new Count();
a.accept();
int words = Words(in);
a.intArray(words);
a.generate();
a.printOut();
}
}
Got it. Here is my code that implements split and reverse from scratch.
The split function is implemented through iterating through the string, and keeping track of start and end indexes. Once one of the indexes in the string is equivalent to a " ", the program sets the end index to the element behind the space, and adds the previous substring to an ArrayList, then creating a new start index to begin with.
Reverse is very straightforward - you simply iterate from the end of the string to the first element of the string.
Example:
Input: df gf sd
Output: sd gf df
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Count{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter string to reverse: ");
String unreversed = scan.nextLine();
System.out.println("Reversed String: " + reverse(unreversed));
}
public static String reverse(String unreversed)
{
ArrayList<String> parts = new ArrayList<String>();
String reversed = "";
int start = 0;
int end = 0;
for (int i = 0; i < unreversed.length(); i++)
{
if (unreversed.charAt(i) == ' ')
{
end = i;
parts.add(unreversed.substring(start, end));
start = i + 1;
}
}
parts.add(unreversed.substring(start, unreversed.length()));
for (int i = parts.size()-1; i >= 0; i--)
{
reversed += parts.get(i);
reversed += " ";
}
return reversed;
}
}
There is my suggestion :
String s = " HERE AM I ";
s = s.trim();
int j = s.length() - 1;
int index = 0;
StringBuilder builder = new StringBuilder();
for (int i = j; i >= 0; i--) {
Character c = s.charAt(i);
if (c.isWhitespace(c)) {
index = i;
String r = s.substring(index+1, j+1);
j = index - 1;
builder.append(r);
builder.append(" ");
}
}
String r=s.substring(0, index);
builder.append(r);
System.out.println(builder.toString());
From adding debug output between each method call it's easy to determine that you're successfully reading the input, counting the words, and initializing the array. That means that the problem is in generate().
Problem 1 in generate() (why "HERE" is duplicated in the output): after you add w to your array (when the word is complete) you don't reset w to "", meaning every word has the previous word(s) prepended to it. This is easily seen by adding debug output (or using a debugger) to print the state of ar and w each iteration of the loop.
Problem 2 in generate() (why "I" isn't in the output): there isn't a trailing space in the string, so the condition that adds a word to the array is never met for the last word before the loop terminates at the end of the string. The easy fix is to just add ar[n] = w; after the end of the loop to cover the last word.
I would use the split function and then print from the end of the list to the front.
String[] splitString = str.split(" ");
for(int i = splitString.length() - 1; i >= 0; i--){
System.out.print(splitString[i]);
if(i != 0) System.out.print(' ');
}
Oops read your comment. Disregard this if it is not what you want.
This has a function that does the same as split, but not the predefined split function
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string : ");
String input = sc.nextLine();
// This splits the string into array of words separated with " "
String arr[] = myOwnSplit(input.trim(), ' '); // ["I", "AM", "HERE"]
// This ll contain the reverse string
String rev = "";
// Reading the array from the back
for(int i = (arr.length - 1) ; i >= 0 ; i --) {
// putting the words into the reverse string with a space to it's end
rev += (arr[i] + " ");
}
// Getting rid of the last extra space
rev.trim();
System.out.println("The reverse of the given string is : " + rev);
}
// The is my own version of the split function
public static String[] myOwnSplit(String str, char regex) {
char[] arr = str.toCharArray();
ArrayList<String> spltedArrayList = new ArrayList<String>();
String word = "";
// splitting the string based on the regex and bulding an arraylist
for(int i = 0 ; i < arr.length ; i ++) {
char c = arr[i];
if(c == regex) {
spltedArrayList.add(word);
word = "";
} else {
word += c;
}
if(i == (arr.length - 1)) {
spltedArrayList.add(word);
}
}
String[] splitedArray = new String[spltedArrayList.size()];
// Converting the arraylist to string array
for(int i = 0 ; i < spltedArrayList.size() ; i++) {
splitedArray[i] = spltedArrayList.get(i);
}
return splitedArray;
}
The purpose of this program is to take information from a file about a music collection and turn it into three arrays.
>4
>141 Pure Heroine:Lorde
>171 Lights Out:Ingrid Michaelson
>270 Unorthodox Jukebox :Bruno Mars
>190 Head Or Heart:Christina Perri
In the file, the 4 stands for how long the arrays will be, the numbers are one array, the album titles another, and the artist names are the final array. The arrays for the titles and artist names are separated by the colon. While I can create the array for the numbers, what is giving me trouble is how to create the separate arrays for name and titles. I understand that I have to convert it into a sting and use the colon as a delimiter but I'm unsure as to how.
import java.util.*;
import java.io.*;
public class tunes {
public static void main(String[] args) throws FileNotFoundException {
int size; //Determines the size of the arrays
Scanner input = new Scanner(new File("music.txt"));
size = input.nextInt();
int[] time = new int[size];
for (int i = 0; i < time.length; i++) { // Creates an array for the numbers
time[i] = input.nextInt();
input.nextLine();
}
String[] artist = new String[size];
for (int i = 0; i <artist.length; i++) {
while (input.hasNextLine()){
}
}
System.out.println();
System.out.println("TOTAL TIME\t\t\t\t" + calcTotalTime(time));
System.out.println();
System.out.println();
System.out.println("LONGEST TRACK");
System.out.println("-------------");
System.out.println();
System.out.println();
System.out.println("SHORTEST TRACK");
System.out.println("--------------");
}
public static void printTable(int[] time, String[] artist, String[] title) {
System.out.println("TITLE\t\t\t" + "ARTIST\t\t\t " + "TIME");
System.out.println("-----\t\t\t" + "------\t\t\t " + "----");
for (int i = 0; i < time.length; i++) {
System.out.println(title[i] + "\t" + artist[i] + "\t" + time[i]);
}
}
public static int calcTotalTime(int[] time) {
int sum = 0;
for (int i = 0; i < time.length; i++) {
sum = sum + time[i];
}
return sum;
}
public static int findLongest(int[] time) {
int longest = 0;
for (int i = 1; i < time.length; i++) {
if (time[i] > time[longest]) {
longest = i;
}
}
return longest;
}
public static int findShortest(int[] time) {
int shortest = 0;
for (int i = 1; i < time.length; i++) {
if (time[i] < time[shortest]) {
shortest = i;
}
}
return shortest;
}
}
An example of how the output would look like would be
>Pure Heroine Lorde 141
>Lights Out Ingrid Michaelson 171
>Unorthodox Jukebox Bruno Mars 270
>Head or Heart Christina Perri 190
You can use String.split(":") on your text to split the artist/title Strings into String[] arrays.
For instance:
System.out.println(Arrays.toString("Head Or Heart:Christina Perri".split(":")));
Output
[Head Or Heart, Christina Perri]
Use the String split() method to save the pieces into a new array. The split() method takes a regular expression - see this question about how to use it. The colon is not a special character in a RegExp and therefore does not need to be escaped.
Allocate all the arrays first after reading the length of the arrays, then parse each line in one go using split to tokenize the artist-title part of the line.
size = input.nextInt();
int[] time = new int[size];
String[] artist = new String[size];
String[] title = new String[size];
for (int i = 0; i < time.length; i++) {
time[i] = input.nextInt();
String[] parts = input.next().split( ":" );
artist[i] = parts[0];
title[i] = parts[1];
}