Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi for some strange reason i cant remove an item from the ArrayList, it removes the first 4 items but it will not remove City from the list any suggestions would be great. Thanks
String str = getset.getFILEMESSAGE();
ArrayList aList = new ArrayList(Arrays.asList(str.split(",")));
for (int i = 0; i < aList.size(); i++) {
System.out.println(aList.get(i));
System.out.println(aList.size());
}
aList.remove("Person ID");
aList.remove("First Name");
aList.remove("Last Name");
aList.remove("Street");
aList.remove("City");
System.out.println(aList);
System.out.println(aList.size());
String convertedmessage = aList.toString();
System.out.println("converted message = " + convertedmessage);
The code seems to be correct if all entries contain the same content/value. However your comment
i tried changing City 1 that didnt work i need the 1 in my list for the person id heres the string Person ID,First Name,Last Name,Street,City 1,Ola,Hansen,Timoteivn,Sandnes 2,Tove,Svendson,Borgvn,Stavanger 3,Kari,Pettersen,Storgt,Stavanger
implies, that the values are changing. The anwser of JajaDrinker looks correct but if you want to keep it really simple I would just remove the entries by their index. Since they are all at the beginnig, the following code will delete the first five entries of your list and should always do the job.
for(int i = 0; i < 5; i++)
aList.remove(0);
You should probably remove the strings you don't need before splitting the array... like this ...
String str = getset.getFILEMESSAGE();
String strWithOutIDNameStreetCity = str.substring(str.indexOf("City")+"City".length());
Then split it and it contains only the stuff you need.
As you say in your comments the string is:
"Person ID,First Name,Last Name,Street,City,Ola,Hansen,Timoteivn,Sandnes 2,Tove,Svendson,Borgvn,Stavanger 3,Kari,Pettersen,Storgt,Stavanger"
If that is true then your code is working.
The final output with that String would be:
converted message = [Ola, Hansen, Timoteivn, Sandnes 2, Tove, Svendson, Borgvn, Stavanger 3, Kari, Pettersen, Storgt, Stavanger]
So I am pretty sure that there is a problem with the String.
Try using debugger and show us the actual contents of the String during the execution.
String str = getset.getFILEMESSAGE();
ArrayList aList = new ArrayList(Arrays.asList(str.split(",")));
for (int i = 0; i < aList.size(); i++) {
if(aList.get(i).startsWith("City")){
String tmpString = aList.get(i);
String[] stringTab= new String[2];
stringTab= tmpString.split(" ");
aList.get(i) = stringTab[1];
}else if(....){ //Do the same for the others
aList.remove(i);
i--;
}
System.out.println(aList.get(i));
System.out.println(aList.size());
}
System.out.println(aList);
System.out.println(aList.size());
String convertedmessage = aList.toString();
System.out.println("converted message = " + convertedmessage);
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
Hello i have an array that is filled with values from database and those values i want to assign them to strings i did this code but its making error:
String[] options = s.split(",");
String visible = options[0];
String sms = options[1];
String contact = options[2];
String calllogs = options[3];
I want the values to separate in array and then by index position to delcare them on each string.
You could use this Technique.
String s = "1000";
String[] options = new String[s.length()];
for(int i=0; i< s.length(); i++)
options[i] = Character.toString(s.charAt(i));
But since you are storing chars the array could be declared as char array
You can get the value from your string like this.
String string = "1000";
char[] options = string.toCharArray();
String visible = options[0];
String sms = options[1];
String contact = options[2];
String calllogs = options[3];
or you can directly use charAt() method to get the value at a particular index.
String visible = string.charAt(0);
String sms = string.charAt(1);
String contact = string.charAt(2);
String calllogs = string.charAt(3);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
System.out.println("Please input the elements and seperate each by a comma.");
e = dk.nextLine();
String[] elems = new String[e.length()];
st = new StringTokenizer(e,",");
for (int i = 0; i<e.length(); i++) {
elems[i] = st.nextToken().toString();
}
for (int i=0; i<e.length(); i++){
System.out.println(elems[i]);
}
I am trying to print out the array elems[] but it wont work the error java.util.NoSuchElementException at java.util.StringTokenizer.nextToken(StringTokenizer.java:349 seems to be at line:
elems[i] = st.nextToken().toString();
can you help me identify and understand the problem?
A correct version:
String[] elems = e.split(",");
for(String elem : elems) {
System.out.println(elem);
}
The mistake you made is that e.length() returns the size of the string (its number of characters) so you ended up calling st.nextToken() more times than there are actual tokens separated by ",". Hence the exception.
#Jean posted a slim version of what you are trying, but ultimately to help to understand the error
e = dk.nextLine(); // input: Alfredo,Bauer,Cisco
String[] elems = new String[e.length()]; // length is 20
st = new StringTokenizer(e,","); // st has a length of 3
Now if you call it like this
for(int i = 0;i<e.length();i++){
elems[i] = st.nextToken().toString(); // NoSuchElementException
}
Because you try to call the nextToken() which does not exist.
The docs:
Returns the next token from this string tokenizer.
Throws:
NoSuchElementException - if there are no more tokens in this
tokenizer's string.
To fix your problem use the length of countTokens()
OR
while(st.hasMoreElements()){
elems[i] = st.nextToken().toString();
}
Another alternative.
String[] elems = e.split(",");
System.out.print(Arrays.toString(elems ));
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I know there has been a similar question before but it doesn't actually solve my problem. I only want to get my string input which represents an employee name and make sure the input is this form "Name". Not "name", not "Name". So i tried to do it but the output doesn't work. So here is the code :
Scanner scanner = new Scanner(System.in);
String ename; // input string
System.out.println("Enter Employee Name : (Type -Name-, not -name-, not -NAME-!!!");
ename = scanner.nextLine(); // read the string input
char[] Transform = new char[ename.length()]; // this array will contain the string split in characters
for (int i = 0;i < ename.length(); i++)
{
Transform[i] = ename.charAt(i); // Split the input to a char array
}
Transform[0] = Character.toUpperCase(Transform[0]); // First Letter Always Capital
for (int i = 1;i < ename.length(); i++)
{
Transform[i] = Character.toLowerCase(Transform[0]); // Other letters small
}
String name = new String(Transform); // convert the array to a new String variable
System.out.println("NEW STRING : " + name );
Output :
You need to change the Statement in the i loop to
Transform[i] = Character.toLowerCase(Transform[i]);
adding Transform[i] and not Transform[0] because you are inserting same first character again and again to the array
Demo
I don't know why you need all this code.
For example:
char[] transform = new char[ename.length()];
for (int i = 0; i < ename.length(); i++) {
transform[i] = ename.charAt(i);
}
is identical to
char[] transform = ename.toCharArray();
And your entire code can be rewritten as:
public static String capitalise(final String name) {
return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
}
Test cases:
public static void main(String[] args) throws Exception {
System.out.println(capitalise("Name"));
System.out.println(capitalise("name"));
System.out.println(capitalise("NamE"));
System.out.println(capitalise("NAMe"));
}
Output:
Name
Name
Name
Naae
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm currently taking my first java class and have become completely stuck on an exercise. I'm supposed to read data from a text file containing student IDs and their corresponding test scores, have the program grade them then print the results.
I kind of understand the problem, but the book we're working from is kinda hard to read. It all blurs together and I feel like they want me to read two separate things and make a logical leap on how to put them together and I just don't get it.
TTFTFTTTFTFTFFTTFTTF
ABC54102 T FTFTFTTTFTTFTTF TF
DEF56278 TTFTFTTTFTFTFFTTFTTF
ABC42366 TTFTFTTTFTFTFFTTF
ABC42586 TTTTFTTT TFTFFFTF
My main issue is that I don't see how I tie the array to the data I have.
I am not gonna post the whole solution but give some steps to start.
Follow this example
BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
ArrayList<String> array = new ArrayList<>();
while ((line = reader.readLine()) != null) {
array.add(line);
}
and to split the string like this
str.split(" "); // considering that ids and name are separated by spaces
So, since blanks are allowed in your list of T's and F's, which I assume means the student left the answer to the question blank, you do not have the luxury of using a convenience method like split to easily separate the answers. Instead we use our knowledge that the number of questions must be the same, and id's must have a common length. You can use the substring method to parse out the what you need.
Here's some pseudocode:
final int NUM_QUESTIONS = 25; //I didn't actually count, that's your job
final int ID_LENGTH = 8;
int currentIndex = 0;
//assuming you can fit the whole string in memory, which you should in an intro java class
//do the operations that googling "read a file into a string java" tells you to do in readFileToString
String fileContents = readFileToString("saidFile.txt");
while(fileContents.charAt(currentIndex) != fileContents.length()){
String userAnswers = fileContents.substring(currentIndex, currentIndex+NUM_QUESTIONS);
//move index past userAnswers and the space that separates the answers and the id
currentIndex = currentIndex + NUM_QUESTIONS + 1;
String userId = fileContents.substring(currentIndex, currentIndex+ID_LENGTH)
//move currentIndex past userId and the space that separates the userId from the next set of answers
currentIndex = currentIndex + ID_LENGTH + 1;
//either create an object to store the score with the userId, or print it right away
int score = gradeAnswers(userAnswers)
System.out.println(userId + " scored " + score);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to find all the substring of one String that contains a key word.
Ex: "This is the keyword in the string".
Output: the keyword, this is the keyword, the keyword in the string, is the keyword in ....
I am think of finding all the substrings first then try to filter one by one. But I think that would be very bad solution.
Could you please give me some advice to do that!. Thank you very much.
I have edited to just find the sequence of tokens.
Try this:
String str = "abcdefkeybncv...";
String key = "key";
int index = str.indexOf(key);
ArrayList<String> sub = new ArrayList<String>();
for (int i = 0; i < str.length(); i++) {
for (int j = 0; j <= str.length() - i; j++) {
String s = str.substring(i, i+j);
if(s.indexOf(key) >= 0){
sub.add(s);
}
}
}
System.out.println(sub);
Output for the code above:
[abcdefkey, abcdefkeyb, abcdefkeybn, abcdefkeybnc, abcdefkeybncv, abcdefkeybncv., abcdefkeybncv.., abcdefkeybncv..., bcdefkey, bcdefkeyb, bcdefkeybn, bcdefkeybnc, bcdefkeybncv, bcdefkeybncv., bcdefkeybncv.., bcdefkeybncv..., cdefkey, cdefkeyb, cdefkeybn, cdefkeybnc, cdefkeybncv, cdefkeybncv., cdefkeybncv.., cdefkeybncv..., defkey, defkeyb, defkeybn, defkeybnc, defkeybncv, defkeybncv., defkeybncv.., defkeybncv..., efkey, efkeyb, efkeybn, efkeybnc, efkeybncv, efkeybncv., efkeybncv.., efkeybncv..., fkey, fkeyb, fkeybn, fkeybnc, fkeybncv, fkeybncv., fkeybncv.., fkeybncv..., key, keyb, keybn, keybnc, keybncv, keybncv., keybncv.., keybncv...]
Build suffix array: http://en.wikipedia.org/wiki/Suffix_array
Use binary search to find your substring there
Move up and down from this point in suffix array while suffixes starts with substring