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];
Related
I have a
List<ArrayList> arg = new ArrayList<ArrayList>();
with
[[logo], [cd_branche], [lib_branche]],
(other arguments not relevant)
[[1111,22222,3333]],[[2222,324,432]]...
and I want to cast it to a String[] so I did this
Object[] obj = arg.toArray();
String[] headers =new String[obj.length];
for(int i=0;i<headers.length;i++) {
headers[i]= (String) obj[i];
}
but I'm getting
java.util.ArrayList cannot be cast to java.lang.String
The output I'm looking for is
headers[0]=logo
headers[1]=cd_branche
headers[2]=lib_branche
Using Java 6
It sounds like you want it to be an array of strings (i.e. "[["logo", "cd_branche", "lib_cranche"],[..],[..],[1111,22222,3333],[2222,324,432]").
In that case simply do:
Object[] obj = arg.toArray();
String[] headers =new String[obj.length];
for(int i=0;i<headers.length;i++) {
headers[i]= Arrays.toString(obj);
}
And each one of your ArrayList objects inside obj will be returned in string array format.
UPDATE: Since you want it as a flat array, you'll need to (a) compute the size of the array needed and (b) run through your object with two loops and make a deep search as such:
int size = 0;
for (int i = 0; i < arg.size(); size += arg.get(i++).size());
String[] headers =new String[size];
for(int count = 0, i=0;i<arg.size();i++) {
for (int j=0; j< arg.get(i).size(); j++) {
headers[count++]= arg.get(i).get(j).toString();
}
}
String headers = "";
for (String header:arg)
{headers += header;}
I'm trying to populate an array [C], then display it using a for loop.. I'm new to arrays and this is confusing the hell out of me, any advice is appreciated!
Below is my code:
public static void main(String[] args) {
int A[] = new int[5];
int B[] = new int[5];
String C[] = new String[5];
int D[] = new int[5];
C[] = {"John", "Cook", "Fred"};
for(String name: C)
System.out.println(C);
}}
You can define and populate an array in two ways. Using literals:
String c[] = {"John", "Cook", "Fred"};
for(String name : c) { // don't forget this { brace here!
System.out.println(name); // you want to print name, not c!
}
Or by setting each index element:
int d[] = new int[2];
d[0] = 2;
d[1] = 3;
for(int num: d) {
System.out.println(num);
}
(You can only use the literal when you first define the statement, so
String c[];
c = {"John", "Cook", "Fred"};
Will cause an "illegal start of expression" error.)
You want to print name instead of C.
C is the name of the array, while name is the name of the String variable. Therefore you must print name instead of C
System.out.println(name);
for(int i=0;i<=2;i++){
System.out.println(C[i]);
}
here 2 is the last index of the array C
You cannot simply print an array you have to provide an index to your item
where C[0] is john and C[1] is Cook and so on
and if you want to use a for each loop then this is how it goes
for(Iterator<String> i = someList.iterator(); i.hasNext(); ) {
String item = i.next();
System.out.println(item);
}
Try specifying at what index you want to add the element.
Example:
C[0] = "hej";
Also, print the element in the array, not the actual array. (System.out.println(name);)
Is there any possibility to merge two elements of ArrayList?
This is my array = [u,s,m,a,t,t]
and I want to have something like this = [us,matt]
I've tried to use toString(), and replace('',''), but it merges whole array [usmatt].
Any other options?
I don't know exactly what you mean but what you try to achieve could be done this way:
Pseudo-code:
String[] array1 = [u,s,m,a,t,t]
String a = array[0]+array[1]
String b = array[2]+array[3]+array[4]+array[5]
String[] array2 = [a,b]
Try this: (For any length ArrayList.)
public static void MergeArrayList() {
ArrayList<Character> Array = new ArrayList<Character>() {{ add('u');add('s');
add('m');add('a');add('t');add('t');}};
ArrayList<String> newArray = new ArrayList<>();
int n=2; // Change this to indicate where you need to make the cut.
String str="";
for (int i=0;i<Array.size();i++) {
if (i==n) {
newArray.add(str);
str="";
}
str += Array.get(i);
}
newArray.add(str);
System.out.println(Array);
System.out.println(newArray);
}
I am building an array based off comparing two other arrays. But when I initalize my third array I have to set the length. But that is making my array have null objects in some instances. Is there away I can drop the empty/null postions in the array. See my code so far below:
private String[] tags = new String[] { "Mike", "Bob", "Tom", "Greg" };
private boolean[] selected = new boolean[tags.length];
public String[] selected_tags = new String[tags.length];
for (int i = 0; i < tags.length; i++) {
if (selected[i] == true){
selected_tags[i] = tags[i];
}
}
I left out the code for the checkboxes that builds the Boolen selected [].
Either way if I only select 2 tags then my selected_tags[] array will be Mike, Bob, Null, Null
I need to get the Null Null out. Thanks in advance!
You can use ArrayList, instead of array.
private String[] tags = new String[] { "Mike", "Bob", "Tom", "Greg" };
private boolean[] selected = new boolean[tags.length];
public List<String> selected_tags = new ArrayList<String>();
for (int i = 0; i < tags.length; i++) {
if (selected[i] == true){
selected_tags.add(tags[i]);
}
}
No, you can't drop the null values (and change the length of the array) after you've created it. You'll have to create a new one (or for instance use an ArrayList as illustrated below):
List<String> list = new ArrayList<String>();
for (int i = 0; i < tags.length; i++)
if (selected[i] == true)
list.add(tags[i]);
// Convert it to an array if needed:
selected_tags = list.toArray(new String[list.size()]);
As others have mentioned, this is much easier with an ArrayList. You can even get a regular array from it with the toArray function.
Without using ArrayList, you would have to figure out the length first and not include the null values. As you can see, that's a little messy:
int length = 0;
for( boolean b : selected ) if(b) ++length; // Count the "true"s
String[] selected_tags = new String[length];
for( int i = 0, j = 0; i < tags.length; i++ )
if( selected[i] )
selected_tags[j++] = tags[i];
Instead of using a standard Java array, you should use an ArrayList : it'll allow you to add elements to it, automatically growing the list as needed.
Basically, you'd first declare / instanciate the ArrayList, without specifying any kind of size :
public ArrayList<String> selected_tags = new ArrayList<String>();
And, then, in your loop, you'd use the add() method to add items to that ArrayList :
selected_tags.add(tags[i]);
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