looping lists in java - java

I have a simple java statement along the lines of:
String[] ykl = yklList.get(0).split(" ");
where, yklList is an ArrayList containing sentences which are split into words. The above works fine.
When I now try and loop this:
Loop:1
for (int i=0;i<=4;i++)
{
String[] ykl = yklList.get(i).split(" ");
}
It does not seem to work and throws me a compile error. Is the above loop wrong?
I have another for loop after the above:
Loop:2
for (String ykl : yklList)
{
//do something
}
It throws me a compile error here saying:
cannot find symbol
symbol : variable ykl
location: class test
for (String ykl : yklList)
Presumably Loop 1 went wrong somewhere?
Edit:
The "full" code looks something like this:
for (int i=0;i<=yklList.size()-1;i++)
{
String[] ykl = yklList.get(i).split(" ");
}
for (String y : ykl)
{
t.add(y);
}
and the error is:
cannot find symbol
symbol : variable ykl
location: class test
for (String y : ykl)

Regarding to your update:
You define ykl in the first loop. So the variable is not in the scope of the second loop. Your code have to look like this:
for (String yklSentence : yklList) {
String[] ykl = yklSentence.split(" ");
for (String y : ykl) {
t.add(y);
}
}
By the way: If you would use an IDE like Eclipse you would see those errors in the editor!

In your appendix, the second cycle does not know about the variable ykl, as defined in the previous cycle and after leaving it - it is destroyed.
If variables were not removed - after a while all of the available computer memory would be filled, which would cause an error of the program. If only you were given the opportunity dal unnecessary variables - that is allowed a situation where you forgot to remove unneeded variables and memory, again, would be full. In this context, Java simplifies the development and can not think about what you are then permennye not removed.
To correct the error:
ArrayList <String> yklList = new ArrayList <String> ();
ArrayList <String> t = new ArrayList <String> ();
for (int i = 0; i <yklList.size (); i + +)
{
String [] ykl = yklList.get (i). Split ("");
for (String y: ykl)
t.add (y);
}
or:
If you fill out absolutely all characters t of yklList:
ArrayList<String> yklList = new ArrayList<String>();
ArrayList<String> t = new ArrayList<String>();
String[] ykl = new String[0];
for (int i=0;i<yklList.size();i++) {
String[] tempYkl = yklList.get(i).split(" ");
String[] tempYklDub = new String[tempYkl.length];
String[] tempYklDubDub = new String[ykl.length];
for (int z=0; z< tempYkl.length; z++)
tempYklDub[z] = tempYkl[z];
for (int z=0; z<ykl.length; z++)
tempYklDubDub[z]=ykl[z];
ykl = new String[tempYklDubDub.length+tempYklDub.length];
for (int z=0; z<tempYklDubDub.length; z++)
ykl[z]=tempYklDubDub[z];
for (int z=tempYklDubDub.length, k=0; k<tempYklDub.length; z++, k++)
ykl[z]=tempYklDub[k];
}
for (String y : ykl)
t.add(y);

If I understood you correctly, you have less than 4 yklList elements.
And, at the next iteration, it tries to take an element from outside the yklList
Solutions to the problem:
for (int i = 0; i <yklList.size(); i + +) {
String[] ykl = yklList.get(i).split(" ");
}
or
for (String yklListDub: yklList) {
String[] ykl = yklListDub.split(" ");
}
P.S. I'm sorry for my english)

You should make sure looping the right count of elements.
Try using size() for your ArrayList:
for (int i=0;i<ykl.size();i++)
{
String[] ykl = yklList.get(i).split(" ");
}
Keep in mind that every cycle overwrites your ykl array. Defining it outside of your loop would solve this problem.
Edit:
Try
String[] ykl = new String[ykl.size()];
for (int i=0;i<ykl.size();i++)
{
ykl[i] = yklList.get(i).split(" ");
}
for (String y : ykl)
{
t.add(y);
}

Related

How to iterate through an arraylist of an arraylist of strings?

I'm creating a program that allows users to interact with a file thats input. One of the options is to display the file. Below, I store the file into an arraylist first by creating arraylists consisting of lines, and then an inner arraylist separated of strings, separated by spaces.
Scanner sc = new Scanner(fileName);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] words = {};
words = line.split(" ");
ArrayList<String> lineArray = new ArrayList<String>();
for (int i = 0; i < words.length; i++) {
lineArray.add(words[i]);
}
fileByLine.add(lineArray);
}
sc.close();
I'm trying to print the contents of the arraylist, called fileByLine, as they appear in the file, but I'm not sure how to. Any suggestion?
case '1':
for(int i = 0; i < fileByLine.size(); i++){
for(int j = 0; j < fileByLine.[i].size(); j++){
System.out.print(fileByLine[i][j]);
} System.out.println("");
} break;
You are using bracket notation which is for arrays, you need to use get() for arraylists
for(int i = 0; i < fileByLine.size(); i++){
for(int j = 0; j < fileByLine.get(i).size(); j++){
System.out.print(fileByLine.get(i).get(j));
}
System.out.println("");
}
Since your container consist of String type you can just print it as follow:
System.out.println(fileByLine);
No need to loop through your collection. For example, let's say you have following list:
List<String> oneList = new ArrayList<>(Arrays.asList("1 2 3 4 5 6 7".split(" ")));
and you want to add it into another list:
List<List<String>> anotherList = new ArrayList<>();
anotherList.add(oneList);
After adding you would like to print it and here is how it looks:
System.out.println(anotherList);
Output: [[1, 2, 3, 4, 5, 6, 7]]
It prints because of String type if you keep any other custom type in your container and try to print it that will not work until you override toString() method.
If you need to iterate over two nested lists you can use this approach too:
Iterator<List<String>> outerIterator = anotherList.listIterator();
while (outerIterator.hasNext()) {
Iterator<String> innerIterator = outerIterator.next().listIterator();
while (innerIterator.hasNext()) {
String item = innerIterator.next();
System.out.print(item + " ");
}
System.out.println();
}
Or something like this as well...
for (List list : fileByLine) {
for (Object line : list) {
System.out.print(line);
}
System.out.println("");
}

check if there are any elements from one arraylist in another one and print the same elements

I want to check if the list "wordlist" has some elements from the list "list". If it has , these elements should be printed. Just have some difficulties with syntax to compare 2 lists in java. Here is my code:
File files = new File("E:/test/dictionary.txt");
String[] words = file.split(" ");
List<String> wordlist = Arrays.asList(words);
try {
Scanner scanner = new Scanner(files);
List<String> list = new ArrayList<>();
while (scanner.hasNextLine()) {
list.add(scanner.nextLine());
}
scanner.close();
for (String word : wordlist) {
System.out.println(word);
}
for (String oleg : list) {
System.out.println(oleg);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Perhaps I am misreading your question because the solution seems pretty simple to me. All you need to do is run a for-loop and use the ArrayList contains(Object O) method or run a nested for-loop and use the String equals(String O) method. See below.
METHOD 1:
for(int a = 0; a < wordlist.size(); a++)
if(wordlist.contains(list.get(a)))
System.out.println(list.get(a));
METHOD 2:
for(int a = 0; a < wordlist.size(); a++)
for(int b = 0; b < wordlist.size(); b++)
if(wordlist.get(a).equals(list.get(b));
System.out.println(list.get(b));
In the second example I keep wordlist.size() as the factor in both loops because both list and wordlist should be the same size, or at least I assume that.
Also, with references or variables that more than one word, Java convention dictates that good practice would be to capitalize the first letter of all subsequent words, that is, wordlist should be wordList.
Hope this helps.
If I understand your question, use Collection.retainAll(Collection) (per the linked Javadoc to retain only the elements in this collection that are contained in the specified collection) like
wordlist.retainAll(list);
System.out.println(wordlist);
// for (String word : wordlist) {
// System.out.println(word);
// }
// for (String oleg : list) {
// System.out.println(oleg);
// }

storing a string into an array causes an ArrayIndexOutOfBoundsException error

int x = 0;
String[] QEquivalent = {};
String s = sc.nextLine();
String[] question2 = s.split(" ");
for (int i = 0; i < question2.length; i++) {
System.out.println(question2[i]);
x++;
} //debug
System.out.println(x);
String s2 = sc2.nextLine();
String[] Answer = s2.split(" ");
for (int c = 0; c < Answer.length; c++) {
System.out.println(Answer[c]);
} //debug
int y;
String u = sn.nextLine();
String[] t = u.split(" ");
for (y = 0; y < question2.length; y++) {
for (int w = 0; w < t.length; w++) {
if (t[w].equals(question2[y])) {
QEquivalent[y] = "ADJ";
System.out.println(QEquivalent[y]);
break;
}
}
}
this is the line of codes that I have as of now. when a string in question2 is found in String[] t, it should store the string "ADJ" in String[] QEquivalent. I can't seem to fix the error. can someone please help me?
You are creating an empty array here:
String[] QEquivalent = {};
So, any index you try to access will be out of bounds. You should creating an array using a fixed size.
Or, you can better use an ArrayList instead, which can dynamically grow in size:
List<String> qEquivalent = new ArrayList<String>();
and then add elements using:
qEquivalent.add("ADJ");
And please follow Java Naming conventions. Variable names should start with lowercase letters.
You create an empty array:
String[] QEquivalent = {};
and then set some elements at index y > 0:
QEquivalent[y] = "ADJ";
You can either:
compute the final dimension of the array and be sure to instantiate it: String[] QEquivalent = new String[SIZE];
use a dynamic structure like an ArrayList
eg:
ArrayList<String> QEquivalent = new ArrayList<QEquivalent>();
QEquivalent.add("ADJ");
Your array QEquivalent is an empty array . It is of length 0 , hence even QEquivalent[0] will throw ArrayIndexOutOfBoundsException.
One fix I can see is assign it a length :
String[] question2 = s.split(" ");
// Just assign the dimension till which you will iterate finally
// from your code `y < question2.length` it seems it should be question2.length
// Note you are always indexing the array using the outer loop counter y
// So even if there are n number of nested loops , assigning the question2.length
// as dimension will work fine , unless there is something subtle you missed
// in your code
String[] QEquivalent = new String[question2.length];
Better use any implementation of List , like an ArrayList.
List<String> qEquivalent = new ArrayList<String>();
......
if (t[w].equals(question2[y])) {
qEquivalent.add("ADJ");
System.out.println(qEquivalent.get(y));
break;
}
Give some size to the array String[] QEquivalent = new String[100];
You statement String[] QEquivalent = {}; creates an array with zero size.
You are declaring your QEquivalent array as an empty String array.
When you access the index QEquivalent[y], that index doesn't exist, hence the ArrayIndexOutOfBoundsException.
I strongly suggest you use a List<String> instead.
Such as:
List<String> qEquivalent = new ArrayList<String>(); // replaces the array declaration and uses Java conventional naming
...
qEquivalent.add("ADJ"); // replaces the indexing of the array and adds the item
Possibly QEquivalent variable makes the error.Because when you declare that variable, its length is 0.So declare the variable as with new and a size.
Or move it after you split the string into question2 and use:
String[] QEquivalent = new String[question2.length];

Converting an ArrayList to an array

I have the following problem... I want to read unknown number of strings from the input. So, I made an arraylist 'words' and added all the strings from the input. Then I wanted to convert this arraylist into simpler String array 'wordsarray'(String[])... As I did that I wanted to check if everything is ok (if words are saved in 'wordsarray') so I
tried to print out the whole array... but it doesn't give me what I wanted... It seems like my code does not work. Where is the problem?
Thanks for your help
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> words = new ArrayList<String>();
while(sc.hasNextLine()) {
words.add(sc.nextLine());
}
String[] wordsarray = new String[words.size()];
for(int i = 0; i < words.size(); i++) {
wordsarray[i] = words.get(i);
}
for(int i = 0; i < words.size(); i++) {
System.out.println(wordsarray[i]);
}
}
There is a precooked method to do what you are trying to do:
ArrayList<String> words = new ArrayList<String>();
String[] array = words.toArray(new String[words.size()]);
But your code seems correct, are you sure everything is fetched fine inside the ArrayList?
By your comment I guess that the problem is the fact that you don't place everything inside a loop. This code:
while(sc.hasNextLine()) {
words.add(sc.nextLine());
}
works only once. If you keep inserting words and pressing enter you are already outside the loop because the Scanner already reached a point in which it didn't have any more lines to fetch.
You should do something like:
boolean finished = false;
while (!finished) {
while(sc.hasNextLine()) {
String line = sc.nextLine();
if (line.equals(""))
finished = true;
else
words.add(sc.nextLine());
}
}
}
This works fine for me:
import java.util.*;
public class a
{
public static void main (String [] args) throws Exception
{
Scanner sc = new Scanner(System.in);
List<String> words = new ArrayList<String>();
while(words.size () < 3 && sc.hasNextLine ()) {
String s = sc.nextLine();
System.out.println ("Adding " + s);
words.add(s);
}
String[] wordsarray = words.toArray(new String [] {});
for(int i = 0; i < words.size(); i++) {
System.out.println("Printing ..." + wordsarray[i]);
}
}
}
Output:
java a
1
Adding 1
2
Adding 2
3
Adding 3
Printing ...1
Printing ...2
Printing ...3

add elements into the list in Java

Here is the code:
class Test {
public static void main (String[] args) throws Exception {
java.io.File fail = new java.io.File("C:/Users/Student/Desktop/Morze.txt");
java.util.Scanner sc = new java.util.Scanner(fail);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] lst = line.split(" ");
int[] letter = new int[26];
int[] sumbol = new int[26];
for (int i = 0; i < lst.length; i++)
System.out.print(lst[i] + " ");
System.out.println();
// How to add?
}
}
}
Please, explain how can I add all letters into list Letter and symbols into list Sumbol?
Content of the file Morze.txt:
A .-
B -...
C -.-.
D -..
E .
F ..-.
G --.
H ....
I ..
J .---
K -.-
L .-..
M --
N -.
O ---
P .--.
Q --.-
R .-.
S ...
T -
U ..-
V ...-
W .--
X -..-
Y -.--
Z --..
Thanks!
You don't have a list, you have an array(s). It appears you want to add the values to two arrays. However you appear to have some code in your loop which should not be in your loop.
Additionally your data is text/String not numbers/int values.
String[] letter = new String[26];
String[] symbol = new String[26];
int count = 0;
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] lst = line.split(" ");
letter[count] = lst[0];
symbol[count] = lst[1];
count++;
}
for (int i = 0; i < count; i++)
System.out.println(letter[i] + " " + symbol[i]);
I'm going to offer a solution that fixes your implementation because I think it might help you understand a few concepts. However I would recommend once you get it working that you go back and read about the Java List interface and re-write your code. Lists are much cleaner way of maintaing sequences that may grow or shrink in length and will greatly reduce the complexity of your code.
You should start by moving your letter and symbol array declarations out of your while loop. Variables within a block in Java are scoped to its bounds. In other words, no statement outside the while loop has visibility of either array. This has the side-effect of creating a new array for every line you parse using your scanner.
int[] letter = new int[26];
int[] sumbol = new int[26];
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] lst = line.split(" ");
Next you'll need to know where to put your current symbol/letter in the array, an index. So you'll want to keep a count of how many lines/symbols you've processed so far.
int[] letter = new int[26];
int[] sumbol = new int[26];
int numberOfSymbolsProcessed = 0;
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] lst = line.split(" ");
Now you have two arrays and an index into each, add the symbol and letter to the array as follows...
int[] letter = new int[26];
int[] sumbol = new int[26];
int numberOfSymbolsProcessed = 0;
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] lst = line.split(" ");
letter[numberOfSymbolsProcessed] = lst[0];
sumbol[numberOfSymbolsProcessed] = lst[1];
numberOfSymbolsProcessed = numberOfSymbolsProcessed + 1;
This would be an excellent usecase for the List interface.
List<String> list = new LinkedList<String>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
list.addAll(Arrays.asList(line.split(" ")));
}
If you know that your file will either have letters or symbols, then, what you can do is to use the Pattern class and use a regular expression such as
^[a-z][A-Z]+$
to check if the given string, in your case it will be lst[i] has one or more letters. The ^ at the beginning and $ at the end ensure that you have only letters in the string.
If the string matches the pattern, than you know that it is a letter, so you can add it to the Letter list. If it does not, you can add it to the symbol data structure.
I recommend that you do not use arrays, but rather dynamic data structures such as an ArrayList for your lists since this will grow dynamically as you add elements to it.
For more information regarding the pattern class, you can check this tutorial

Categories