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 9 years ago.
Improve this question
I need a program that expands a string into single lines.
Operators "\|" and "," delimit colums.
IN
a10,a2|||||f4|g5|h107||j1|k13,k3||||
OUT
a10|||||f4|g5|h107||j1|k13|
a10|||||f4|g5|h107||j1|k3|
a2|||||f4|g5|h107||j1|k13|
a2|||||f4|g5|h107||j1|k3|
import java.io.*;
public class CitesteLinii{
static String[] expandedLine = null;
static String[][] lineToExpand = null;
static int N = 0;
static String toLine() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i< N; i++) {
if (i>0) {
sb.append("|");
}
String[] list = expandedLine;
for (int pi = 0; pi <list.length;pi++) {
if (pi>0) {
sb.append(",");
}
sb.append(list[pi]);
}
}
return sb.toString();
}
static void expandLine(int i) {
if (i == N) {
System.out.print(toLine());
}
else {
String[] v = lineToExpand[i];
if (v == null || v.length == 0) {
expandedLine[i] = "";
expandLine(i + 1);
} else {
for (int p = 0; p < v.length; p++) {
expandedLine[i]=v[p];
expandLine(i + 1);
}
}
}
}
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new FileReader(new File("in.txt")));
try {
String line = in.readLine();
while (line!=null) {
String[] parts = line.split("\\|");
N= parts.length;
lineToExpand = new String[N][];
for (int ai = 0; ai < N; ai++) {
String[] v = parts[ai].split(",");
System.out.println(parts[ai]+' ');
lineToExpand[ai] = v;
}
expandLine(0);
line = in.readLine();
}
}
finally {
in.close();
}
}
}
expandedLine is not initialised anywhere (except for null). Thus, the access to the elements yields a null pointer exception.
Adding to #Howard explanation .. you need to initialize the expandedLine array before you add anything to it . .so you must do something like
String[] expandedLine = new String[100]; before using expandedLine[i]=v[p]; The number 100 inside the new String[..] statment defined the size of the array, you need to decide
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
The homework requires reading two file and entering the information of students into two separate ArrayLists. Then I need to perform 2 functions: combine the two lists and sort the combined list.
public abstract class Tools {
public static ArrayList<JUPASStudent> readJUPASFile(String f) throws Exception {
ArrayList<JUPASStudent> jList = new ArrayList<JUPASStudent>();
BufferedReader readbuffer = null;
readbuffer = new BufferedReader(new FileReader(f));
String strRead;
while ((strRead = readbuffer.readLine()) != null) {
String splitarray[] = strRead.split("/t");
String firstentry = splitarray[0];
String secondentry = splitarray[1];
JUPASStudent x = new JUPASStudent(firstentry, Double.parseDouble(secondentry));
jList.add(x);
}
readbuffer.close();
return jList;
}
public static ArrayList<NonJUPASStudent> readNonJUPASFile(String f) throws Exception {
ArrayList<NonJUPASStudent> njList = new ArrayList<NonJUPASStudent>();
BufferedReader readbuffer = null;
readbuffer = new BufferedReader(new FileReader(f));
String strRead;
while ((strRead = readbuffer.readLine()) != null) {
String splitarray[] = strRead.split("/t");
String firstentry = splitarray[0];
String secondentry = splitarray[1];
NonJUPASStudent x = new NonJUPASStudent(firstentry, Double.parseDouble(secondentry));
njList.add(x);
}
readbuffer.close();
return njList;
}
public static ArrayList<Student> combineArrayList(ArrayList<JUPASStudent> S1, ArrayList<NonJUPASStudent> S2) {
ArrayList<Student> sList = new ArrayList<Student>();
for (int i = 0; i < S1.size(); i++)
sList.add(S1.get(i));
for (int i = 0; i < S2.size(); i++)
sList.add(S2.get(i));
return sList;
}
public static ArrayList<Student> sort(ArrayList<Student> s){
for (int i = 0; i < s.size()-1; i++) {
for (int j = 0; i < s.size()-i-1; j++) {
if (s.get(j).getResult() > s.get(j+1).getResult()) {
Student Temp = s.get(j);
s.set(j, s.get(j+1));
s.set(j+1, Temp);
}
}
}
return s;
}
}
However, I keep getting "Index 1 out of bounds for length 1"
In the inner loop you're defining a constraint to the wrong counter. Instead of :
for (int j = 0; i < s.size()-i-1; j++)
there should be:
for (int j = 0; j < s.size()-i-1; j++)
In package java.util, we can :
Collections.sort(List); // to sort list, ex:
Collections.sort(Arrays.asList(13, 4));
Collections.addAll(Collection c, T... elements); // to join list, ex :
Collections.addAll(Arrays.asList(13, 4), Arrays.asList(3,4,5));
So you don't need to write your own function anymore.
The issue you are facing might be in the below line.
in method readNonJUPASFile and readJUPASFile
String secondentry = splitarray[1];
You are splitting the String based on /t. If you are expecting to split it based on tab you should be giving \t. If your line does not contain /t as you have given you will probably get a ArrayIndexOutOfBoundsException. You should check the length before assigning the variable like
if (splitarray.length > 1) {
String firstentry = splitarray[0];
String secondentry = splitarray[1];
}
Can you add few system.out statements. It will help you see where the error. I suspect data from file.
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 6 years ago.
Improve this question
My user input is
\home\me\cs1
\usr\share
\var\log
\usr\local\jdk1.6.0\jre\lib
and I need to sort these pathnames so that the output is in the correct lexographic order. However they are first sorted by length which is the number of slashes in each string. The path names are stored in an arraylist of strings. I attempting to do this without the use of collections,comparator or arrays. Would this be possible with the use of ArrayList?
the output should be:
\usr\share
\var\log
\home\me\cs1
\usr\local\jdk1.6.0\jre\lib
This is my code so far:
import java.util.ArrayList;
import java.util.Scanner;
public class FileName
{
private ArrayList<String> pathNames;
public FileName()
{
pathNames = new ArrayList<String>();
}
public void printPaths()
{
for(int i = 0; i < pathNames.size(); i++)
{
System.out.println(pathNames.get(i));
}
}
public int pathLength(String path)
{
int count = 0;
String slash = "\\";
for(int i = 0; i < path.length(); i++)
{
if(path.substring(i,i + 1).equals(slash))
{
count++;
}
}
return count;
}
public void sort()
{
pathNames = mergeSort(pathNames);
}
public ArrayList<String> mergeSort(ArrayList<String> paths)
{
if(paths.size() == 1)
{
return paths;
}
else
{
ArrayList<String> left = new ArrayList<String>();
ArrayList<String> right = new ArrayList<String>();
int middle = paths.size() / 2;
for(int i = 0; i < middle; i++)
{
left.add(paths.get(i));
}
for(int i = middle; i < paths.size(); i++)
{
right.add(paths.get(i));
}
right = mergeSort(left);
left = mergeSort(left);
merge(left, right, paths);
}
return paths;
}
public void merge(ArrayList<String> left, ArrayList<String> right, ArrayList<String> paths)
{
int leftNum = 0;
int rightNum = 0;
int pathsNum = 0;
while (leftNum < left.size() && rightNum < right.size())
{
if ((left.get(leftNum).compareTo(right.get(rightNum)))<0)
{
paths.set(pathsNum, left.get(leftNum));
leftNum++;
}
else
{
paths.set(pathsNum, right.get(rightNum));
rightNum++;
}
pathsNum++;
}
ArrayList<String>rest;
int restNum;
if (leftNum >= left.size())
{
rest = right;
restNum = rightNum;
}
else
{
rest = left;
restNum = leftNum;
}
for (int i = restNum; i < rest.size(); i++)
{
paths.set(pathsNum, rest.get(i));
pathsNum++;
}
}
public void readInput()
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter a list of path names.(press enter after each path name, and type \"stop\" once you are finished.");
String termination = "stop";
String in = input.nextLine();
boolean reading = true;
while(reading)
{
pathNames.add(in);
if(in.equals(termination))
{
reading = false;
return;
}
in = input.nextLine();
}
}
}
This is my main method.
public class FileNamePrgm
{
public static void main(String [] args)
{
FileName paths = new FileName();
paths.readInput();
paths.sort();
}
}
You have a typo:
right = mergeSort(left);
Should be
right = mergeSort(right);
Also you need to add in = input.nextLine(); once more inside the while loop. Currently you are reading only one line from the input and checking it over and over again.
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
Here is the homework:
Write a method called printStrings that accepts a String and a
number of repetitions as parameters and prints that String the given
number of times with a space after each time.
printStrings("abc", 5);
will print the following output:
abc abc abc abc abc
This is what I have tried:
public class Apples {
public static String printStrings(String a) {
return (int i = 1; i <= 5; i++) {
System.out.print(a);
}
public static void main(String[] args) {
System.out.println(printStrings("abc"));
}
}
}
Really don't know what to do.
public void printStrings(String a, int b) {
String printString = "";
for (int i = 0; i<b; i++){
printString = printString+" "+a;
}
System.out.println(printString);
}
This would work, and it wouldnt put a space at the end:
private static void printStrings(String str, int num) {
for (int i = 0; i < num; i++) {
System.out.print(str + (i == num - 1 ? "" : " "));
}
}
public static String printStrings(String a, int count) {
String result = "";
for (int i = 0 ; i < count ; i++)
{
result = result + a;
if (i != (count-1))
result = result + " ";
}
return result;
}
public static void main(String[] args) {
System.out.println(printStrings("abc", 5));
}
Modifying your code a little
public static void main(String[] args) {
System.out.println(printStrings("abc", 5));
}
public static String printStrings(String a, int numOfTimes) {
StringBuilder sb = new StringBuilder(""); // StringBuilder is better than concatenating Strings
for (int i = 1; i <= numOfTimes; i++) {
// System.out.println(sb);
sb.append(a); // append String
sb.append(" "); // append space
}
sb.replace(sb.length()-1, sb.length(), ""); // replace last space
System.out.println(sb.length());
return sb.toString(); // return String representation of StringBuilder sb
}
O/P :
19
abc abc abc abc abc
public static String printStrings(String a,int b) {
String s = "";
for(int i = 1; i <= b; i++) {
s=s+a+" ";
}
return s;
}
public static void main(String[] args) {
System.out.println(printStrings("abc",5));
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have written a algorithm that searches for a word in dictionary. But it searches only with 1 or 2 letters of a specified length of word.
Ex search:-
A**
result should be:-
Aid, Aim,
I have used linear search algorithm to find the words that matches my criteria. But i want to know if Binary search can be used instead of linear search? if so then can any one please give me some hint about it
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Cse221LabAssignment1 {
/**
* #param args the command line arguments
*/
public static final String wordListFileName = "E:\\BRAC UNI\\cse lab\\cse221 lab\\cse221LabAssignment1\\src\\cse221labassignment1\\WordList.txt";
public static final String searchListFileName = "E:\\BRAC UNI\\cse lab\\cse221 lab\\cse221LabAssignment1\\src\\cse221labassignment1\\SearchList.txt";
public static void main(String[] args) {
// TODO code application logic here
String wordList, searchList;
wordList = ReadFile(wordListFileName); //Reading wordlist
searchList = ReadFile(searchListFileName); //Reading searchList
String[] w = wordList.split("\\,"); //Spliting wordlist and putting it into an array
String[] s = searchList.split("\\,"); //Spliting searchList and putting it into an array
for (int c = 0; c < s.length; c++) { //iterating through the searchList array
// String [] refinedList=new String[w.length]; //array containing the list of words that matches with the lenght of search word.
// int refinedCounter=0; //counter for the refinedList array
for (int i = 0; i < w.length; i++) { //iterating through the wordList array
if (s[c].length() == w[i].length()) {
// refinedList[refinedCounter]=w[i];
// refinedCounter++;
if (LetterMatch(w[i], s[c])) {
System.out.print(w[i]);
if (i < w.length - 1) {
System.out.print(",");
} else {
System.out.println(";");
}
}
}
}
}
}
public static String ReadFile(String fileName) {
Scanner k = null;
try {
k = new Scanner(new File(fileName));
} catch (FileNotFoundException ex) {
System.out.println(ex);
}
String rt = k.nextLine();
while (k.hasNextLine()) {
rt = rt + "," + k.nextLine(); //Words seperated by Comma
}
return rt;
}
public static boolean LetterMatch(String m, String s) {
char[] letters = m.toCharArray();
char[] searchLetters = s.toCharArray();
boolean match = false;
int c = 0;
for (; c < s.length(); c++) {
if (searchLetters[c] != '*') {
if (searchLetters[c] == letters[c]) {
match = true;
} else {
match = false;
}
}
}
if (c != s.length()) {
return false;
} else {
return match;
}
}
}
I would recommend using an alternative data structure to help you do some of the heavy lifting. Try a radix tree http://en.wikipedia.org/wiki/Radix_tree. This will let you complete the words as you traverse the tree opposed to having to do linear list searches.
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 9 years ago.
Improve this question
I'm using Java (NetBeans 6.8) to make an anagram game. The code runs without no errors, but when I try the game, I do not receive any value from list/anagramlist (it is made to return 'Error - Null Result'). Is there a problem with my code? I think it is probably in WordList.java, as that should be adding the values to the list. Maybe I am calling the Void wrongly?
Note: This is a compilation of my code snippets
Here is my code:
//This is the code to add the word to the word list, and make the anagram
//and add it to the anagram list. This code is in the game creator
//(GameCreator.java)
String toadd = (jTextField1.getText() + ",");
WordList wordlist = new WordList();
AnagramMaker anagmaker = new AnagramMaker();
wordlist.addword(toadd);
wordlist.addanag(anagmaker.makeanagram(toadd, toadd.length()));
//This is the code in the anagram maker (AnagramMaker.java) to make the anagram
char[] usedpos;
public String makeanagram(String toanagram, int length){
usedpos = null;
String anagram = "";
Random rnd = new Random();
if(usedpos == null)
{
int rnum = rnd.nextInt(length);
usedpos = (Integer.toString(rnum)).toCharArray();
anagram += Character.toString(toanagram.toCharArray()[rnum]);
}
else
{
for(int i = 0; i < length; ++i)
{
int rnum = rnd.nextInt(length);
for(int pos = 0; pos < usedpos.length; ++pos)
{
if(Character.toString(usedpos[pos]).equals(Integer.toString(rnum)))
{
i-= 1;
pos = 0;
}
else
{
anagram += Character.toString(toanagram.toCharArray()[rnum]);
usedpos = (new String(usedpos) + Integer.toString(rnum)).toCharArray();
pos = 0;
}
}
}
}
return anagram;
//This is the code in the word list (WordList.java) to receive and add the words
//and to allow the user to get words too.
char[] list = null;
char[] anagramlist = null;
public String getword(int num){
String word = "";
int wordcount = 0;
int endpos = 0;
if(list == null)
{
return "Error - Null Result";
}
else
{
for(int i = 0; i != -1; ++i)
{
if((Character.toString(list[i]).equals(",")))
{
wordcount += 1;
if(wordcount == (num - 1))
{
for(int pos = list[i]; pos > endpos; ++pos)
{
word += Character.toString(list[pos]);
if(Character.toString(list[pos + 1]).equals(","))
{
endpos = pos + 1;
i = -1;
}
}
}
}
}
return word;
}
}
public String getanagram(int num){
String anagram = "";
int wordcount = 0;
int endpos = 0;
if(list == null)
{
return "Error - Null Result";
}
else
{
for(int i = 0; i != -1; ++i)
{
if((Character.toString(anagramlist[i]).equals(",")))
{
wordcount += 1;
if(wordcount == (num - 1))
{
for(int pos = anagramlist[i]; pos > endpos; ++pos)
{
anagram += Character.toString(anagramlist[pos]);
if(Character.toString(anagramlist[pos + 1]).equals(","))
{
endpos = pos + 1;
i = -1;
}
}
}
}
}
}
return anagram;
}
public void addword(String word){
if(list != null)
{
list = (new String(list) + word).toCharArray();
}
else
{
list = word.toCharArray();
}
}
public void addanag(String anagram){
if(anagramlist != null)
{
anagramlist = (new String(anagramlist) + anagram).toCharArray();
}
else
{
anagramlist = anagram.toCharArray();
}
}
//This is the code in the game (Game.java)
int length;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText(null);
jLabel2.setText(null);
newword();
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
jLabel2.setText("The answer is: " + answer);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jTextField1.getText().equals(answer))
{
jLabel2.setText("Correct answer");
}
else
{
jLabel2.setText("Incorrect answer, try again");
}
}
public void newword(){
jTextField1.setText(null);
jLabel1.setText(null);
jLabel2.setText(null);
Random rnd = new Random();
int rnum = rnd.nextInt(length);
answer = wordlist.getword(rnum);
anagram = wordlist.getanagram(rnum);
jLabel1.setText("The anagram is: " + anagram + ". Guess the original word");
}
public void getlength(int lng){
length = lng;
newword();
}
Cool, add a } after return anagram; in makeanagram method
It's because the values are not being inputted into the other classes and therefore your function is returning a null result