How to fix this bubble sort program? - java

package arraySort;
import java.io.IOException;
import java.io.File;
import java.util.*;
public class openFile {
int x;
static int i;
static int[] myList = {100};
public static void main(String[] args){
try{
File myFile = new File("arraySort.txt");
Scanner scan = new Scanner(myFile);
while(scan.hasNext()){
myList[i] = scan.nextInt();
BubbleSort(myList);
System.out.println(myList[i]);
}
catch(IOException e){
System.out.println("File not found!");
}
}
public static void BubbleSort(int[] x){
if (x[i] > x[i + 1]){
int temp;
temp = x[i];
x[i] = x[i+1];
x[i+1] = temp;
}
}
}

Rather than give you the answer outright, here are a couple of hints:
You don't have any loops in BubbleSort().
You should only call BubbleSort() once, after you've read in all the numbers from the file. Meaning, move the call outside of the while loop.
You never increment the variable i so you're just overwriting myList[0] each time through your while loop.
Arrays are not resizable. If you try to assign to myList[1] or myList[2] you will get an ArrayIndexOutOfBoundsException error. There are several ways to solve this--one is to change it from int[] myList = {100} to ArrayList myList = new ArrayList(). You can add numbers to it with myList.add(number) and look them up with myList.get(i).

Your program has several problems, not just related to the sorting part.
static int[] myList = {100};
This line defines myList as an array with size 1, containing the single element 100. Then, your main loop is
while(scan.hasNext()) {
myList[i] = scan.nextInt();
BubbleSort(myList);
System.out.println(myList[i]);
}
You do not increase i in this loop so you are just overwriting the single value in myList with whatever value you read from the file. And when your Bubblesort function tries to access myList[i+1], it throws an ArrayIndexOutOfBoundsException because there is no element at index i+1 (which equals 1, since you don't increase i).
In general, and especially for a beginner, it is better to use ArrayList than a regular array. Also, you should fill in the array first and only after it has all the elements should you attempt to sort it. Finally, it is a better idea to make the variables local instead of class members. So that would make your main function something like
ArrayList myList = new ArrayList();
while(scan.hasNext()) {
myList.append(scan.nextInt());
}
Bubblesort(myList);
And then change Bubblesort to take an ArrayList, and then you can also make the loop index i local to the Bubblesort method. After that is done, you can work on getting the bubble sort algorithm working. Remember to be careful with your array indices there so that you never access outside the bounds of the array.

http://www.leepoint.net/notes-java/data/arrays/32arraybubblesort.html <- some bubble sort example for you ;)

Change this:
try{
File myFile = new File("arraySort.txt");
Scanner scan = new Scanner(myFile);
while(scan.hasNext()){
myList[i] = scan.nextInt();
BubbleSort(myList);
System.out.println(myList[i]);
}
catch(IOException e){
System.out.println("File not found!");
}
to:
try{
File myFile = new File("arraySort.txt");
Scanner scan = new Scanner(myFile);
while(scan.hasNext()){
myList[i] = scan.nextInt();
}
catch(IOException e){
System.out.println("File not found!");
}
BubbleSort(myList);
System.out.println(myList[i]);
}
Change sort method according to answer by #Federico

Related

Add method not working when inserting integers from a data file into an integer array

import java.util.*;
import java.io.*;
import java.util.Set;
public class tester
{
public static void main(String args[]) throws Exception
{
BufferedReader reader1 = new BufferedReader(new FileReader("numbers1.in"));
//this will create a buffered reader to read the file, read each line
//and count how many lines there are so I can easily create my array
int lines = 0;
while (reader1.readLine() != null)//reads each line
{
lines++;
}
reader1.close();
Scanner reader2 = new Scanner(new File("numbers1.in"));//new scanner to read the file
int numbers[] = new int[lines];//creates my array with correct array dimensions
while(reader2.hasNextLine())
{
int next = reader2.nextInt();
numbers.add(next);
}
}
}
I am a beginner at this, so excuse the messy code. I am trying to read integers from a data file which includes a list of integers, each separated by a new line. I have to add each of those into an integer array, and for some reason the .add method from java.util.Set is not working, giving me an error message that states the add method cannot be found.
I would appreciate any help, thank you!
In java array length is immutable. It doesn't have an add method.
Use a List
List<int> numbers = new ArrayList<>();
while(reader2.hasNextLine()) {
int next = reader2.nextInt();
numbers.add(next);
}
Or, if you need to use array only
int index = 0;
while(reader2.hasNextLine()) {
int next = reader2.nextInt();
numbers[index++] = next;
}

Issue With writing to File

import java.util.*;
import java.io.*;
public class comparing{
static ArrayList <compare> events = new ArrayList<compare>();
public static void main(String[]args){
try{
Scanner in = new Scanner(new File("events.txt"));
File output = new File("chines.txt");
Scanner sc = new Scanner(output);
PrintWriter printer = new PrintWriter(output);
while(in.hasNext()){
int temp = in.nextInt();
String temptwo = in.nextLine();
//String s = ;
events.add(new compare(temp,temptwo));
//System.out.println("Next word is: " + temp);
Collections.sort(events);
for(int i = 0;i<events.size();i++){
printer.write(events.get(i));
System.out.println(events.get(i));
}
}
}
catch(Exception e){
System.out.println("Invalid file name");
}
}
My code above reads from a file it sorts the data then prints it out. What I would like to do is write this sorted data to another file but I keep getting the following error:
comparing.java:27: error: no suitable method found for write(compare)
printer.write(events.get(i));
You're declaring events to be an ArrayList, meaning that it contains java.lang.Object elements, thus printer.write(java.lang.Object) is what's being searched for by the compiler.
You're adding an object of your undisclosed class compare, so even declaring ArrayList<compare> wouldn't help. Hopefully your compare class has a meaningful toString, so that you can use ArrayList<compare> events, combined with printer.write(event.toString());
See the docs.
There is no write(Object) method. You can change it to write(events.get(i).toString()) to convert it to a String first.
Alternatively, use print instead of write for more input options. See write() vs print().
It can take a object as argument and calls the String.valueOf(obj) method for you:
printer.print(events.get(i));
Add this code instead of your loop
for (int i = 0; i < events.size(); i++)
{
printer.write(String.valueOf(events.get(i)));
out.write(" ");
}

NullPointerException error, converting string[] to int[]

I'm running out of patience and needs this problem fixed. This program is intended to retrieve data from two text files as two string arrays, then use a mergesort algorithm to sort the results. My issue is during the conversion to an integer array. I return the array I created, and see that there is data stored. However, when running an loop and checking if any index is null, I find that the program believes them all to be null.
import java.io.IOException;
import java.nio.file.Files;
import java.io.File;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.*;
public class MergeInventories
{
public static File inv1 = new File("H:\\Senior Year\\CompSci\\Projects\\storeOneInv.txt");
public static File inv2 = new File("H:\\Senior Year\\CompSci\\Projects\\storeTwoInv.txt");
//the two text files I'm retrieving data from
public static String[] store1; //string array in question
public static String[] store2;
public static void header()
{
System.out.println("Keenan Schmidt");
System.out.println("AP Computer Science");
System.out.println("Merge Inventories");
System.out.println("...finally...");
}
public static void main() throws FileNotFoundException
{
header();
readFiles(inv1,store1); //converts file to string array
sort(); //converts string[] to int[]
//System.out.print(readFiles(inv1,store1));
//System.out.print(readFiles(inv2,store2);
}
public static String[] readFiles(File file, String[] store)
{
try {
Scanner scanner = new Scanner(file);
int i = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner = new Scanner(file);
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
i++;
}
store = new String[i];
i = 0;
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
store[i] = line;
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return store;
}
public static int[] sort()
{
int[] items = new int[store1.length];
for(int i = 0; i < store1.length; i++)
{
if(store1[i] != null) //this is the line where the error occurs
{
try{
items[i] = Integer.parseInt(store1[i].replaceAll("[^0-9]"," "));
} catch (NumberFormatException nfe) {};
}
}
return items;
}
private void mergeSort(String[] arr1, String[] arr2)
{
}
private void merge(int low, int med, int hi)
{
}
}
As azurefrog mentions in a comment, Java arrays are pass by value (the reference to the array) so that when you reassign the store variable in the method, the original array you passed in doesn't get the new reference assignment.
Since you want to re-use this method multiple times to make different arrays, I would suggest making a new array everytime inside the method. No need to pass it in.
static String[] readFiles(File file){
String[] store =null;
//rest of method this same
}
Then in your calling code:
store1 = readFiles(inv1);
store2 = readFiles(inv2);
You are getting a NullPointerException when trying to access store1 because you never give store1 a value other than null, because Java is pass-by-value.
You create a new array, but you only assign it to store, which is a local variable in readFiles(), and that assignment has no effect on the store1 variable.
You do return that value from your method, but you neglected to assign it in the invoking code.
Replace
readFiles(inv1,store1); //converts file to string array
with
store1 = readFiles(inv1,store1); //converts file to string array and saves it in store1
so that the created array is assigned to store1.
As dkatzel points out, this means that there is no longer any point in passing store1 into the method in the first place. It would be a good idea to follow his advice on cleaning up the method.
You can use a List at first because the file could be of unknown size, then convert the List to an Array (using toArray), and then you will know the length to which you should initialize the int array and your code can proceed as expected.
either change to this: store1 = readFiles(inv1,store1);
or in readFiles() use this.store1 instead

How to copy contents of array from another method into an array within the main method?

I have an array I created that holds the contents of a file. This array is not in my main method, but another method. I am having trouble figuring out how to copy the array holding the file contents into an array within my main method so I can manipulate/append the information from there. I'm getting an error saying that it can't find the variable dataPieces. Can someone please help me figure this out? Is this even the best way to work with a file so that I can show the user the information and let them append it?
Thanks
/**
Add in javadoc comments
*/
//import statements
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class Try {
public static void main(String[] args){
String dataHolder[] = createFile();
System.out.println(dataHolder);
}
public static String[] createFile(){
//create file holding inventory information
String dataPieces[] = new String[10];
try{
PrintWriter outputFile = new PrintWriter("inventory.txt");
outputFile.println("3000.0");
outputFile.println("Lamps 15.3 400");
outputFile.println("Chairs 19.95 250");
outputFile.print("Desks 95.0 300");
int i =0;
outputFile.close();
File myFile = new File("inventory.txt");
Scanner inputFile = new Scanner(myFile);
while(inputFile.hasNext() && i<dataPieces.length){
dataPieces[i] = inputFile.next();
i++;
}
inputFile.close();
}
catch(IOException e){
System.out.println("File cannot be created."); //what to say???????????<<<<<<<<
}
return dataPieces;
}
}
Your createFile() method already returns an array, so your main method should just assign that array to a variable :
public static void main(String[] args){
String[] dataHolder = createFile();
...
}
There's no reason to call createFile() multiple times.
You have something like:
for(int i=0; i<dataHolder.length; i++){
dataHolder[i] = createFile(dataPieces);
}
Here you are trying to create inventory.txt file 10 times after that reading the same 10 times in a loop as above which is going to return you the same data.
So your method createFile is returning an array i.e. dataPieces, you could just change your for loop to something like:
dataHolder = createFile();
for(int i=0; i<dataHolder.length; i++){
...do something with dataPieces which is referred by dataHolder now.
}
There by reading and writing file just once and then operating on array further in another method.

accessing variable within main method

I am very new to Java and writing this program to shuffle words and fix the suffle words. The following is my program. After I call mix(), I would like to be able to assign the output of word to team array within main.
For some reason, I can call mix() it works but I cannot access word which is in the shuffle function. Since I am in main and all these function within main, I thought I can access the variables. Any ideas what I am missing here?
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Project2
{
public static void main(String[] args)
{
System.out.println("Select an item from below: \n");
System.out.println("(1) Mix");
System.out.println("(2) Solve");
System.out.println("(3) Quit");
int input;
Scanner scan= new Scanner(System.in);
input = scan.nextInt();
//System.out.println(input);
if(input==1) {
mix();
System.out.println(word);
char team[]=word.toCharArray();
for(int i=0;i<team.length;i++){
System.out.println("Data at ["+i+"]="+team[i]);
}
}
else{
System.out.println("this is exit");
}
}
static void mix()
{
String [] lines=new String[1000];//Enough lines.
int counter=0;
try{
File file = new File("input.txt");//The path of the File
FileReader fileReader1 = new FileReader(file);
BufferedReader buffer = new BufferedReader(fileReader1);
boolean flag=true;
while(true){
try{
lines[counter]=buffer.readLine();//Store a line in the array.
if(lines[counter]==null){//If there isn't any more lines.
buffer.close();
fileReader1.close();
break;//Stop reading and close the readers.
}
//number of lines in the file
//lines is the array that holds the line info
counter++;
}catch(Exception ex){
break;
}
}
}catch(FileNotFoundException ex){
System.out.println("File not found.");
}catch(IOException ex){
System.out.println("Exception ocurred.");
}
int pick;
Random rand = new Random();
pick = rand.nextInt(counter ) + 0;
System.out.println(lines[pick]);
///scramble the word
shuffle(lines[pick]);
}
static void shuffle(String input){
List<Character> characters = new ArrayList<Character>();
for(char c:input.toCharArray()){
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while(characters.size()!=0){
int randPicker = (int)(Math.random()*characters.size());
output.append(characters.remove(randPicker));
}
String word=output.toString();
}
}
Return string value from shuffle() method using return statement:
static String shuffle(String input) {
// . . .
return output.toString();
}
...and then use it in mix:
String word = shuffle(lines[pick]);
But it is better to read basic java tutorials before programming.
In Java, variables cannot be seen outside of the method they are initialized in. For example, if I declare int foo = 3; in main, and then I try to access foo from another method, it won't work. From the point of view of another method, foo does not even exist!
The way to pass variable between methods is with the return <variable> statement. Once the program reaches a return statement, the method will quit, and the value after the return (perhaps foo) will be returned to the caller method. However, you must say that the method returns a variable (and say what type is is) when you declare that method (just like you need to say void when the method does not return anything!).
public static void main(String[] args){
int foo = 2;
double(foo); //This will double foo, but the new doubled value will not be accessible
int twoFoo = double(foo); //Now the doubled value of foo is returned and assigned to the variable twoFoo
}
private static int double(int foo){//Notice the 'int' after 'static'. This tells the program that method double returns an int.
//Also, even though this variable is named foo, it is not the same foo
return foo*2;
}
Alternatively, you could use instance variable to have variables that are accessible by all the methods in your class, but if you're new to Java, you should probably avoid these until you start learning the basics of object-oriented programming.
Hope this helps!
-BritKnight

Categories