trying to print out the array in java [closed] - java

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 ));

Related

How do I stop NumberFormatException? [closed]

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 1 year ago.
Improve this question
I'll keep this short. I don't know why I'm getting NumberFormatException in my code. Any help would be much appreciated.
import java.io.IOException;
import java.util.Arrays;
public class Main {
public static void loadFiles() throws IOException {
Info i = new Info();
Song s = new Song();
int a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7;
s.id = i.getSongTxt(a);
s.titulo = i.getSongTxt(b);
String ano = i.getSongTxt(c);
s.id1 = i.getSongArtistsTxt(a);
s.artista = i.getSongArtistsTxt(b);
s.id2 = i.getSongDetailsTxt(a);
String tempo = i.getSongDetailsTxt(b);
String explicita = i.getSongDetailsTxt(c);
String popularidade = i.getSongDetailsTxt(d);
String dancabilidade = i.getSongDetailsTxt(e);
String vivacidade = i.getSongDetailsTxt(f);
String volume = i.getSongDetailsTxt(g);
String[] ano1 = new String[ano.length()];
String[] tempo1 = new String[tempo.length()];
String[] explicita1 = new String[explicita.length()];
String[] popularidade1 = new String[popularidade.length()];
String[] dancabilidade1 = new String[dancabilidade.length()];
String[] vivacidade1 = new String[vivacidade.length()];
String[] volume1 = new String[volume.length()];
ano = ano.replaceAll("\\s+", "");
ano1 = ano.split(" ");
tempo1 = tempo.split("");
for(int n = 0; n < 7; n++){
s.ano[n] = Integer.parseInt(ano1[n]);
}
System.out.println(Arrays.toString(ano1));
}
public static void main(String[] args) throws IOException {
Info i = new Info();
loadFiles();
}
}
and this is what the error looks like.
Exception in thread "main" java.lang.NumberFormatException: For input string: "[2012,2013,2012,2013,2012,2013,2012]"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:660)
at java.base/java.lang.Integer.parseInt(Integer.java:778)
at pt.ulusofona.aed.deisiRockstar2021.Main.loadFiles(Main.java:44)
at pt.ulusofona.aed.deisiRockstar2021.Main.main(Main.java:55)
Process finished with exit code 1
Any ideas as to why it's giving me this error?
Read the Javadoc.
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
Your input string "[2012,2013,2012,2013,2012,2013,2012]" is not a number. So that input cannot be processed as a number.
No more specific diagnosis can be made as you have shown too much code that does not matter, not enough code that does matter, and no example data.
I suggest reading the Help section of Stack Overflow to learn how to ask better questions. Specifically: How to create a Minimal, Reproducible Example.
"How do I stop it?"
Look at how you (supposedly) splitting the ano string.
ano = ano.replaceAll("\\s+", "");
ano1 = ano.split(" ");
That says:
Replace all whitespace with ... nothing. That is: remove all whitespace.
Split using a single space as the separator.
Which plainly doesn't make sense. You have removed the very characters that you are telling split to split on!
But that's wrong anyway, because the actual string you are attempting to process clearly also contains ',', '[' and ']' characters, and they shouldn't be part of the number strings.
So what you need to do is redesign the way you are splitting the ano string into a sequence of number strings ... so that it will work with your input.
Hint: find and read the javadocs for String.split(...) and Pattern.

String arrays of capacity 5 will only display first 4 elements (java - scanner class) [closed]

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 3 years ago.
Improve this question
I'm new in java programming and was learning input via scanner class. My program accepts a string array of capacity 5, and displays it back to the user.
However, the array is only accepting 4, and I can't figure out why. Any help would be appreciated.
My code
Accepting string array
String n[] = new String[5];
for (int i = 0 ; i<5 ; i++)
{
n[i] = sc.nextLine();
}
Displaying the string array
for(int i=0 ; i<5 ; i++)
{
System.out.println(n[i]);
}
The 5th string is being accepted and printed as blank for some reason, as in instead of 5 only 4 strings are being accepted and printed.
Maybe you read from a file, and the last line does not end with a line break.
From a Scanner you may first test whether a next line is available:
String[] n = new String[5];
for (int i = 0; i < 5; i++) {
if (!sc.hasNextLine()) {
System.out.println("Failing to read line at index " + i);
break;
}
n[i] = sc.nextLine();
}
Notice that String[] n is the usual way to write an array variable. String n[] is for C programmers.
It would be helpful if you provided information on what your input source is. However, sc.nextLine() always progresses the scanner to the next line (excluding any line separators at the end of the line).
Your code is correct given (for example) an input file such as "test.txt":
Line1
Line2
Line3
Line4
Line5
I would make sure there's no spaces between your input and that you don't accidentally call sc.nextLine() (or any of the scanner next methods) somewhere earlier in your code.

Using contains method in java [closed]

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 years ago.
Improve this question
I have converted my string array to Array using Arrays.toString(array) method.
But still my string looks like an array in this way. [Monday, Sunday, Tuesday]. Okie thats not the issue. I have another array which is also converted to String.
Say [Monday, Tuesday]. Now this is my problem. When I try to use contains method in these arrays it is not working. Can anyone help.
See Arrays#toString(Object[]):
The value returned by this method is equal to the value that would be returned by Arrays.asList(a).toString(), unless a is null, in which case "null" is returned.
and String#contains(CharSequence):
Returns true if and only if this string contains the specified sequence of char values.
Example:
String[] stringArray = new String[] { "Monday", "Tuesday" };
String string = Arrays.toString(stringArray);
boolean result = string.contains("Tuesday");
But I would recommend:
String[] stringArray = new String[] { "Monday", "Tuesday" };
List<String> stringList = Arrays.asList(stringArray);
boolean result = stringList.contains("Tuesday");
See Arrays#asList(T...) and ArrayList#contains(Object)
This is one way to check if one array got (contains) content of another array without using the contains method
String[] string1 = new String[] { "Monday", "Sunday", "Tuesday" };
String[] string2 = new String[] { "Monday", "Tuesday" };
for (int i = 0; i < string1.length; i++) {
for (int j = 0; j < string2.length; j++) {
if (string1[i].equals(string2[j])) {
// do something here
}
}
}

ArrayList not removing item [closed]

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);

How to swap the words in the list. [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can reprint this string
List<String> abc = new ArrayList<String>();
abc.add("D. Bwer");
abc.add("Z. abc");
abc.add("X. RDS");
Output : Bwer, D.
abc, Z.
RDS, X.
tried swapping the indexes but didnt work
List<String> abc = new ArrayList<String>();
abc.add("D. Bwer");
abc.add("Z. abc");
abc.add("X. RDS");
List<String> string1= new ArrayList<String>();
for(String str1: abc){
String new1= str1.split("\\s+")[0];
String new2= str1.split("\\s+")[1];
String temp = new2+","+ new1;
string1.add(temp );
}
}
Try something like this
List<String> abc = new ArrayList<String>();
abc.add("D. Bwer");
abc.add("Z. abc");
abc.add("X. RDS");
for(String i:abc){
String[] arr=i.split(" ");
System.out.println(arr[1]+", "+arr[0]);
}
If you want to go by substring
First solution if space location varies.
Second solution if you know that space will always be present at third location.
List<String> abc = new ArrayList<String>();
abc.add("D. Bwer");
abc.add("Z. abc");
abc.add("X. RDS");
for(String dummy:abc){
System.out.println((dummy.substring(dummy.indexOf(" ")+1))+",
"+dummy.substring(0, dummy.indexOf(" "))); //1
System.out.println(dummy.substring(3)+", "+dummy.substring(0,3)); //2
}
To swap elements of Java ArrayList use,
static void swap(List list, int firstElement, int secondElement)
method of Collections class. Where firstElement is the index of first
element to be swapped and secondElement is the index of the second element
to be swapped.
If the specified positions are equal, list remains unchanged.
Please note that, this method can throw IndexOutOfBoundsException if
any of the index values is not in range.
Collections.swap(arrayList,0,4);

Categories

Resources