Bubble sorting arraylis is not working - java

I'm trying to bubble sort car make and year, where I would have the car year sorted and if two car makes are in the same year, then they are sorted alphabetically. My program works up to the point where I call BubbleSorted(). It's giving me an error java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 and I don't know why. My program seems to be correct. Below is my program. I have 3 classes(main, bubblesortCars, GetCarInfo).
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
public class TheMain {
public static void main(String[] args) {
Scanner keyboard=new Scanner(System.in);
int choice;
boolean done = false;
try{
String filename1 = "Demo.txt";
FileReader inputFile = new FileReader(filename1);
//Instantiate the BufferedReader Class
BufferedReader bufferReader = new BufferedReader(inputFile);
ArrayList<GetCarInfo> CarList = new ArrayList();
//Variable to hold the one line data
String line;
StringTokenizer st;
int i=0;
// Read file line by line and print on the console
while ((line = bufferReader.readLine()) != null) {
st = new StringTokenizer(line, "\t");
st.nextToken();
st.nextToken();
String getMake = st.nextToken();
st.nextToken();
int getYear = Integer.parseInt(st.nextToken());
GetCarInfo temp;
temp = new GetCarInfo(getMake, getYear);
CarList.add(temp);
}
bufferReader.close();
BubbleSortCars Sorted = new BubbleSortCars();
Sorted.bubblesorted(CarList, 0, CarList.size());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
import java.util.ArrayList;
public class BubbleSortCars {
ArrayList <GetCarInfo> temp= new ArrayList();
public void bubblesorted(ArrayList <GetCarInfo> grabber, int began, int end){
for(int i =0; i<end-began-1; i++){
for(int j=began; j<(end-i-1); j++){
if(grabber.get(j).year > grabber.get(j+1).year){
temp.set(j, grabber.get(j));
grabber.set(j,grabber.get(j+1));
grabber.set(j+1, temp.get(j));
System.out.println("Success");
}
else if(grabber.get(j).year==grabber.get(j+1).year){
if((grabber.get(j).make).compareTo(grabber.get(j+1).make)>0){
temp.set(j, grabber.get(j));
grabber.set(j, grabber.get(j+1));
grabber.set(j+1, temp.get(j));
System.out.println("Success");
}
}
}
}
}
}
public class GetCarInfo {
int year;
String make;
public GetCarInfo(String newmake, int newyear){
make = newmake;
year = newyear;
}
}

Reason you get IndeOutOfBoundException is due to this line:
temp.set(j, grabber.get(j));
and your definition of arrayList.
ArrayList<GetCarInfo> temp = new ArrayList();
Here you are defining temp as arrayList without any element and you are trying to set an element at 0th location which is not defined. See this for your reference http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#set%28int,%20E%29
When you define temp as above it created with size 0 and jdk does check internally if index that you are trying to access is less than size then only it will allow you to access/set content.
So one way to avoid this, you define your temp arrayList in your method like:
ArrayList<GetCarInfo> temp = new ArrayList(grabber);
Or you could use grabber arrayList to do the sorting without any other data structure.

The problem is with the ArrayList temp. Please refer the Oracle documentation for the set method.
Here you don't need an ArrayList. User a simple GetCarInfo object as temp variable.

Related

Accessing Elements in an ArrayList of ArrayLists

I have an ArrayList of ArrayLists, and I'm trying to access the elements inside, and generally add, remove, replace, and get the items.
My code is below.
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class MarvelNetworkRearrange {
public static void main(String[] args) {
BufferedReader csvReader = null;
try {
String newLine;
ArrayList B = new ArrayList<ArrayList>();
csvReader = new BufferedReader(new FileReader("MARVEL P2P.csv"));
Integer i = 0;
while ((newLine = csvReader.readLine()) != null)
{
B.add(A(newLine));
}
File f = new File("MarvelRearranged.csv");
PrintWriter printWriter = new PrintWriter(f);
ArrayList<String> x = new ArrayList<String>();
x = B.get(0);
x.remove(0);
System.out.println(x);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (csvReader != null) csvReader.close();
}
catch (IOException newException)
{
newException.printStackTrace();
}
}
}
public static ArrayList<String> A(String fromCSV) {
ArrayList<String> csvResult = new ArrayList<String>();
if (fromCSV != null)
{
String[] splitData = fromCSV.split("\\s*,\\s*");
for (int i = 0; i < splitData.length; i++)
{
if (!(splitData[i] == null) || !(splitData[i].length() == 0))
{
csvResult.add(splitData[i].trim());
}
}
}
return csvResult;
}
}
I'm reading in a .csv file, and I'm attempting to rearrange the items in the .csv file in order to create a .csv file that I can use more effectively for a project. However, when I run this code, I get "error: incompatible types: Object cannot be converted to ArrayList" at "x = B.get(0);". I have also tried x.get(0).remove(0).
I am trying to remove the first element of the first ArrayList in the ArrayList B, so what am I doing wrong? The reason I'm trying to remove it is that the specified element is a blank space in the .csv (done intentionally when creating the original, as it was the space between the headers in a matrix).
Please help!
You have defined your ArrayList B without type, but ArrayList x has String type. Either you need to cast the type, or you need to follow below approach which is better:
Specify type of ArrayList B:
ArrayList<ArrayList<String>> B = new ArrayList<>();
To delete any element from your ArrayList, skip creating another object and point to an element of B, directly delete from B:
B.get(0).remove(0);

Adding integers to arraylist "scores"

I have a text file with about 5000 names or so, each separated by line.
I am have already accomplished adding all the names to an ArrayList "names", but
i am not able to add anything to my arrayList scores.
I don't know where I'm going wrong, especially in the addScores method, nothing gets outputted at all.
If anymore information is required, please ask.
And thanks for the help..
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
public class ScoringNames {
BufferedReader x = null;
String location = "xxxxx\\names.txt";
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> scores = new ArrayList<Integer>();
public void readFile(){ //Opens file, and prints every line.
try{
x = new BufferedReader(new FileReader(location));
} catch(FileNotFoundException e) {
e.printStackTrace();
}
try{
String name = x.readLine();
while(name != null){
//System.out.println(name);
names.add(name);
name = x.readLine();
}
} catch(IOException e) {
e.printStackTrace();
}
}
public int nameScore(String name){
this.readFile(); //Open file and read, so that values are added to <names>
this.sortNames();
int score = 0;
char[] tempName = name.toCharArray();
for (char i : tempName){
score += alphValue(i);
}
return score;
}
public void addScores(){
for(String x : names){
scores.add(nameScore(x));
}
}
public void printScores(){
for(int counter: scores)
System.out.println(counter);
}
public static void main(String[] args) {
ScoringNames abc = new ScoringNames();
abc.readFile();
abc.addScores();
abc.printScores();
}
}
The error i get is:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at ScoringNames.addScores(ScoringNames.java:148)
at ScoringNames.main(ScoringNames.java:163)
You are modifying the List names while accessing it from the For loop of addScores() method.
When you call nameScore(String str) method, Then you don't need to read the file again as all data has been read already and stored in the names list. You need to do just evaluation of the String and return the score.
public int nameScore(String name){
int score = 0;
char[] tempName = name.toCharArray();
for (char i : tempName){
score += alphValue(i);
}
return score;
}
Change method nameScore - remove two top lines.
this.readFile(); // Open file and read, so that values are added to
// <names>
this.sortNames();
There are not unnecessary and the readFile() is the reason of the error.
The reason of the error is that you try to change this.names value in for each loop (for (String x : names)) and that is forbidden in Java.
public int nameScore(String name) {
int score = 0;
char[] tempName = name.toCharArray();
for (char i : tempName) {
score += alphValue(i);
}
return score;
}

Read integers from file and save two integers per index in a ArrayList

I have research about what I am trying to accomplish. This is my code, and here the main function is to read a file.txt which has integers separated by white spaces and they will be read one by one. However, I want to know... How Can I stored the integers inside a ArrayList, But in each index of the ArrayList there will be two integers instead of one, as usual?
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
int[] arr = readFile("address.txt");
System.out.println("The memory block generated is:");
System.out.println(Arrays.toString(arr));
}
// access this method in FIFO
public static int[] readFile(String file) { // this main method
try { // try and catch
File f = new File(file);
#SuppressWarnings("resource")
Scanner r = new Scanner(f); // read the file with scanner
int count = 0; // count for the integers
while(r.hasNextInt()) { // while keep reading
count++;
r.nextInt();
}
int[] array = new int[count];
#SuppressWarnings("resource")
Scanner readAgain = new Scanner(f); // read again
ArrayList<ArrayObjects> blockMem = new ArrayList<>(); // array size * we can use dynamic array
for(int i = 0; i < count; i++) {
// i want to iterate and save them
}
return array;
} catch(Exception fnf) {
System.out.println(fnf.getMessage() + "The file could not be open, try again");
System.exit(0);
}
return null;
} // method closed
}`
Create a new class with two integers.
class TwoIntegers{
int one,two;
TwoIntegers(int data1,int data2){
one = data1;
two = data2;
}
}
Now create an Arraylist of objects of type TwoIntegers
ArrayList<TwoIntegers> blockMem = new ArrayList<TwoIntegers>();
//now you can iterate and insert integers you need
blockMem.add(new TwoIntegers(1,2));
blockMem.add(new TwoIntegers(3,4));

Issues with do while loop in java

Having an issue with my do while loop as it doesn't end when STOP is entered. Also I'm not sure if I need to add any exceptions or what not. I know doing toString would be more efficient but the requirement for the program is a for loop when extracting the output.
import java.util.*;
import java.util.ArrayList;
import java.lang.IndexOutOfBoundsException;
public class MyProj
{
public static void main(String[] args)
{
ArrayList <String> MyItems = new ArrayList <String>();
Scanner Scan = new Scanner(System.in);
String Temp;
System.out.println("Please enter the name of an object, repeat as needed, type STOP to end");
do
{
Temp = Scan.nextLine();
if(Temp != "STOP")
{
MyItems.add(Temp);
}
}
while(Temp == "STOP");
for(int x = 0; x <= MyItems.size() - 1; x++)
{
System.out.println(MyItems.get(x));
}
}
}
Try this code:
do
{
Temp = Scan.nextLine();
if(!Temp.equals("STOP"))
{
MyItems.add(Temp);
}
}
while(!Temp.equals("STOP"));
I'd recommend that you change that to equalsIgnoreCase() as #3kings suggested.

Adding a value to a sorted array in Java 8

You are provided the following list that contains (semi-random) years from modern history. Save the list to a text file named “events.txt” Write a program that:
Reads in the file “events.txt”
Sorts it with the latest events first
Determines whether the founding of CMU in 1892 was considered a world historic event
If not so yet, adds the event to the list of events
Writes the new list of events to a file named “sorted_events.txt
import java.io.*;
import java.util.*;
public class EventSorter {
public static void main(String[] args) throws FileNotFoundException{
File file =new File("events.txt");
FileReader read = new FileReader(file);
LineNumberReader lines = new LineNumberReader(read);
Scanner readIn = new Scanner(file);
PrintWriter output = new PrintWriter("sorted_events.txt");
try{
//call for the file
//make sure it exists
if(file.exists()){
{
//first write this to determine the number of lines
int lineNumber = 0;
//gets the number of lines
while (lines.readLine() != null){
lineNumber++;
}
int[] event = new int[lineNumber];
int j = 0;
while(readIn.hasNext()){
event[j]=readIn.nextInt();
j++;
}
//sort the array
Arrays.sort(event);
boolean found;
for(int i = 0; i < event.length; i++){
if (event[i] == 1892){
//see if 1892 is on the list
System.out.println("CMU is a historic event");
found = true;
}
else{
addElement(event, 1892);
}
}
int[] sortedEvent = new int[lineNumber];
for(int k = 0; k < event.length; k++){
sortedEvent[k] = event[(event.length-1) - k];
System.out.println(sortedEvent[k]);
}
for(int print = 0 ; print < event.length; print++){
output.println(sortedEvent[print]);
}
}
readIn.close();
output.close();
lines.close();
}else{
System.out.println("File does not exist!");
}
}
catch(IOException e){
e.printStackTrace();
}
}
static int[] addElement(int[] a, int e) {
a = Arrays.copyOf(a, a.length + 1);
a[a.length - 1] = e;
return a;
}
}
I'm going to answer strictly to the title "Adding a value to a sorted array in Java 8". Two options can be:
Create a TreeSet or any SortedSet (or a structure based on a Binary Search Tree) from your array. This collection is sorted by default and any new items you add to it will keep it sorted.
Use something similar to binary search to find where in the array the new element should be placed.
This program does exactly what you want and answers the question of the teacher perfectly.
However, it's using several advanced techniques of Java and I strongly doubt that your teacher will give you any credit for it. So use it at your own risk.
The best you can do with this code is to read it, understand its concept and apply them in conjunction to what you know.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class EventSorter {
public static void main(String[] args) {
try {
Path inPath = Paths.get("events.txt");
Path outPath = Paths.get("sorted_events.txt");
int event = 1892;
Comparator<Integer> lastFirst = Comparator.<Integer>naturalOrder().reversed();
List<Integer> events = Files.lines(inPath).map(Integer::valueOf).sorted(lastFirst).collect(Collectors.toCollection(ArrayList::new));
int pos = Collections.binarySearch(events, event, lastFirst);
if (pos < 0) {
events.add(~pos, event);
}
Files.write(outPath, events.stream().map(Object::toString).collect(Collectors.toList()));
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
events.txt (input)
1982
1821
1934
1809
sorted_events.txt (output)
1982
1934
1892
1821
1809

Categories