How to compare against a null element in an array in java? - java

I have a program where I need to store the results in an arraylist:-
public class ReseedingDBRandomElements {
public static void main(String[] args){
try {
// getting the field Keyword from the csv
String csvfile="/Users/dray/Downloads/ReseedingDBRandomKeywords.csv";
BufferedReader br =new BufferedReader(new FileReader(csvfile));
StringTokenizer st = null;
String line="";
int linenumber=0;
int columnnumber;
// initializing the parameter for each column
int free = 0;
int free1 = 0;
// create the ArrayList
ArrayList<String> Keyword = new ArrayList<String>();
ArrayList<String> Alternate = new ArrayList<String>();
// reading through the csv file
while((line=br.readLine())!=null){
linenumber++;
columnnumber = 0;
st = new StringTokenizer(line,",");
while(st.hasMoreTokens()){
columnnumber++;
String token = st.nextToken();
if("Keyword".equals(token)){
free=columnnumber;
System.out.println("The value of free :"+free);
}else if ("Alternate".equals(token)){
free1=columnnumber;
System.out.println("The value of free1 :"+free1);
}
if(linenumber>1){
if (columnnumber==free)
{
Keyword.add(token);
}else if (columnnumber==free1){
Alternate.add(token);
}
}
}
}
// converting the keyword ArrayList to an array
String[] keyword = Keyword.toArray(new String[Keyword.size()]);
for(int i=0;i<keyword.length;i++){
System.out.println(" The value of the keyword is :"+keyword[i]);
}
// converting the alternate ArrayList to an array
String[] alternate = Alternate.toArray(new String[Alternate.size()]);
for(int i=0;i<alternate.length;i++){
System.out.println("The value of the alternate is :"+alternate[i]);
}
ArrayList<String> AlternateNew = new ArrayList<String>();
for(int i=1;i<keyword.length;i++){
if(keyword[i].equals(keyword[i-1])){
AlternateNew.add(alternate[i-1]);
}else if(!(keyword[i]==(keyword[i-1]))){
AlternateNew.add(alternate[i]);
}
}
String[] alternatenew = AlternateNew.toArray(new String[AlternateNew.size()]);
System.out.println("The length of the array is :"+alternatenew.length);
for(int i=0;i<alternatenew.length;i++){
System.out.println("the value of the alternatenew :"+alternatenew[i]);
}
}catch (Exception e){
System.out.println("there is an error :"+e);
}
}
}
The following is the csv file
Keyword,Alternate
ego kit,baby doll
ego kit,garage park
ego kit,random beats
galaxy tab,venus
galaxy tab,earth
galaxy tab,sun
What I am trying to do is compare elements and store it in an arraylist and display the results, but when last element is getting compared i.e 'galaxy tab' is getting compared to an empty field after last 'galaxy tab', it is not storing the previous result in the arraylist which is 'sun'
The following is the result of the program :
The value of the alternate is :baby doll
The value of the alternate is :garage park
The value of the alternate is :random beats
The value of the alternate is :venus
The value of the alternate is :earth
The last element is not getting stored in the arraylist.
Do not understand why? New to Java programming.

This section has a few problems also present throughout
AlternateNew.add(alternate[0]);
for(int i=1;i<keyword.length;i++){
if(keyword[i]==(keyword[i-1])){
AlternateNew.add(alternate[i]);
}else if(!(keyword[i]==(keyword[i-1]))){
AlternateNew.add(alternate[i]);
}
}
The naming convention in Java is to start with a lowercase letter for a variable name (unless it is a constant), which is why object AlternateNew is highlighted as if it were a class name.
The else if block tests the opposite of the same condition as its if. You could comment out if(!(keyword[i]==(keyword[i-1])), delete, or replace it with a more readable reminder comment, and the result would be the same.
AlternateNew.add(alternate[i]); happens regardless of this condition, in either branch of the if, so either remove the if statement entirely or fix some typo.
As for your actual [edit: original] question, I can't find anything wrong. Are you sure you didn't forget to save the csv file? I ran it using a text file and got output contrary to your post!

Related

Java .split() Array out of bounds

I keep getting this Array out of bounds error for the following code.
brock.txt = reflection program, routine, Arrow, snake game,
public static void main(String[] args) {
String filename = "brock.txt";
String line;
String [] cities = {};
int x = 0;
try {
BufferedReader eshread = new BufferedReader( new FileReader (filename));
line = "";
while ((line = eshread.readLine()) != null ) {
String[] store = line.split(",");
System.out.println(store[0]);
System.out.println(store[1]);
System.out.println(store[2]);
cities[x] = store[2]; //< keep getting an error here
x++;
}//end while loop
eshread.close();
}//end try
catch(IOException iox) {
System.out.println("failiure");
}//end catch
String [] cities = {} will make the array size to 0,when x is greater than 0 the error will occur,that's the reason,so you need to make cities a fixed size at first or use List to do it
You Must define the size of cities or use a list .
You initialized cities with an empty array({}), which means it has a length of 0(not an null, but an empty array). By using cities[0] you are expecting it has at least one element, which is not true.
To fix this, use an ArrayList<String> instead of a String array.
In agreement with the other comments. The issue is with the size of cities array which is being set to 0 and hence the issue for array out of bounds.
I tried the following code and it works if you want to work with a String array.
Else an ArrayList is a better solution if the size is not defined.
String [] cities = new String[10];

Java, trouble with making a double array of string from file

I have a class "car", having five parametres of car (str brand, str model, str colour, int power, int tank), and I have a .txt with five cars, written like that:
Toyota Supra Black 280 80
Ferrari F430 Red 510 95
Nissan GT-R White 600 71
Koenigsegg Agera White 940 80
Mazda RX-8 Red 231 62
I have to read this list from file and make an array of lines array (cars), while each car array is an array of 5 parametres, like:
Cars[car][parametres], and push it into a object of a class (should be a peace of cake, and i think i can handle this)
But i have no clue how to deal with array. Only thing i have now is reading from file:
void 123() {
String[] ImpData = null;
try {
String str;
BufferedReader br = new BufferedReader(new FileReader("imp.txt"));
while ((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
} catch (IOException exc) {
System.out.println("IO error!" + exc);
}
}
Any suggestions?
Create a list of Car object and adding each line into the list as 1 Car object each.
ArrayList<Car> list = new ArrayList<Car>();
while ((str = br.readLine()) != null) { //Not checking your loop
String[] tok = str.split(" "); //str holds all car information
list.add(new Car(tok[0], tok[1], tok[2], tok[3], tok[4]));
}
Assuming your Car class has a constructor which accepts the 5 arguments.
Edit: (To fit requirement of using Array)
When you use array, you have to pre-allocate a fixed array length first. Using array is not suitable for storing data from files because there can exist any number of lines of data. Anyway, to answer your question on using array:
String[][] data = new String[numRecords][5]; //numRecords equals total car objects
int x=0;
while ((str = br.readLine()) != null) { //Not checking your loop
String[] tok = str.split(" "); //str holds all car information
data[x] = tok; //Assign entire row of tok into data
x++;
}
Once again, I seriously do not recommend reading data file into an array. If you really have to do so, you can pre-determine number of records in the text file first, then set the array size accordingly.
Side note: 2D arrays are also not a suitable data structure for storing data such as a car object with its own attributes.
You want a two dimensional array. However, note that the array size must be known in advance and you don't know how many lines are in the file. So, first read everything into a secondary linked list data structure (you could also read the file twice, this is not efficient). Now you have all the strings, make a two dimensional array and then split each string into an array of tokens, using the " " delimiter. If you want to treat the tokens as integers and strings, you can use an array of Object instead and store Integer, String, etc. Off the top of my head, something like this follows - also note in your post, you can't start a method with numbers :)
String[] ImpData = null;
try {
String str;
List<String> allStrings = new LinkedList<String>();
BufferedReader br = new BufferedReader(new FileReader("imp.txt"));
while ((str = br.readLine()) != null) {
allStrings.add(str);
}
br.close();
String[][] ImpData = new String[allStrings.size()][];
for(int i=0; i<allStrings.size();i++){
ImpData[i] = allStrings.get(i).split(" ");
}
} catch (IOException exc) {
System.out.println("IO error!" + exc);
}
I think what you are looking for is a 2-dimensional array.
The first dimension is the index for the car, the second are the 5 pieces that make it up. It looks like this: (not actual language, just a guide to build it.)
array is car[int][string, string, string, int, int]
car[0][Toyota,Supra,Black,280,80]
car[1][Ferrari,F430,Red,510,95]
So, referencing car[1] will tell you all about that car.
That's one idea, anyway...
for Car
class Car {
public String brand, model, colour;
int power, int tank;
}
structure
List<Car> cars = new ArrayLis<Car>()'
the most important part is safe analize line and fill part of data. The simplest (but not the best) is:
In out loop when You have line str line by line, set analyse:
String arg[] = str.split(" ");
Car c = new Car();
c.brand = arg[0];
c,model = arg[1];
c.color = arg[2];
c.power = Integer.parseInt(arg[3],0);
c.tank = Integer.parseInt(arg[4],0);
and then
cars.Add(c);

JAVA: How to convert String ArrayList to Integer Arraylist?

My question is -
how to convert a String ArrayList to an Integer ArrayList?
I have numbers with ° behind them EX: 352°. If I put those into an Integer ArrayList, it won't recognize the numbers. To solve this, I put them into a String ArrayList and then they are recognized.
I want to convert that String Arraylist back to an Integer Arraylist. So how would I achieve that?
This is my code I have so far. I want to convert ArrayString to an Int Arraylist.
// Read text in txt file.
Scanner ReadFile = new Scanner(new File("F:\\test.txt"));
// Creates an arraylist named ArrayString
ArrayList<String> ArrayString = new ArrayList<String>();
// This will add the text of the txt file to the arraylist.
while (ReadFile.hasNextLine()) {
ArrayString.add(ReadFile.nextLine());
}
ReadFile.close();
// Displays the arraystring.
System.out.println(ArrayString);
Thanks in advance
Diego
PS: Sorry if I am not completely clear, but English isn't my main language. Also I am pretty new to Java.
You can replace any character you want to ignore (in this case °) using String.replaceAll:
"somestring°".replaceAll("°",""); // gives "sometring"
Or you could remove the last character using String.substring:
"somestring°".substring(0, "somestring".length() - 1); // gives "somestring"
One of those should work for your case.
Now all that's left is to parse the input on-the-fly using Integer.parseInt:
ArrayList<Integer> arrayInts = new ArrayList<Integer>();
while (ReadFile.hasNextLine()) {
String input = ReadFile.nextLine();
try {
// try and parse a number from the input. Removes trailing `°`
arrayInts.add(Integer.parseInt(input.replaceAll("°","")));
} catch (NumberFormatException nfe){
System.err.println("'" + input + "' is not a number!");
}
}
You can add your own handling to the case where the input is not an actual number.
For a more lenient parsing process, you might consider using a regular expression.
Note: The following code is using Java 7 features (try-with-resources and diamond operator) to simplify the code while illustrating good coding practices (closing the Scanner). It also uses common naming convention of variables starting with lower-case, but you may of course use any convention you want).
This code is using an inline string instead of a file for two reasons: It shows that data being processed, and it can run as-is for testing.
public static void main(String[] args) {
String testdata = "55°\r\n" +
"bad line with no number\r\n" +
"Two numbers: 123 $78\r\n";
ArrayList<Integer> arrayInt = new ArrayList<>();
try (Scanner readFile = new Scanner(testdata)) {
Pattern digitsPattern = Pattern.compile("(\\d+)");
while (readFile.hasNextLine()) {
Matcher m = digitsPattern.matcher(readFile.nextLine());
while (m.find())
arrayInt.add(Integer.valueOf(m.group(1)));
}
}
System.out.println(arrayInt);
}
This will print:
[55, 123, 78]
You would have to create a new instance of an ArrayList typed with the Integer wrapper class and give it the same size buffer as the String list:
List<Integer> myList = new ArrayList<>(ArrayString.size());
And then iterate through Arraystring assigning the values over from one to the other by using a parsing method in the wrapper class
for (int i = 0; i < ArrayString.size(); i++) {
myList.add(Integer.parseInt(ArrayString.get(i)));
}

Search for a word in a file results in java.util.NoSuchElementException

This is my code. It produces the error java.util.NoSuchElementException.
It is meant to search a file, example.txt for a word (eg. and) and find all instances of the the word and print the word either side of it also (eg. cheese and ham, tom and jerry) in ONE JOptionPane. Code:
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class openFileSearchWord {
public static void main(String Args[])
{
int i=0,j=0;
String searchWord = JOptionPane.showInputDialog("What Word Do You Want To Search For?");
File file = new File("example.txt");
try
{
Scanner fileScanner = new Scanner(file);
String[] array = new String[5];
String[] input = new String[1000];
while (fileScanner.hasNextLine())
{
for(i=0;i<1000;i++)
{
input[i] = fileScanner.next();
if(input[i].equalsIgnoreCase(searchWord))
{
array[j] = input[i-1] + input[i] + input[i+1];
j++;
}
}
}
Arrays.toString(array);
JOptionPane.showMessageDialog(null, array);
fileScanner.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
It looks like you're assuming each line will have 1000 words.
while (fileScanner.hasNextLine())
{
for(i=0;i<1000;i++) <-------- Hardcoded limit?
{
....
}
}
You can try putting another catch loop, or check hasNext() during that for loop.
while (fileScanner.hasNextLine())
{
for(i=0;i<1000 && fileScanner.hasNext();i++)
{
....
}
}
There are also many issues with your code, like if input[i-1] hits the -1 index, or if your 'array' array hits the limit.
I took the liberty to have some fun.
Scanner fileScanner = new Scanner(file);
List<String> array = new ArrayList<String>();
String previous, current, next;
while (fileScanner.hasNext())
{
next = fileScanner.next()); // Get the next word
if(current.equalsIgnoreCase(searchWord))
{
array.add( previous + current + next );
}
// Shift stuff
previous = current;
current = next;
next = "";
}
fileScanner.close();
// Edge case check - if the last word was the keyword
if(current.equalsIgnoreCase(searchWord))
{
array.add( previous + current );
}
// Do whatever with array
....
I see a few error here ...
You are creating two arrays one with 5 and one with 1000 elements.
In your code you are referencing elements directly by index ... but this index might not be present.
input[i-1] ... what if i = 0? ...index is -1
array[j] ... what if j > 4 ... index 5 doesn't exist
I suggest using List of elements instead of fixed arrays.
List<String> array = new ArrayList<>();
You are assuming that the input is something but don't do anything to check what it actually is.
Just as Drejc told you, The first iteration would fail because of the negative index and the program will fail as well if it finds more than 5 matches of the desired word.
Also I want to add another one. You should think that when you do this line:
array[j] = input[i-1] + input[i] + input[i+1];
You have not assigned input[i+1] yet. In that iteration you've just assigned input[i], but no the next one.
You should process the concatenation of the three elements (previousWord + match + nextWord) when reaching nextWord.
Another solution, but inefficient, would be copying all the words to an Array at beginning and using your actual code without modifying. This would work, but you would go twice through all the words.

How to fix java.lang.ArrayIndexOutOfBoundsException error

I am getting an error when trying to use a JFileChooser to scan a text file add it to an array and parse one of the strings to a double and two to integers. Does it have to do with the fact that the addEmployee method adds the six parameters to an arrayList? Here is the code...
else if (e.getSource()==readButton){
JFileChooser fileChooser = new JFileChooser("src");
if (fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
empFile=fileChooser.getSelectedFile();
}
Scanner scan = new Scanner("empFile");
while(scan.hasNext()){
String[] rowData = scan.next().split(":");
if(rowData.length == 5){
rowData[4] = null;
fName = rowData[0];
lName = rowData[1];
position2 = rowData[2];
firstParam = Double.parseDouble(rowData[3]);
secondParam = Integer.parseInt(rowData[4]);
empNum = Integer.parseInt(rowData[5]);
}
else{
fName = rowData[0];
lName = rowData[1];
position2 = rowData[2];
firstParam = Double.parseDouble(rowData[3]);
secondParam = Integer.parseInt(rowData[4]);
empNum = Integer.parseInt(rowData[5]);
}
if (position2.equals("Manager")){
c.addEmployee(fName, lName, position2, firstParam, 0, empNum);
}
else if(position2.equals("Sales")){
c.addEmployee(fName, lName, position2, firstParam, 0, empNum);
}
else{
c.addEmployee(fName, lName, position2, firstParam, secondParam, empNum);
}
}
}
John:Smith:Manufacturing:6.75:120:444
Betty:White:Manager:1200.00:111
Stan:Slimy:Sales:10000.00:332
Betty:Boop:Design:12.50:50:244
You are trying to fetch empNum = Integer.parseInt(rowData[5]);
row data only having size 5 that means index 0-4, Thats why ArrayIndexOutOfBoundsException is getting
So Initialize String[] rowData = new String[6];
String[] rowData = new String[5]; // edited out of original post
rowData = scan.next().split(":");
The first statement allocates an array of 5 Strings and sets them all to null. The second statement just throws away the array you just allocated. The result of split will return an array of however many items it finds, and then you assign rowData, which is a reference to an array, to a reference to the new array. The old one gets garbage collected. So there's no guarantee that rowData will have 5 elements after this assignment.
You'll have to decide what you want to do if the split doesn't return enough array elements. You could use something like Arrays.copyOf that could put the split result into some of the rowData elements while leaving the rest alone, but then the unassigned elements will still be null, and you'll just get a NullPointerException a few lines later. So you have some design decisions to make here.
More: You may want to consider using the Scanner method nextLine() instead of next(). next() will return just one token, which means it will stop at a space character, which means you will have problems if someone is named "Mary Beth" or something like that.

Categories

Resources