I created a method to output a String. Using the split method and a for loop, I added each word in my sentence into a String array, replacxing the last two letters of each word with "ed". Now, my return statement should return each of the words. When I used System.out.print, it worked. When I use a return and call it in my main method, I get this output: "[Ljava.lang.String;#1b6235b"
The error seems so simple but I just don't know where I'm going worng. Any help would be appreciated.
Here is my method:
public String[] processInfo() {
String sentence = this.phrase;
String[] words = sentence.split(" ");
if (!this.phrase.equalsIgnoreCase("Fred")) {
for (int i = 0; i < words.length; i++) {
words[i] = words[i].substring(0, words[i].length() - 2).concat(
"ed ");
// System.out.print(words[i]);
}
}
return words;
}
You are printing arrays but arrays don't have a proper implementation of toString() method by default.
What you see is
"[Ljava.lang.String;#1b6235b"
This is [Ljava.lang.String; is the name for String[].class, the java.lang.Class representing the class of array of String followed by its hashCode.
In order to print the array you should use Arrays.toString(..)
System.out.println(Arrays.toString(myArray));
A good idea however, it returns my Strings in an Array format. My aim
is to return them back into sentence format. So for example, if my
input is, "Hey my name is Fred", it would output as, "Hed ed naed ed
Fred". Sorry, I forgot to add that it also seperates it with commas
when using Arrays.toString
Then you should modify your processInfo() returning a String or creating a new method that convert your String[] to a String.
Example :
//you use like this
String [] processInfoArray = processInfo();
System.out.println(myToString(processInfoArray));
// and in another part you code something like this
public static String myToString(String[] array){
if(array == null || array.length == 0)
return "";
StringBuilder sb = new StringBuilder();
for(int i=0;i<array.length-1;i++){
sb.append(array[i]).append(" ");
}
return sb.append(array[array.length -1]).toString();
}
As much as I can get from your question and comment is that your aim is to return them back into sentence format. So for example, if your input is, "Hey my name is Fred", it would output as, "Hed ed naed ed Fred".
In that case you should return a String, and not an array. I have modified your method a bit to do so. Let me know if you wanted something else.
public String processInfo() {
String sentence = this.phrase;
String[] words = sentence.split(" ");
if (!this.phrase.equalsIgnoreCase("Fred")) {
sentence = "";
for (int i = 0; i < words.length; i++) {
words[i] = words[i].substring(0, words[i].length() - 2).concat(
"ed ");
sentence += " " + words[i];
// System.out.print(words[i]);
}
}
return sentence.trim();
}
Your commented out call to System.out.print is printing each element of the array from inside the loop. Your method is returning a String[]. When you try to print an array, you will get the java representation of the array as you are seeing. You either need to change your method to build and return a string with all the array entries concatenated together, or your calling code needs to loop through the returned array and print each entry.
Related
What I want to do is create a method that takes two objects as input
of type String. The method will return logical truth if both strings are the same (word spacing and capitalization do not matter). I thought to split String, make an Array of elements, add each element to List and then compare each element to space and remove it from List. At the end use a compareToIgnoreCase() method. I stopped on removing space from List for string2. It works to string1List and doesn't work to string2List, I'm wondering why?? :(
I will be grateful for help, I spend a lot of time on it and I'm stuck. Maybe someone know a better solution.
import java.util.ArrayList;
import java.util.List;
public class Strings {
public static void main(String[] args) {
String string1 = "This is a first string";
String string2 = "this is a first string";
String[] arrayOfString1 = string1.split("");
List<String> string1List = new ArrayList<>();
for (int i = 0; i < arrayOfString1.length; ++i) {
string1List.add(arrayOfString1[0 + i]);
}
String[] arrayOfString2 = string2.split("");
List<String> string2List = new ArrayList<>();
for (int i = 0; i < arrayOfString2.length; ++i) {
string2List.add(arrayOfString2[0 + i]);
}
for (int i = 0; i < string1List.size(); ++i) {
String character = string1List.get(0 + i);
if (character.equals(" ")) {
string1List.remove(character);
}
}
for (int i = 0; i < string2List.size(); ++i) {
String character = string2List.get(0 + i);
if (character.equals(" ")) {
string2List.remove(character);
}
}
System.out.println(string2List.size());
}
}
You can try below solution. As you mentioned word spacing and capitalization do not matter
1.remove capitalization - using toLowercase()
2.for word spacing - remove all word spacing using removeAll() with regex pattern "\\s+" so it removes all spaces.
3. check both strings now.
public class StringChecker {
public static void main(String[] args) {
System.out.println(checkString("This is a first string", "this is a first string"));
}
public static boolean checkString(String string1, String string2){
String processedStr1 = string1.toLowerCase().replaceAll("\\s+", "");
String processedStr2 = string2.toLowerCase().replaceAll("\\s+", "");
System.out.println(" s1 : " + processedStr1);
System.out.println(" s2 : " + processedStr2);
return processedStr1.equals(processedStr2);
}
}
Your problem has nothing to do with spaces. You can replace them with any other character (for example "a") to test this. Therefore, removing spaces in any of the methods given above will not improve your code.
The source of the problem is iterating the list with the for command. When you remove an item from a list inside the for loop, after removing the i-th element, the next element in the list becomes the i-th current element.
On the next repetition of the loop - when i is incremented by one - the current i + 1 item becomes the next item in the list, and thus you "lose" (at least) one item. Therefore, it is a bad idea to iterate through the list with the for command.
However you may use many other methods available for collections - for instance Iterators - and your program will work fine.
Iterator <String> it = string1List.iterator();
while(it.hasNext())
{
if(it.next().equals("a")) it.remove();
}
Of course there is no need at all to use Lists to compare these two strings.
String offensive_words[] = {<offensive words>};
String userinput = input.next();
for (int i = 0; i < offensive_words.length; i++) {
if (userinput.contains(offensive_words[i]) {
System.out.println("Please dont use the " + userinput);
}
}
Am trying to check firstly if user input contains an offensive word listed in my array of offensive word. Then if user input contains such words listed in the array, then print a message saying(Please don't use the ).
You got a user input. This is a String. You can use String.contains(offensiveWord) to check if this string contains given string. You can just create a for-each loop which will iterate through your list of offensive words and do something if user input contains them.
Also, you can String.split() your input and then (in a double for loop) check if String.equalsIgnoreCase(offensiveWord) returns true.
Sample code for you :
public static boolean contains(String input, String[] ows) {
for (String ow : ows) {
if (input.contains(ow)) return true;
}
return false;
}
I have to be able to input any two words as a string. Invoke a method that takes that string and returns the first word. Lastly display that word.
The method has to be a for loop method. I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
How can I make it so that no matter what phrase I use for the string, it will always return the first word? And please explain what you do, because this is my first year in a CS class. Thank you!
I have to be able to input any two words as a string
The zero, one, infinity design rule says there is no such thing as two. Lets design it to work with any number of words.
String words = "One two many lots"; // This will be our input
and then invoke and display the first word returned from the method,
So we need a method that takes a String and returns a String.
// Method that returns the first word
public static String firstWord(String input) {
return input.split(" ")[0]; // Create array of words and return the 0th word
}
static lets us call it from main without needing to create instances of anything. public lets us call it from another class if we want.
.split(" ") creates an array of Strings delimited at every space.
[0] indexes into that array and gives the first word since arrays in java are zero indexed (they start counting at 0).
and the method has to be a for loop method
Ah crap, then we have to do it the hard way.
// Method that returns the first word
public static String firstWord(String input) {
String result = ""; // Return empty string if no space found
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break; // because we're done
}
}
return result;
}
I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
There it is, using those methods you mentioned and the for loop. What more could you want?
But how can I make it so that no matter what phrase I use for the string, it will always return the first word?
Man you're picky :) OK fine:
// Method that returns the first word
public static String firstWord(String input) {
String result = input; // if no space found later, input is the first word
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break;
}
}
return result;
}
Put it all together it looks like this:
public class FirstWord {
public static void main(String[] args) throws Exception
{
String words = "One two many lots"; // This will be our input
System.out.println(firstWord(words));
}
// Method that returns the first word
public static String firstWord(String input) {
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
return input.substring(0, i);
}
}
return input;
}
}
And it prints this:
One
Hey wait, you changed the firstWord method there.
Yeah I did. This style avoids the need for a result string. Multiple returns are frowned on by old programmers that never got used to garbage collected languages or using finally. They want one place to clean up their resources but this is java so we don't care. Which style you should use depends on your instructor.
And please explain what you do, because this is my first year in a CS class. Thank you!
What do I do? I post awesome! :)
Hope it helps.
String line = "Hello my name is...";
int spaceIndex = line.indexOf(" ");
String firstWord = line.subString(0, spaceIndex);
So, you can think of line as an array of chars. Therefore, line.indexOf(" ") gets the index of the space in the line variable. Then, the substring part uses that information to get all of the characters leading up to spaceIndex. So, if space index is 5, it will the substring method will return the indexes of 0,1,2,3,4. This is therefore going to return your first word.
The first word is probably the substring that comes before the first space. So write:
int x = input.indexOf(" ");
But what if there is no space? x will be equal to -1, so you'll need to adjust it to the very end of the input:
if (x==-1) { x = input.length(); }
Then use that in your substring method, just as you were planning. Now you just have to handle the case where input is the blank string "", since there is no first word in that case.
Since you did not specify the order and what you consider as a word, I'll assume that you want to check in given sentence, until the first space.
Simply do
int indexOfSpace = sentence.indexOf(" ");
firstWord = indexOfSpace == -1 ? sentence : sentence.substring(0, indexOfSpace);
Note that this will give an IndexOutOfBoundException if there is no space in the sentence.
An alternative would be
String sentences[] = sentence.split(" ");
String firstWord = sentence[0];
Of if you really need a loop,
String firstWord = sentence;
for(int i = 0; i < sentence.length(); i++)
{
if(sentence.charAt(i) == ' ')
{
sentence = firstWord.substring(0, i);
break;
}
}
You may get the position of the 'space' character in the input string using String.indexOf(String str) which returns the index of the first occurrence of the string in passed to the method.
E.g.:
int spaceIndex = input.indexOf(" ");
String firstWord = input.substring(0, spaceIndex);
Maybe this can help you figure out the solution to your problem. Most users on this site don't like doing homework for students, before you ask a question, make sure to go over your ISC book examples. They're really helpful.
String Str = new String("Welcome to Stackoverflow");
System.out.print("Return Value :" );
System.out.println(Str.substring(5) );
System.out.print("Return Value :" );
System.out.println(Str.substring(5, 10) );
I have an assignment where I'm supposed to have a method that formats an array of String objects to be tabulated a certain way with a header, and put all the objects (after being formatted) nicely into a single String for the method to return. This method is inside an object class, so it ultimately will be formatting multiple objects the same way, so I need it to format the same way with various String lengths.
Here's what I need the output to look like:
Hashtags:
#firstHashtag
#secondHashtag
Each hashtag is in a String[] of hashtags,
i.e.
String[] hashtags = ["#firstHashtag", "#secondHashtag"]
So basically I need to use string.format() to create on single string containing a tabbed "Hashtags:" header, and then each String in the "hashtags" array to be on a new line, and double-tabbed. The size of the "hashtag" array changes since it is in an object class.
Could someone help me use String.formatter?
This is what my method looks like so far:
public String getHashtags()
{
String returnString = "Hashtags:";
String add;
int count = 0;
while(count < hashtags.length)
{
//hashtags is an array of String objects with an unknown size
returnString += "\n";
add = String.format("%-25s", hashtags[count]);
//here I'm trying to use .format, but it doesn't tabulate, and I
//don't understand how to make it tabulate!!
count++;
returnString = returnString + add;
}
if(hashtags == null)
{
returnString = null;
}
return returnString;
}
Any helpful advice on what to do here with formatting would be greatly appreciated!!!
If you are trying to use real tabs and not spaces, then just change your program to be like this one:
public String getHashtags()
{
if(hashtags == null)
{
return null;
}
String returnString = "Hashtags:";
int count = 0;
while(count < hashtags.length)
{
//hashtags is an array of String objects with an unknown size
returnString = returnString + "\n\t\t"+hashtags[count];
count++;
}
return returnString;
}
Your String.format() statement will create a String that is left-justified and padded to 25 spaces. For example, this line:
System.out.println("left-justified >" + String.format("%-25s", "hello") + "<");
outputs:
left-justified >hello <
The other thing is that you're not really using tabs (I don't see the tab character in your program). String.format() is creating Strings that are length 25 and left-justified. Keep that in mind as you create the return string. Also, your loop as adding a newline character each time. That's why you're getting multi-line output.
I am creating a program that lets you store 10 items in an array. What I haven't been able to get the program to do is give an error if one of the entered items already exists in the array.
So, for example, if the array looks like [banana, potato, 3, 4, yes, ...] and I enter banana again, it should say "Item has already been stored" and ask me to re-enter the value. The code I currently have is:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int stringNumber = 0;
String[] stringArray = new String[10];
for (int i = 0; i <= stringArray.length; i++) {
out.println("\nEnter a string");
String input = keyboard.next();
stringArray[stringNumber] = input;
out.println("\"" + stringArray[stringNumber] + "\"" + " has been stored.");
PrintArray(stringArray);
stringNumber++;
You can use nested loops to go through the array to see if the new input exists. It would be better to do this in a function. Also when doing this you need to make sure that you are not at the first element or you will get a null pointer exception.
for (int i = 0; i <= stringArray.length; i++) {
boolean isInArray = false;
System.out.println("\nEnter a string");
String input = keyboard.next();
if (i > 0) {
for (int j = 0; j < stringArray.length; j++) {
if (stringArray[j].equalsIgnoreCase(input)) {
isInArray = true;
break;
}
}
}
if (!isInArray) {
stringArray[stringNumber] = input;
} else {
System.out.println("\"" + stringArray[stringNumber-1] + "\""
+ " has been stored.");
}
PrintArray(stringArray);
stringNumber++;
}
It's always better to use a HashSet when you don't want to store duplicates. Then use HashSet#contains() method to check if element is already there. If ordering is important, then use LinkedHashSet.
If you really want to use an array, you can write a utility method contains() for an array. Pass the array, and the value to search for.
public static boolean contains(String[] array, String value) {
// Iterate over the array using for loop
// For each string, check if it equals to value.
// Return true, if it is equal, else continue iteration
// After the iteration ends, directly return false.
}
For iterating over the array, check enhanced for statement.
For comparing String, use String#equals(Object) method.
When you got the String input, you can create a method that will :
Go through the entire array and check if the string is in it (you can use equals() to check content of Strings)
Returns a boolean value wheter the string is in the array or not
Then just add a while structure to re-ask for an input
Basically it can look like this :
String input = "";
do {
input = keyboard.next();
}while(!checkString(input))
The checkString method will just go through all the array(using a for loop as you did to add elements) and returns the appropriate boolean value.
Without introducing some order in your array and without using an addition structure for instance HashSet, you will have to look through the whole array and compare the new item to each of the items already present in the array.
For me the best solution is to have a helper HashSet to check the item for presence.
Also have a look at this question.
To avoid you should use an Set instead of an array and loop until size = 10.
If you need to keep an array, you can use the .contains() method to check if the item is already present in the array.
while (no input or duplicated){
ask for a new string
if (not duplicated) {
store the string in the array
break;
}
}
You should check the input value in array before inserting into it. You can write a method like exists which accepts String[] & String as input parameter, and find the string into the String array, if it finds the result then return true else false.
public boolean exists(String[] strs, String search){
for(String str : strs){
if(str.equals(search))
return true;
}
return false;
}
performance would be O(n) as it searchs linearly.