using split on Array Object in Java - java

Why do I get mssg with "cannot find symbol", when I use .split on the String Object?
public static void main(String[] args) {
String[] inputFile = StdIn.readAllLines().split("\\n");
//create Congress caracteristics
int states = Integer.parseInt(inputFile[0]); // read states value and save in the first
//position in the array
int totalSeats = Integer.parseInt(inputFile[1]); //read number of seats and save in the second
//position in the array

This is because you are trying to call the split method on an array. There is no such method on an array. readAllLines() already returns an array of the strings. Just remove the .split() call.
From the JavaDoc:
static String[] readAllLines()
Reads all remaining lines from standard input and returns them as an array of strings.

StdIn.readAllLines() does not return a String but a String[] (array of strings). You can't use split() on an array of strings.
Actually, you don't need to do that, because calling readAllLines() already gives you the array you are looking for.

You are most likely calling #split() in an Array/Collection of Strings, not a String. You should iterate though them and split one after the other.

We have fileName Object we itrate it a split it simple in this program i split my object with (.) so thats why i used this =split("\\.");
String[] fileName="we have a object here to we want to splite it ";
for(String obj:FileName)
{
String[] part1=obj.split("\\.");
}
System.out.println(part1);
check it its working fine

Related

String in Java : charAt Function use

Reversing a string can be done by concatenating the Original String through a reverse loop (from str.length-1->0)
but why is this not Working Correctly :
by adding the character by character from last positon to the 0th position:
int i = 0;
while(i<originalStr.length())
{
strRev.charAt(i)=originalStr.charAt(str.length()-1-i);
i++;
}
Strings are immutable in Java. You cannot edit them.
If you want to reverse a String for training purpose, you can create a char[], manipulate it then instantiate a String from the char[].
If you want to reverse a String for professional purpose, you can do it like this :
String reverse = new StringBuilder(originalStr).reverse().toString();
strRev.charAt(i) // use to Retrieve what value at Index. Not to Set the Character to the Index.
All we know that String is a immutable class in Java. Each time if you try to modify any String Object it will Create a new one.
eg :- String abc = "Vikrant"; //Create a String Object with "Vikrant"
abc += "Kashyap"; //Create again a new String Object with "VikrantKashyap"
// and refer to abc again to the new Object.
//"Vikrant" Will Removed by gc after executing this statement.
Better to Use StringBuffer or StringBuilder to perform reverse Operation. The only Difference between these two class is
A) StringBuffer is a Thread Safe (Synchronized). A little slow because each time need to check Thread Lock.
B) StringBuider is not Thread Safe. So, It gives you much faster Result Because it is Not Synchronized.
There are Several Third Party Jars which provides you a Features like Reverse and Many more String base Manipulation Methods
import org.apache.commons.lang.StringUtils; //Import Statement
String reversed = StringUtils.reverse(words);
In your test method, best practice is to use triple A pattern:
Arrange all necessary preconditions and inputs.
Act on the object or method under test.
Assert that the expected results have occurred.
#Test
public void test() {
String input = "abc";
String result = Util.reverse(input);
assertEquals("cba", result);
}

Put String[] in a String[][]?

Ok, soo what I'm trying to do, I have an oject with a attribut which looks like String[][], and I want to fill this one by calling a function and fill this String[][], one by one.
So here is what I tried but I get an error telling me :
"The type of the expression must be an array type but it resolved to String"
When I try to do
Produit[NbrProduit][0] = Produit[0];
My code :
public String[][] Produit = new String[MAX_Produit][2];
public void GetInfo1(String Client, String[] Produit,int NbrProduit){
Produit[NbrProduit][0] = Produit[0];
Produit[NbrProduit][1] = Produit[1];
Produit[NbrProduit][2] = Produit[2];
I don't understand why I get this because I'm filling a String field with an another String, right ? no ?
Sorry for my english.
Your parameter name (a 1D array) is the same as your instance variable name (a 2D array), so you're actually referring to your parameter only. Either use a different name (recommended), or use this.Produit when referring to your 2D array.
i.e.
public void GetInfo1(String Client, String[] produitParam,int NbrProduit){
Produit[NbrProduit][0] = produitParam[0];
Produit[NbrProduit][1] = produitParam[1];
Produit[NbrProduit][2] = produitParam[2];
Produit is a two dimensional String array, which means each of its element will be a string array. So you need to assign the element with the array of String and not just one String. Try this if it makes sense for your logic:
this.Produit[NbrProduit][0] = Produi;

Converting an array list to a single string

I am working on a section of code for an assignment I am doing atm, and I am completely stuck with 1 little bit.
I need to convert the contents of an array list into a string, or the form of a string, which will be able to be imput into toString() in order for it to be printed to the screen.
public String toString(){
String full;
full = (this.name + this.address + "\n" + "Student Number = " + this.studentId);
for (int i = 0; i < cs.size(); i++) {
full.append(cs[i]);
return full;
The piece of above code is where i attempt to combine 3 varaibles and the contents of an array list into a single string with formatting.
Unfortunatly it creates an error "The type of the expression must be an array type but it resolved to ArrayList"
Thanks for any help.
Jake
cs is array list, so you have to do get operation, not [] (which is for array access)
It should be like:
full.append(cs.get(i));
Not
full.append(cs[i]);
EDIT: As assylis said, full should be StringBuilder not just String, because String doesn't support append() method.
StringBuilder full = new StringBuilder();
Apache Commons StringUtils has different varieties of join() methods that mean you don't have to write this yourself. You can specify the separator and even the prefix/suffix.
I would recommend you look at Apache Commons, not just for this but for lots of other useful stuff.
You are attempting to access an ArrayList as though it is a primitive array (using the square brackets around the index). Try using the get(int index) method instead.
i.e.,
cs.get(i);
You cannot index an ArrayList like an array, you need the get(index) method. Even better, use the enhanced for loop, since it's not recommended to index over a list, as the implementation may change to LinkedList.
I also suggest using a StringBuilder for efficiency:
public String toString() {
StringBuilder full = new StringBuilder();
full.append(this.name);
full.append(this.address);
full.append("\n");
full.append("Student Number = ");
full.append(this.studentId);
for (String s: cs)
full.append(s);
return full.toString();
}
Just use
"cs.get(i)" in place of "cs[i]".
as cs is an ArrayList not an Array.
and also use
full = full + cs.get(i); and not full.append(cs.get(i));
as String type dont have a append method.
Just a note, since you don't put any spacers between each element of the ArrayList it might be unreadable. Consider using Guava's Joiner class.
So instead of
for (...)
s.append(y);
if would be
a.append(Joiner.on(" ").join(yourList));
The Joiner is also more efficient than the for loop since it uses a StringBuilder internally.

Using an internal class to make a custom object, creating an array of that object, and access information in that object using Java

Code first questions later...
public class Program2
{
//The custom word object used when parsing the input file
class Word
{
public String wordname;
public int count;
public int uniqueWord = 0;
public Word(String word)
{
wordname = word;
count = 1;
}
public boolean wordExists(String word)
{
if (word == this.wordname)
{
this.count++;
return true;
}
else
{
return false;
}
}
public int getCount(Word word)
{
return this.count;
}
public String getName(Word word)
{
return this.wordname;
}
}
// The main method
public static void main(String[] args) throws IOException
{
//new array of words size 100
Word[] words = new Word[100];
//set the first word to bananna
Word words[0] = new Word("bananna");
//print bananna
System.out.print(getName(words[0]));
}
}
Ok, so with what I know about Java, the code above should let me make an array of words, set the first to "bananna", and print it out. I have little experience making a custom class like this, and I can't find a good resource to model. Also, I am not 100% sure I understand calling static/nonstatic methods, so I'm sure some of the errors are from that as well.
What the program should do eventually, as a reference for why I am doing this, I have to take information in from a file (delimited strings aka Words) and see if it already exists in the array of words (and increment that word's count if it does), if it doesn't then make a new word.
Errors I'm getting are here:
Program2.java:116: ']' expected
Word words[0] = new Word("bananna");
^
Program2.java:116: illegal start of expression
Word words[0] = new Word("bananna");
^
2 errors
Any other information that you need let me know. I'll be back to check this post in an hour. Thank you for any help you have!
Word words = new Word[100];
Your main problem I can see is that Word[100] is an Array type that holds Word objects. You'll need the words variable to be of type Word[], not just of type Word.
Regarding static and non-static, think of it this way: You've written a Word class, and then you can create as many Word objects as you like that belong to that class. When something is static, it means it belongs to the Word class, so it belongs to the definition of a word without belonging to any particular word. In contrast, something that is not static will belong to a particular Word object.
You have syntax errors when you try to create the array, you should have:
Word[] words = new Word[100];
If you want to invoke Word.newWord() without calling the method on an instance of the Word class, this method needs to be static.
The issue is with the way you are creating Array of Objects. You should declare the array of Class and then create objects:
//new array of words size 100
Word[] words = new Word[100];
//then Create objects
words[0] = new Word("apple");
Let's start with the first error message. This is telling you that Word[] and Word are incompatible types. The [] at the end tells you that this is an array of Word objects. In other words, Word words declares a reference to a single Word object. Whereas your use of new allocates an array of them. To fix this simply change to Word[] words.
I won't go into detail about the other error messages because they will likely change after you fix this one. Good luck with your Java!

Removing Backing Array From Strings

I want to get the first 4 characters of a string to compare with another string. However, when I do something like
String shortString;
shortString = longString.subString(0,3);
It takes along longString's backing array and makes it impossible to compare easily.
I've also tried converting longString into a character array and inserting each character but I always seem to end up with long string. The Android Development documents say to use the String constructor to remove the backing array but it doesn't seem to work for me either.
String shortString = new String(longString.subString(0,3));
Any suggestions would be appreciated!
First, it's string.substring() not .subString().
Second, what do you mean "impossible to compare easily"? You can compare strings with .equals() easily.
public static void main(String[] args) {
String longString = "abcdefghijklmn";
String shortString = longString.substring(0, 3);
System.out.println(shortString.equals(longString));
}
this code prints false, as it should.
Update:
If you call .substring() so that it produces string of the same length as original string (e.g. "abc".substring(0,2)) than it will return reference to the same string. So, .equals() in this case will return true.
How would you want to compare? There's built in method for simple comparison:
longString.subString(0, 3).compareTo(anotherString);
Alternatively, since String is a CharSequence, something like:
for (int i=0; i<4; i++){
if (anotherString.charAt(i) != shortString.charAt(i)) return false;
}
would work as well.
Finally, every String is constructed in backing Array, there's no way to deny it, and longString.subString(0,3) would always (except index out of bound) return a String with a 4-element Char Array.
In the event that you actually need to get rid of the backing array the following will work:
String newString = StringBuilder(oldString).toString();
This might be necessary, for example, if you are parsing strings and creating substrings and you might need to do this:
String newString = StringBuilder(oldString.substring(start,end).toString();
This creates a truly new string with a zero offset and independent backing array. Otherwise, you maintain the same backing array which, in rare cases might cause a problem for the heap because it can never be garbage collected.

Categories