I have a trouble with the for loop method that only loop 1 times whats is the problem? In the array was no problem at all, it able to print the value I want to.
here is my code:
public static void main(String[] args){
String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
String[] word = s.split(",");
StringBuffer str = new StringBuffer();
Integer total = 0;
for (int y = 0; y < word.length; y++){
if(word[y].toString().equals("Apple2") ){
total++;
//str.append(word[y].toString());
}else if(word[y].toString().equals("Apple3") ){
total++;
//str.append(word[y].toString());
}else if(word[y].toString().equals("Apple4") ){
total++;
//str.append(word[y].toString());
}
else if(word[y].toString().equals("Apple1") ){
total++;
//str.append(word[y].toString());
}
}
System.out.println( word[0] + word[1] + word[2] + word[3] + word[4] + word.length);
System.out.println(str + "hihi" + total);
}
The others have nailed the cause of your problem. However, the fix they suggest is rather too specific ... and fragile. (Splitting with split("\\s*,\\s*") is better but it won't cope with whitespace at the start / end of the entire string.)
I suggest that you continue to use split(","), but trim the words before testing; e.g.
for (int y = 0; y < word.length; y++) {
String trimmed = word[y].trim();
if (trimmed.equals("Apple2")) {
total++;
//str.append(trimmed.toString());
} else if (trimmed.equals("Apple3")) {
// etcetera
or better still:
String[] words = s.split(",");
for (String word : words) {
String trimmed = word.trim();
if (trimmed.equals("Apple2")) {
total++;
//str.append(trimmed.toString());
} else if (trimmed.equals("Apple3")) {
// etcetera
That will make your code work irrespective of the whitespace characters around the commas and at the start and end of the string. Robustness is good, especially if it costs next to nothing to implement.
Finally, you could even replace the if / else if / ... stuff with a Java 7 String switch statement.
Try splitting on ", " (with space)
String[] word = s.split(", ");
without that space in split word[1] would look like " Apple1" instead "Apple1"
Other option would be calling word[y].trim().equals("Apple2") to get rid of that additional space, but I would say including it in split is better. If you aren't sure how many white-spaces can be near comma you can split this way split("\\s*,\\s*") to include all white-spaces around comma.
Also as Matt Ball pointed in his comment you don't need to call toString() on word[y] since it is already String.
you ignore the space during split. String[] word = s.split(", ");
You'are split by "," but your String contains ", ".
You can change the s.split(","); to s.split(", ");
Or trim the split's result like this :
public static void main(String[] args) {
String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
String[] word = s.split(",");
StringBuffer str = new StringBuffer();
Integer total = 0;
for (int y = 0; y < word.length; y++) {
if (word[y].trim().equals("Apple2")) {
total++;
// str.append(word[y].toString());
} else if (word[y].trim().equals("Apple3")) {
total++;
// str.append(word[y].toString());
} else if (word[y].trim().equals("Apple4")) {
total++;
// str.append(word[y].toString());
} else if (word[y].trim().equals("Apple1")) {
total++;
// str.append(word[y].toString());
}
}
System.out.println(word[0] + word[1] + word[2] + word[3] + word[4]
+ word.length);
System.out.println(str + "hihi" + total);
}
There is nothing wrong with your code but the problem lies in the String that you are giving to the variable.
String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
Here the string contains spaces between them after the comma. So that when you split your string it splits like
word[0]= "Apple0"
word[1]= " Apple1"
word[2]= " Apple2"
word[3]= " Apple3"
and so on.
So that when you compare like
word[y].equals("Apple1") it returns false because " Apple1" and "Apple1" are two different strings. So that initialize your string like this
String s = "Apple0,Apple1,Apple2,Apple3,Apple4"; // without white spaces
It will work fine. Or you can use trim method in your existing code without changing String like
word[y].trim().equals("Apple1") //It will trim all the leading and trailing white spaces.
Hope this helps.
Related
There are functions available for multiple spaces to single space, but I want to add more spaces where single spaces are there.
I tried this:
int rem = b - temp.length();
for(int k = 0; k < rem; k++) {
temp.replace(" ", " ");
}
I want to add that much space between words as predefined length of string.
You only need to invoke temp.replace(" "," "); once (i.e. instead of looping) to replace all single spaces with two consecutive spaces.
However, since Strings are immutable, you need to assign temp with the outcome of your replace invocation.
temp = temp.replace(" "," ");
I will suggest you a combination of String.trim Method and REGEX
EXAMPLE:
public static void main(String[] args) {
String temp = "Is you see this is because ";
String replacedString = temp.trim().replaceAll(" +", " ");
System.out.println(temp);
System.out.println(replacedString);
}
this will correct the temp String to
Is you see this is because
I have the following code that takes 2 strings as inputs and returns Boolean on whether they're anagrams:
import java.util.ArrayList;
import java.util.Scanner;
public class AnagramChecker {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print ("Enter string 1: ");
String str1 = sc.nextLine();
System.out.print ("Enter string 2: ");
String str2 = sc.nextLine();
boolean check = isAnagram (str1, str2);
System.out.println ("Anagram check for '" + str1 + "' and '" + str2 + "': " + check);
sc.close();
}
public static boolean isAnagram (String s1, String s2) {
if(s1.length() != s2.length())
return false;
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
ArrayList<String> myList = new ArrayList<String>();
for(int i = 0; i < s2.length() ; i++ ){
myList.add(String.valueOf(s2.charAt(i)));
}
for(int i = 0; i < s1.length();i++){
for(int j = 0; j < myList.size(); j++){
if(myList.get(j).equals(String.valueOf(s1.charAt(i)))){
myList.remove(j);
j = 0;
break;
}
}
}
return myList.isEmpty();
}
}
It is somewhat limited though, I'm trying to expand it to work for the following cases:
- different cases i.e. eager == AGREE
- single word with whitespaces i.e. eager == a g ree
- different amounts of whitespace i.e. " eager" == agree
Is there a nice and clean way to integrate this into already written code above without much pain and re-writing. Any help much appreciated. Thanks.
Yes there is. Regex to the rescue! You can use the String built in .replaceAll(). Passing it the \s value will remove all spaces and characters not printed such as \n. I would suggest that during comparison you use something like the following:
string1.replaceAll("\\s","").equals(string2.replaceAll("\\s",""));
personally I would do the following
use trim() to remove leading and traiing whitespace
use replace to remove whitespaces
use toLowerCase() to make the text lower case
convert the Strings into an array list of characters
sort the arrays
compare the arrays - if they are the same then you have an anagram
I'm trying to slice a string for the first time.
With this code, if I input, for example 'one two three' it works fine until the last word.
This is the last few lines of the output:
Current word is thr
Sentence is now e
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.substring(String.java:1907)
at TestCurr.main(testCurrentWord.java:18)
Has anyone any idea why it does that to the last word?
class TestCurr
{
public static void main (String []args)
{
String s;
int i;
String currentWord;
int length;
int spacePos;
System.out.println("Enter a sentence ");
s = EasyIn.getString();
spacePos = s.indexOf(" ");
length = s.length();
for (i = length -1; i >= 0; i--)
{
currentWord = s.substring(0,spacePos);
s = s.substring(spacePos +1);
System.out.println("Current word is " + currentWord);
System.out.println("Sentence is now " + s);
}
}
}
First of all, you call
spacePos = s.indexOf(" ");
length = s.length();
only once, but these values should change with each iteration of the loop. Furthermore,
s.substring(spacePos +1);
with
spacePos == s.length()-1
means you are passing an index beyond the end of the string as the start index for substring(). Once you fix the first error, this will be your next exception.
Your problem is that you only get the index of the space once. This causes the program to cut the string every three characters, as the first word is three letters long. You need to update spacePos after each iteration.
I believe your problem is in your usage of your spacePos variable.
Outside the loop, you initialize the variable like so:
spacePos = s.indexOf(" ");
Which in your example string of "one two three", yields 3.
But then inside your loop, you never set the variable again, based on what whatever is left that you haven't processed.
Try re-calculating spacePos's value inside the loop and your problem should go away.
Your current approach is too error prone.
And you have too many variables.
Try this just as an idea.
class TestCurr {
public static void main(String[] args) {
String s = null;
System.out.println("Enter a sentence: ");
s = " one two three ";
System.out.println("|" + s + "|");
int i = 0;
int j = 0;
while (true){
while (i<s.length() && s.charAt(i)==' ') i++;
j = i;
if (i>=s.length()) break;
while (i<s.length() && s.charAt(i)!=' ') i++;
System.out.println("Current word is: [" + s.substring(j, i)+ "]");
System.out.println("Sentence is now: [" + s.substring(i) + "]");
if (i>=s.length()) break;
}
}
}
As others have stated, you only get the index once. But I'm curious, why re-invent the wheel?
String s = "one two three";
String[] split = s.split(" ");
for (String out : split) {
System.out.println("Word: " + out);
}
I have to find the last word in a string and can't understand why my code isn't working. This is what I have:
int i, length;
String j, lastWord;
String word = "We the people of the United States in order to form a more perfect union";
length = word.length();
for (i = length - 1; i > 0; i--)
{
j = word.substring(i, i + 1);
if (j.equals(" ") == true);
{
lastWord = word.substring(i);
System.out.println("Last word: " + lastWord);
i = -1; //to stop the loop
}
}
However, when I run it, it prints the last letter. I know I could use
String lastWord = word.substring(word.lastIndexOf(" ") + 1)
But I'm pretty sure my teacher doesn't want me to do it this way. Any help?
You need to remove the ; after the if to make it work:
if (j.equals(" ")) // <== No semicolon, and no == true
{
lastWord = word.substring(i);
System.out.println("Last word: " + lastWord);
i = -1; //to stop the loop
}
You do not need == true for booleans inside control statements, either.
Finally, making single-character substrings is more expensive than using single characters. Consider using charAt(i) instead:
if (word.charAt(i) == ' ') // Single quotes mean one character
{
lastWord = word.substring(i+1);
System.out.println("Last word: " + lastWord);
break; // there is a better way to stop the loop
}
You've terminated the if statement. It should be,
if(j.equals(" "))
{
...
}
Just take that ; from if (j.equals(" ") == true); out.
Your code remade cleaner:
String word = "We the people of the United States in order to form a more perfect union";
for (int i = word.length() - 1; i > 0; i--)
if (word.charAt(i - 1) == ' ') {
System.out.println("Last word: " + word.substring(i));
break; // To stop the loop
}
Minimum iterations.
Convert the string to char array and look for space from the end of array. Don't forget to remove white spaces from the end using trim() as they could be counted as separate words.
s = s.trim();
char[] c = s.toCharArray();
for(int i=0; i<c.length; i++)
{
if(c[c.length-1-i]==' ')
{
return s.substring(c.length-1-i);
}
}
return s;
This also covers the null string case.
Another alternative using split.
s = s.trim();
String[] strs = new s.split(' ');
return str[str.length-1];
The semicolon after your "if" statement means "do nothing." Also, the "== true" is redundant. Lastly, you don't want to include the space you just found. Try this:
for (i = length - 1; i > 0; i--)
{
j = word.substring(i, i + 1);
if (j.equals(" "))
{
lastWord = word.substring(i + 1);
System.out.println("Last word: " + lastWord);
i = -1; //to stop the loop
}
}
There's a method for strings to split up at http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split%28java.lang.String%29
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
A good, fast and easier way would be:
word = word.split(" ")[word.length-1];
split() returns an array of substrings based on " ". Since an array starts with 0, its last element is the length of the array - 1.
The output is always a String, for example H,E,L,L,O,. How could I limit the commas? I want the commas only between letters, for example H,E,L,L,O.
import java.util.Scanner;
import java.lang.String;
public class forLoop
{
public static void main(String[] args)
{
Scanner Scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String Str1 = Scan.next();
String newString="";
String Str2 ="";
for (int i=0; i < Str1.length(); i++)
{
newString = Str1.charAt(i) + ",";
Str2 = Str2 + newString;
}
System.out.print(Str2);
}
}
Since this is homework I'll help you out a little without giving the answer:
If you want the output to only be inbetween letters IE: A,B,C instead of A,B,C, which is what I imagine you are asking about. Then you need to look at your for loop and check the boundary conditions.
The easiest way I see is :
public static void main(String[] args) {
Scanner Scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String Str1 = Scan.nextLine();
String newString="";
String Str2 ="";
for (int i=0; i < Str1.length()-1; i++)
{
newString = Str1.charAt(i) + ",";
Str2 = Str2 + newString;
}
Str2 = Str2 + Str1.charAt(Str1.length()-1);
System.out.println(Str2);
}
The output it will give is :
run:
Enter a string: Hello world
H,e,l,l,o, ,w,o,r,l,d
BUILD SUCCESSFUL (total time: 5 seconds)
Though I will highly recommend learning regular expression as suggested by #Roman. Till then this will do the trick. :)
Try regular expressions:
String input = scanner.next();
String output = input.replaceAll(".", "$0,");
With spaces it would be a bit easier since you don't need to abandon last 'odd' comma:
output = output.substring (0, ouput.length() - 2);
When you've figured out the loop-solution, you could try the following ;)
System.out.println(Arrays.toString("HELLO".toCharArray()).replaceAll("[\\[ \\]]", ""));
Just don't append the comma when the last item of the loop is to be appended. You have the item index by i and the string length by Str2.length(). Just do the primary school math with a lesser-than or a greater-than operator in an if statement.
The following snippet should be instructive. It shows:
How to use StringBuilder for building strings
How to process each char in a String using an explicit index
How to detect if it's the first/last iteration for special processing
String s = "HELLO";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (i == 0) { // first
sb.append("(" + ch + ")");
} else if (i == s.length() - 1) { // last
sb.append("<" + ch + ">");
} else { // everything in between
sb.append(Character.toLowerCase(ch));
}
}
System.out.println(sb.toString());
// prints "(H)ell<O>"