Storing nested lists - java

I really need some assistance so I'm trying so freaking hard to store a str in a list inside a list and this will not freaking work. The code I have written makes perfect sense to me. Can someone please give me some guidance here. I'm desperate. I continously get errors on at line 30 myArrayList.get(index).add(newClassObj);
suggesting >>
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at myClass.main(myClass.java:30)
public class myCLass {
public static void main(String[] args)
{
ArrayList<LinkedList<myCLass>>
myArrayList = new ArrayList<LinkedList<MyClass>>(26);
inFile file = new inFile();
file.inFile("myfile.txt");
while(inFile.hasNext())
{
String str = inFile.next();
char ch = str.toUpperCase().charAt(0);
char ch2 = 'A';
int index = (int)ch - (int)ch2;
for (int i = 0; i < 26; i++)
myArrayList.add(new LinkedList<MyClass>());
myClass newClassObj = new myClass(str);
myArrayList.get(index).add(newClassObj);
}
}
}

Before you can call myArrayList.get(index).add(newClassObj);, you must make sure that index < myArrayList.size(). Otherwise you'll get an index out of bounds exception.
Your myArrayList's size is 0, since you never add anything to it. Initializing the capacity to 26 doesn't add 26 elements to the list. It doesn't add any elements to the list.
If you wish your list to have 26 elements, you should initialize it properly :
for (int i = 0; i < 26; i++)
myArrayList.add(new LinkedList<MyClass>());

It doesn't look like you're ever making your lists. You have a list that has 26 slots, but you're never filling those slots with a list.
I don't know what this infile is so I just used java.util.Scanner for testing. I also don't see this original MyClass class, so I'm just adding the Strings. Yours is a little different, but the algorithm is the same.
import java.util.*;
import java.io.*;
public class MyClass {
public static void main(String[] args) throws Exception {
ArrayList<LinkedList<String>> list = new ArrayList<>(26);
for(int i = 0; i < 26; i++) {
list.add(new LinkedList<String>());
}
Scanner sc = new Scanner(new File("words.txt"));
while(sc.hasNext()) {
String next = sc.next();
char c = next.toUpperCase().charAt(0);
int index = c - 'A';
list.get(index).add(next);
}
// let's test it by looking at all the H words
System.out.println(list.get(7));
}
}
Result:
C:\files\j>javac MyClass.java
C:\files\j>java MyClass
[have, he, his, her, him, how]

Related

Trying to remove the 5th name entered from my array. I'm getting a cannot find symbol error and I can't figure out why

import java.util.Scanner;
public class Assignment6APt2 {
public static void main(String[] args) {
int n = 10;
Scanner scan = new Scanner(System.in);
System.out.println("Enter 10 names: ");
String [] names = new String[n];
for (int i = 0; i < names.length; i++){
names[i] = scan.nextLine();
}
names.remove(4);
arrayMethod(names);
}
private static void arrayMethod(String[] names)
{
for (String a : names)
{
System.out.printf( "%s",a);
}
}
}
There isn't a remove method for arrays, and this operation really doesn't make sense anyway. What does it even mean to "remove" an item from a fixed-size array?
The closest thing you can do is set array index 5 to null, which is just a simple assignment. I'm not sure I recommend doing that, though. You probably want to either rethink doing that or just use a variable-size data structure.

addition of distinct substrings of multiple strings to a Treeset

Question - You are given n strings w1, w2, ......, wn. Let Si denote the set of strings formed by considering all unique substrings of the string wi. A substring is defined as a contiguous sequence of one or more characters in the string. More information on substrings can be found here. Let S = {S1 U S2 U .... Sn} .i.e S is a set of strings formed by considering all the unique strings in all sets S1, S2, ..... Sn
My approach - I am using a TreeSet and filling it directly rather than creating a list, a set, and a sorted list.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int cases = Integer.parseInt(in.nextLine());
String[] a = new String[cases];
int i, c;
//Adding directly to the Set prevents a larger list because you remove the duplicates
Set<String> set = new TreeSet<String>();
for( i = 0; i < cases; i++)
{
a[i] = in.nextLine();
for (c = 0; c < a[i].length(); c++)
{
for (i = 1; i <= a[i].length() - c; i++)
{
String sub = a[i].substring(c, c + i);
set.add(sub);
}
}
}
}
for input :
2
aab
aac
i got a runtime error :
Exception in thread "main" java.lang.NullPointerException
at Solution.main(Solution.java:32)
can anyone explain me why i am getting this runtime error , what should i do to avoid this null pointer exception and why did this occur in the first place? please help me if you can
We have a lot of memory nowadays. But even old days it was considered a bad practice to use the same variable for different purposes. Use each one for one purpose and it will be all right. Code is clear and undersatndable and no more unexplainable exceptions:
import java.io.StringReader;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(new StringReader("2\naab\naac\n"));
int cases = Integer.parseInt(in.nextLine());
String[] a = new String[cases];
//int i, c;
// Adding directly to the Set prevents a larger list because you remove
// the duplicates
Set<String> set = new TreeSet<String>();
for (int i = 0; i < cases; i++) {
a[i] = in.nextLine();
for (int c = 0; c < a[i].length(); c++) {
for (int ii = 1; ii <= a[i].length() - c; ii++) {
String sub = a[i].substring(c, c + ii);
set.add(sub);
}
}
}
System.out.println(set);
}
}
P.S. Homework - make name of variables meaningful and unforgetable.

removing duplicated words from an array

I am trying to remove duplicated words from an array, and I keep getting null values. I'm not allowed to use java sorting methods so I have to develop my own. Here's my code:
public class Duplicate{
public static void main(String[] args){
String[] test = {"a", "b", "abvc", "abccc", "a", "bbc", "ccc", "abc", "bbc"};
removeDuplicate(test);
}
public static String[] removeDuplicate(String[] words){
boolean [] isDuplicate = new boolean[words.length];
int i,j;
String[] tmp = new String[words.length];
for (i = 0; i < words.length ; i++){
if (isDuplicate[i])
continue;
for(j = 0; j < words.length ; j++){
if (words[i].equals(words[j])) {
isDuplicate[j] = true;
tmp[i] = words[i];
}
}
}
for(i=0;i<words.length;i++)
System.out.println(tmp[i]);
return tmp;
}
}
I tried doing
if(words == null)
words == "";
But it doesn't work. I also want to return the tmp array with a new size.
For example, test array length = 9, after removing the duplicates,I should get a new array with a length of 7.Thank you for your help.
EDIT:
result i get:
a
b
abvc
abccc
null
bbc
ccc
abc
null
You're getting nulls because the result array contains fewer words than the input array. However, you're constructing the arrays of the same length.
You don't have to sort to solve this problem. However, if you're not allowed to use the tools provided by java.utils, then this is either a poorly contrived test question or whomever told you not to use the Java utility classes is poorly informed.
You can solve without sorting by doing (assuming Java 1.5+):
public class Duplicate {
public static void main(String[] args) {
String[] test = {"a", "b", "abvc", "abccc", "a", "bbc", "ccc", "abc", "bbc"};
String[] deduped = removeDuplicate(test);
print(deduped);
}
public static String[] removeDuplicate(String[] words) {
Set<String> wordSet = new LinkedHashSet<String>();
for (String word : words) {
wordSet.add(word);
}
return wordSet.toArray(new String[wordSet.size()]);
}
public static void print(String[] words) {
for (String word : words) {
System.out.println(word);
}
}
}
The output will be:
a
b
abvc
abccc
bbc
ccc
abc
I would go for hashset to remove duplicates, it will remove duplicates since hash function for the same string will give same value, and duplicates will be eliminated. Then you can convert it to a string.
I would recommend doing this with a different approach. If you can use an ArrayList, why not just create one of those, and add the non-duplicate values to it, like this:
ArrayList<String> uniqueArrayList = new ArrayList<String>();
for(int i = 0; i < words.length; i++){
if(!uniqueArrayList.contains(words[i])){ // If the value isn't in the list already
uniqueArrayList.add(words[i]);
}
}
Now, you have an array list of all of your values without the duplicates. If you need to, you can work on converting that back to a regular array.
EDIT
I really think you should use the above option if you can, as there is no clean or decently efficient way to do this only using arrays. However, if you must, you can do something like this:
You can use the code you have to mark values as null if they are duplicates, and also create a counter to see how many unique values you have, like this:
int uniqueCounter = 0;
for(int i = 0; i < isDuplicate.length; i++){
if(!isDuplicate[i]){
uniqueCounter++;
}
}
Then, you can create a new array of the size of unique items, and loop through the words and add non-duplicate values.
String[] uniqueArray = new String[uniqueCounter];
int uniqueIndex = 0;
int wordsIndex = 0;
while(index < uniqueArray.length){
// Check if words index is not a duplicate
if(!isDuplicate[wordsIndex]){
// Add to array
uniqueArray[uniqueIndex] = words[wordsIndex];
uniqueIndex++; // Need to move to next spot in unique.
}
// Need to move to next spot in words
wordsIndex++;
}
Again, I HIGHLY recommend against something like this. It is very poor, and pains me to write, but for the sake of example on how it could be done using an array, you can try it.
I don't have the time to write functioning code, but I would reccomend to first sort the array using Arrays.sort(stringArray) and then loop throug the array coparing one string to the previous. Strings that match the previous one are duplicates.
Note: This method is probably not the fastest one and though only should be used on small arrays or in tasks where performance does not matter.
What about this approach?
public static String[] removeDuplicate(String[] words){
// remember which word is a duplicate
boolean[] isDuplicate = new boolean[words.length];
// and count them
int countDuplicate = 0;
for (int i = 0; i < words.length ; i++){
// only check "forward" because "backwards checked" duplicates have been marked yet
for(int j = i + 1; j < words.length ; j++){
if (words[i].equals(words[j])) {
isDuplicate[j] = true;
countDuplicate++;
}
}
}
// collect non-duplicate strings
String[] tmp = new String[words.length - countDuplicate];
int j = 0;
for (int i = 0; i < isDuplicate.length; i++) {
if (isDuplicate[i] == false) {
tmp[j] = words[i];
j++;
}
}
// and return them
return tmp;
}

How can I do this recursive search in java?

import java.util.*;
import java.io.*;
import java.io.CharArrayReader;
public class Program2 {
public static void main(String[] args) {
try {
String filename = args[0]; //reads command line argument 1 as filename
Scanner File = new Scanner(new File(filename)); //reads filename into program,and opens it for analysis
File.useDelimiter(System.getProperty("line.seperator"));
ArrayList<String> list = new ArrayList<>(); //creates an array list to store chars to transfer for reading from the file
while (File.hasNext()){
list.add(File.next());
}
File.close();
char[][] array1 = new char[10][20];
for (int i =0; i < list.size(); i++){
array1[i] = list.get(i).toCharArray();
}
} catch (FileNotFoundException e){
System.out.println("File is not found: " + e.getMessage() );//catches and sends out an error message
}
}
static int CharSearch(char[][] array1, char a, char b, char c){
for (int i =0 ; i < array1.length; i++){
for (int j =0; j < array1.length; j++){
while (a == 'A'){
return 1;
Hi all, so I have to make a program that reads in a file that is a 10x20 grid. The grid has letters A, B, C. All chars, in random order. What I need to do, is find a searching algorithm that checks for "groupings" of these letters.
Much like this much smaller version:
AABBACCA
CCABACBA
CCAAAABB
AAAACCCC
So see how there are 3 C groups, 2 B groups, and 3 A groups? (the groups can only be touching horizontally or vertically, not diagonally.)
I have to count that. I tried it, as can be seen on the bottom.
Also, I wanted to also make sure that the rest of my code makes sense and won't just pfft on me.
Thank you :)

List<String> ----> to int [ ] [ ] arr

Well I have been stumped as to the best way to do this, I have written the code to read in lines of code from txt files as List. I can then print specific parts or convert this to an array of objects. But, ultimately I would like to have just a 2d int array you can see often in C/C++. I am very green when it comes to java, having only started earlier this week. I have like it up until this point of making dynamic 2d arrays at run time. Can any of you suggest a good way to get to a 2d int array from where i am currently stuck. I was just about to convert it to a char array using 'toChar', then to take the (value#index-48) and store it in its corresponding spot, but that seems pretty ghetto to me.
====updated==========================
eh, thanks for all the replies, but I just figured out how to do it using doubles, so for anyone else, here you go. I would still rather have int, since I have already built my other matrixops classes using this type, but Double shouldn't be an issue i guess.
package uaa.cse215;
import java.io.*;
import java.util.*;
public class ReadMatrix {
private Double[][] A;
private Double[][] B;
private int count;
public int filedir(String matrix) throws Exception{
Double[][] Temp;
String[] arr;
BufferedReader rd = new BufferedReader(new FileReader(matrix));
String s;
List<String> textFile = new ArrayList<String>();
while ((s=rd.readLine())!=null) {
textFile.add(s);
}
String splitarray[] = textFile.get(0).split(" ");//run once to grab # cols
int rows = textFile.size();//number of rows
int cols = splitarray.length;//number of cols
Temp = new Double[rows][cols]; // now can initiate array
for (int i=0; i<rows; i++) {
s = textFile.get(i);
arr = s.split(" ");
for (int j=0; j<cols; j++) {
Temp[i][j] = Double.parseDouble(arr[j]);
}
}
count++;
if (count == 1){
A = Temp;
}
else
B = Temp;
rd.close();
return(1);
}
}
Please note that Java has the char data type which is a 16bit unsigned integer holding a UTF-16 code point. int is in Java always a signed 32 bit integer. So if you want a C like Arrays of chars representing the content of a String, you should use a char[][]
To convert the content of your List<String> into a 2d array you can use the following code:
char[][] twoDarray = new char[textFile.size()];
for(int i = 0; i < textFile.size(); i+)
{
twoDarray[i] = textFile.get(i).toCharArray();
}
The array twoDarray then contains all Strings each as a char array.
This line won't compile
splitarray[j] = textFile.get(i).split(" ");
as splitarray[j] is of type String and split returns an array of Strings
Do the following instead:
for(int row=0;row<textFile.size();row++){
String[] splitarray = textFile.get(row).split(" ");
for(int col=0;col<splitarray.length;col++){
tmp[row][col] = Integer.parse(splitarray[col]);
}
}
if the input matrix dimentions are dynamic or jagged you can use
List<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
to read numbers and than copy it to raw 2d array if you want.
java.util.Scanner has many handy methods for reading "typed" data from input
Here's an example reading file to 2D array
public static int[][] read2DArray(String fileName) throws FileNotFoundException {
Scanner sc = null;
List<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
int columnCount = 0;
int[][] arr = null;
try {
sc = new Scanner(new File(fileName));
while (sc.hasNextLine()) {
// Read line
String line = sc.nextLine();
// Split it
String[] nums = line.split(" ");
if (nums.length > columnCount) {
columnCount = nums.length;
}
// Convert to integers and add to list
list.add(new ArrayList<Integer>());
for (String n : nums) {
list.get(list.size() - 1).add(new Integer(n));
}
}
// Convert list to array
int rowCount = list.size();
arr = new int[rowCount][columnCount];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < list.get(i).size(); j++) {
arr[i][j] = list.get(i).get(j);
}
}
} finally {
if (sc != null) {
sc.close();
}
}
return arr;
}
Assuming your data file contains ascii-represented numbers that you want parsed into integers:
11 -9 13
12 55 102
1 1 1024
Then you can use the Integer(String s) constructor to parse your string objects.
Also, I suggest splitting each row only once. It won't matter much for small arrays, but the larger your inputs get, the more you'll needlessly recompute the splits.
An (untested) re-writing:
int tmp[][] = new int [rows][cols];
for(int i=0;i<rows;i++){
splitarray = textFile.get(i).split(" ");
for(int j=0;j<cols;j++){
tmp[i][j] = Integer(splitarray[j]);
}
}

Categories

Resources