I am working on an assignment for my java class and part of the assignment requires reading in a .csv file that is 20x20 and inserting each string into an array.
I am trying to convert my 1d array from the initial reading in of the file into a 2d array, but I seem to be doing something wrong in my output of the data.
I made an add method, and when running the program and calling the method I only get one column of strings and listed in reverse order, but if I do a System.out.println() I don't the output I desire. I am still fairly new to this so I'm sure I just don't see the simple error, but to me, it looks correct.
the reading in of the file
try {
Scanner fileScanner = new Scanner(toOpen);
while (fileScanner.hasNext()) {
fromFile = fileScanner.nextLine();
String temp[] = fromFile.split(" ");
theList.add(temp[0]);
System.out.println(fromFile);
String[][] arr = new String[20][20];
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = temp[i];
System.out.print(arr);
}
}
System.out.println();
}
fileScanner.close();
my add method
public void add(String tableValue) { // Adds a new node
Node newNode = new Node(tableValue);
if (isEmpty()) {
setRoot(newNode);
} else {
newNode.setNext(getRoot());
setRoot(newNode);
}
}
and my method that prints the result
public String makeString() { // A Class that makes a string
String theString = new String();
if (isEmpty()) {
theString = "List is empty";
} else {
Node printer = getRoot();
while (printer != null) {
theString += printer.getTableValue() + " ";
printer = printer.getNext();
}
}
return theString;
}
I guess your problem is here:
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = temp[i];
This assigns the same value (temp[i]) to all slots in arr[i]. Again guessing, I think you need something like:
int tmpIndex = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = temp[tmpIndex];
tmpIndex++;
In other words: you have 400 different values in temp. But your code is only assigning the first 20 values 20 times again and again.
Beyond that: System.out.print(arr); isn't doing what you expect it to do - to learn how to print arrays correctly, see this.
As we don't know the number of lines in a file, we can start by storing each line into an ArrayList (of String[]) and then convert it into a 2D array, e.g.:
List<String[]> lines = new ArrayList<>();
while (fileScanner.hasNext()) {
String line = fileScanner.nextLine();
String temp[] = line.split(" ");
lines.add(temp);
}
Now, convert it into an array:
String[][] array = new String[lines.size()][];
for(int i=0 ; i<lines.size() ; i++){
array[i] = lines.get(i);
}
I hevent seen where you have really used your add and makeString methods, and what is the role of the theList variable.
Also, could you please send your file Content.
any way:
If this is your calling to the add method: theList.add(temp[0]); that means that you are inside an Extended class structure that you have not shown it. but Any way you have not used it to fill the 2d Array in the for loop
the Code here is also error: you insert the same element temp[i] in every line !!!!
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = temp[i];
System.out.print(arr);
}
}
You can use a dynamic structure like ArrayList to fill the Elements...
Related
I have a List called listTeams which comprises of Strings. I need to generate all unique combinations of these strings and store them in another ArrayList called lines. I've tried the following but the results are not desirable:
for(int i=0; i<listTeams.size();i++){
for(int j=1;j<listTeams.size();j++){
if (listTeams.get(j).equals(listTeams.get(i)))
continue;
for(int k=2;k<listTeams.size();k++){
if (listTeams.get(k).equals(listTeams.get(i)) || listTeams.get(k).equals(listTeams.get(j)))
continue;
String str = listTeams.get(i)+listTeams.get(j)+listTeams.get(k);
lines.put(str,new ArrayList<String>());
}
}
}
Here's the original list : {"A","B","C","D"}
What I am getting is
a_b_c
a_b_d
a_c_d
a_d_c
b_c_d
b_d_c
c_b_d
d_b_c
What I desire is:
a_b_c
a_b_d
a_c_d
b_c_d
for(int i=0; i<listTeams.size();i++){
for(int j=i+1;j<listTeams.size();j++){
for(int k=j+1;k<listTeams.size();k++){
String str = listTeams.get(i)+listTeams.get(j)+listTeams.get(k);
lines.put(str,new ArrayList<String>());
}
}
}
You need to modify your for loops like this:
for (int j = i;
and
for (int k = j;
So that only unique combinations appear
As #Berger said, the following code is working as you expect.
for (int i = 0; i < listTeams.size(); i++) {
for (int j = i+1; j < listTeams.size(); j++) {
if (listTeams.get(j).equals(listTeams.get(i)))
continue;
for (int k = j+1; k < listTeams.size(); k++) {
if (listTeams.get(k).equals(listTeams.get(i)) || listTeams.get(k).equals(listTeams.get(j)))
continue;
String str = listTeams.get(i) + listTeams.get(j) + listTeams.get(k);
lines.add(str);
}
}
}
I am completely new to programming. Can you give me some tips on how to improve my code?
The problem was:
Given an array of strings, return a new array without the strings that are equal to the target string. One approach is to count the occurrences of the target string, make a new array of the correct length, and then copy over the correct strings.
And my code:
public String[] wordsWithout(String[] words, String target) {
int numberOfTargets = 0;
for (int i = 0; i < words.length; i++){
if ( words[i].equals(target) ) numberOfTargets++;
}
String[] result = new String[words.length - numberOfTargets];
for (int i = 0; i < words.length - numberOfTargets; i++){ // 1
result[i] = "0"; // 1
} // 1
for (int i = 0; i < words.length; i++){
if ( !words[i].equals(target) ){
int j = 0; // 2
while ( !result[j].equals("0") ){ // 2
j++; // 2
} // 2
result[j] = words[i];
}
}
return result;
}
Example of how code works:
wordsWithout(["aa", "ab", "ac", "aa"], "aa") → ["ab", "ac"]
I know that new array of ints is filled by zeros dy default. What about new array of Strings? I had to artificially fill it by zeros in part marked as //1, so that I could "scroll" to the right element, when I have to add elements to my new array in part marked as //2.
My code seems to be kind of awkward. Are there any standard methods or general ways to improve my code?
You don't need to set each element to "0".
Just do this:
public static String[] wordsWithout(String[] words, String target) {
int numberOfTargets = 0;
for (int i = 0; i < words.length; i++){
if ( words[i].equals(target) ) numberOfTargets++;
}
String[] result = new String[words.length - numberOfTargets];
int j =0; // for indices of result
for (int i = 0; i < words.length; i++){
if (!words[i].equals(target) ){
result[j++] = words[i];
}
}
return result;
}
Looks like your code could be simplified a lot by just using an ArrayList.
public String[] wordsWithout(String[] words, String target)
{
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < words.length; ++i)
{
if(!words[i].equals(target))
{
list.add(words[i]);
}
}
return list.toArray(new String[0]);
}
Basically instead of calculating the size of the target array and initialising it, you use a list (which is variable in size), put in all the elements you need, and then create a new array from it.
Unrelated to that, please don't invent your own values ("0") to describe a null value - there's a dedicated keyword, null, for that.
Use
for (String s : words) {
if (s.equals(target))
numberOfTargets++;
}
This might be a bit simpler. Using the split string method allows you to create an array with each value separated by white space.
public String[] wordsWithout(String[] words, String target) {
String newStr = "";
for (int i = 0; i < words.length; i++){
if (words[i].equals(target))
continue;
newStr = newStr + words[i] +" ";
}
return newStr.split(" ");
}
I tried finding this problem on this site, and the closest similar thread was this:
Can't figure out why im getting null values in my array print statement
Basically, I have an instance variable array of Strings taking words from a dictionary.txt file whenever its method is called (I have a separate main method). I have it set up to create a new array with double the capacity whenever it reaches its limit:
public String[] lengthN (int n) {
/*String[] output = new String[1000];*/
int i = 0;
while (input.hasNext()) {
String word = input.next();
if (i == output.length) {
increaseSize();
}
if (word.length() != n) {
}
if (word.length() == n) {
output[i] = word;
/*System.out.println(output[i]);
System.out.println(i);*/
i++;
}
}
for (int j = 0; j < output.length; j++) {
System.out.println(output[j]); //for testing purposes,returns random null values
}
return output;
}
public void increaseSize() {
String[] temp = new String[output.length + 1000];
for (int i = 0; i < output.length; i++) {
temp[i] = output[i];
output = temp;
}
}
Thankfully, it actually runs and prints out this list. However, in addition to these words, it appears as though large chunks of my list are replaced with null values.
The output itself is too long to post here (with >10000 elements or so), but essentially it is along the lines of
aardvark
null
null
null
null
//lots of null values dispersed throughout
vindicate
vineyards
vintagers
null
null
null
null
If anyone could help point me to a way to fix this problem, I'd be incredibly appreciative! (Apologies if I didn't explain well, first time posting here).
Here:
public void increaseSize() {
String[] temp = new String[output.length + 1000];
for (int i = 0; i < output.length; i++) {
temp[i] = output[i];
output = temp; // <-- here
}
}
you are setting the output array variable to the temp array inside your loop. On subsequent iterations through the loop, output and temp are referencing the same array, so temp[i] = output[i] does nothing. Presumably you meant something like this:
public void increaseSize() {
String[] temp = new String[output.length + 1000];
for (int i = 0; i < output.length; i++) {
temp[i] = output[i];
}
// Once the loop is finished, and the whole contents have been copied, use the `temp` array as the new `output`.
output = temp;
}
That should work pretty much the same as just having:
output = Arrays.copyOf(output, output.length+1000);
I am writing a really simple program which automatically extends the array when the user reaches the limit of the current array.
The problem is that I am getting a java.lang.ArrayIndexOutOfBoundsException when I run my PrintList method and I really don't know why. It's working perfectly if I use a random number, which is bigger than the array (e.g. 500), but if I use
for (int i = 0; i < stringArray.length; i++)
or
for (int i = 0; i <= stringArray.length; i++)
I get a nasty exception. How do I deal with this and why am I getting it in the first place?
Thanks a lot for your help!
Here's the source code of my program:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int index = 0;
String[] randomString = new String[1];
while (index <= randomString.length) {
out.println("Enter your string");
String input = keyboard.next();
randomString[index] = input;
PrintArray(randomString);
index++;
if (index >= randomString.length) {
ExtendArray(randomString);
continue;
}
}
}
public static void ExtendArray(String[] stringArray) {
String[] secondArray = new String[stringArray.length * 2];
// Copy first array into second array
for (int i = 0; i < stringArray.length; i++) {
stringArray[i] = secondArray[i];
stringArray = secondArray;
}
}
public static void PrintArray(String[] stringArray) {
for (int i = 0; i < stringArray.length; i++) {
out.println(" " + stringArray[i]);
}
}
Java does not work in the methods you are trying to employ. Everything in Java is passed by value, unless it is a data point in an object. What you are trying to employ is a pass by reference, which is not possible in Java.
What you are trying to do is an already existing data structure called a Vector: http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html
I would suggest doing this: (not sure if it will work properly, as my current PC doesn't have dev tools):
public static String[] ExtendArray(String[] stringArray) {
String[] secondArray = new String[stringArray.length * 2];
// Copy first array into second array
for (int i = 0; i < stringArray.length; i++) {
secondArray[i] = stringArray[i];
}
return secondArray;
}
then calling it like so in main:
randomString = ExtendArray(randomString);
Relating to vectors, this is how it works in a Vector class:
public void incrementCount(int count){
int increment = (count * 2);
Object newElementData [] = new Object[increment];
for(int i = 0; i < count; i++)
{
newElementData[i] = elementData[i];
}
elementData = new Object[increment];
elementData = newElementData;
}
In this case, elementData is the original array, newElementData is a temp array that acts to up the bounds.
You cant get error on your PrintArray method, you get the error on the line before!
randomString[index] = input;
Because if you do this
index <= randomString.length
The last iteration is out of bounds, String of length 10 has values on 0-9. You have to change the while cycle to
index < randomString.length
Also your ExtendArray method is NOT functional!
You are supposed to swap out the randomString array for a new array with double length. You create a new array and copy the contents of the old one to the new one, but don't do anything with the new array.
I suppose you want the ExtendArray method to return the new array, and set the randomString variable to be the new array.
You need to return your second array from ExtendArray function:
public static String[] ExtendArray(String[] stringArray) {
String[] secondArray = new String[stringArray.length * 2];
// Copy first array into second array
for (int i = 0; i <= stringArray.length; i++) {
stringArray[i] = secondArray[i];
}
return secondArray;
}
and in your main:
randomString = ExtendArray(randomString);
also your while condition should be:
while (index < randomString.length)
I want to compare two arrays and store the difference in another array
For example the two arrays might be
String[] a1 = { "cat" , "dog" };
String[] a2 = { "cat" , "rabbit" };
The resultant array would be like this
{ "rabbit" }
I use this code, but it does not work
int n = 0;
for (int k = 0; k <= temp.length; k++)
{
for (int u = 0; u <= origenal.length; u++)
{
if (temp[k] != origenal[u] && origenal[u] != temp[k])
{
temp2[n] = temp[k];
System.out.println(temp[u]);
n++;
}
}
}
This should do the trick.
String[] result = new String[100];
Int k = 0;
Boolean test = true;
for(i=0; i < a1.length; i++){
for(j=0; j < a2.length; j++){
if(a2[i].equals(a1[i])) continue;
test = false
}
if(test == false) result[k++] = a1[i];
}
I think that this may be what you are looking for. Note that it will only add to the third 'array' if the value exist in second array but not in first. In your example only rabbit will be stored, not dog (even though dog does not exist in both). This example could possibly be shortened but I wanted to keep it like this so it is easier to see what is going on.
First import:
import java.util.ArrayList;
import java.util.List;
Then do the following to populate and analyze the arrays
String a1[] = new String[]{"cat" , "dog"}; // Initialize array1
String a2[] = new String[]{"cat" , "rabbit"}; // Initialize array2
List<String> tempList = new ArrayList<String>();
for(int i = 0; i < a2.length; i++)
{
boolean foundString = false; // To be able to track if the string was found in both arrays
for(int j = 0; j < a1.length; j++)
{
if(a1[j].equals(a2[i]))
{
foundString = true;
break; // If it exist in both arrays there is no need to look further
}
}
if(!foundString) // If the same is not found in both..
tempList.add(a2[i]); // .. add to temporary list
}
tempList will now contain 'rabbit' as according to the specification. If you necessary need it to be a third array you can convert it to that quite simply by doing the following:
String a3[] = tempList.toArray(new String[0]); // a3 will now contain rabbit
To print the content of either the List or Array do:
// Print the content of List tempList
for(int i = 0; i < tempList.size(); i++)
{
System.out.println(tempList.get(i));
}
// Print the content of Array a3
for(int i = 0; i < a3.length; i++)
{
System.out.println(a3[i]);
}