Issue With writing to File - java

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(" ");
}

Related

How to read a file and pass the information to separately saved class objects?

I'm setting a java application that has 3 separately saved classes WordApp, WordProcessor, and WordType. WordApp reads the file and is suppose to pass the data to the other classes. I can read the file but I can't the data to pass to the other classes. How to pass the information via a string?
I've searched this and every example I find has all the classes saved to the same file. I'm using textpad and I tried passing the string to the WordProcessor class which has constructs an ArrayList of WordType objects. This method is not working for me.
This is the first part of the WordApp class for reading the file.
import java.io.*; // Import IO package
import java.util.Scanner; // Import Scanner utility
import java.util.ArrayList; // Import ArrayList utility
public class WordApp // Declared WordApp Class
{
public static void main (String[] args) // Main
{
// Declared Variables
String again;
String initial = "";
String inputFileName;
String outputFileName;
// Declared Objects
Scanner input = new Scanner(System.in);
do
{
try
{
System.out.println(" Welcome to the Word Processor App! ");
System.out.println("**********************************************************************\n");
System.out.println("Enter file names with .txt extension.");
System.out.print("Please Enter File Name to Read: ");
inputFileName = input.nextLine().trim();
File mcFile = new File(inputFileName);
Scanner scan = new Scanner(mcFile);
System.out.println("Enter file names with .txt extension.");
System.out.print("Please Enter File Name to Save: ");
outputFileName = input.nextLine().trim();
File deFile = new File(outputFileName);
PrintWriter out = new PrintWriter(deFile);
System.out.println("Reading file...\n");
while(scan.hasNext())
{
initial = scan.next();
}
scan.close();
System.out.println("Scanning Paragraph.....\n");
WordProcessor x = new WordProcessor();
x.addWord(initial);
I'm trying to pass the words in the file here:
import java.util.ArrayList;
import java.util.Collections;
public class WordProcessor
{
private ArrayList<WordType> words;
private int totSentences;
private int totUnique;
public WordProcessor()
{
words = new ArrayList<WordType>();
totSentences = 0;
totUnique = 0;
}
and here:
public class WordType implements Comparable
{
// instance data
private String word;
private int count;
private int syllables;
// Constructors
public WordType(String newWord)
{
word = newWord;
count = 1;
syllables = countSyllables();
}
I'm expecting that that words pass to the other classes but when I save the file it is blank. Sorry if I didn't post the code correctly
You're reading the file and getting the items it holds but discarding all but the last.
while(scan.hasNext()) {
initial = scan.next();
// You do **nothing** with the String read in
}
scan.close();
System.out.println("Scanning Paragraph.....\n");
WordProcessor x = new WordProcessor();
x.addWord(initial); // until here where you add the last one
Instead create the WordProcessor object before the while loop, and add words within the while loop
WordProcessor x = new WordProcessor();
while(scan.hasNext()) {
initial = scan.next();
x.addWord(initial);
}
scan.close();
There may be other errors, especially problems in your code not shown (addWord(...) comes to mind), but this error was immediately obvious.
Also what type of looping are you doing and why? You appear to have a do-while loop -- why? Again if this does not solve your problem, then you still will need to create and post a valid mcve so we don't have to guess what the problem truly is. Please understand that I am not asking for all your code but rather for something completely different -- please read the link and understand it fully if your problem has not been solved and you still need help.

Trying to check the words within one file in another

I'm setting up a spell checker for a class assignment.
I'm trying to check the words within one file with another.
I'm currently experiencing an error:
spelling.java:29: error: cannot find symbol
if(checkMe.next().equals(dicArr[i])){
^
symbol: variable dicArr
location: class spelling
1 error
Could you please advise me on what I'm doing wrong or what I could potentially improve with my approach? Many thanks.
import java.util.*;
import java.io.*;
public class spelling{
public static void main(String args[]) throws FileNotFoundException {
//read the dictionary file
Scanner dicIN = new Scanner(new File("dictionary.txt"));
Scanner spellCheckFile = new Scanner(new File("checkMe.txt"));
String inputWord;
int i = 0;
//create arraylist to pass dictionary through, then I can define the size of my array
ArrayList<String> dicList = new ArrayList<String>();
while(dicIN.hasNext()){
dicList.add(dicIN.next());
String[] dicArr = dicList.toArray(new String[dicList.size()]);
}
//Scan through checkMe file to see if the words occur in the dictionary
Scanner checkMe = (spellCheckFile);
while(checkMe.hasNext())
{
if(checkMe.next().equals(dicArr[i])){
i++;
} else{
System.out.println("The word " + checkMe + "doesn't exist in the dictionary");
}
}
//System.out.println(dicList);
}
}
your i++ is confusing - you should have 2 loops:
one to iterate checkme, like you do: while(checkMe.hasNext())
the other to iterate through all dicArr. Only if you check every dicArr[i], you can tell The word doesn't exist in the dictionary
Prefer this:
1 use a Set for your dictionnary
2 to check each word, you only need to do set_string.contains(new_word)
For example
Set set_string=new HashSet();
set_string.add(new_string);
if (set_string.contains(another_string)) ...
Set keeps unique elements. searching is straightforward.
You declare dicArr in the body of a while loop. It is not visible outside the body of the while loop.
I am not certain what you are trying to do, but I think you need to close the while loop before the declaration of dicArr:
while(dicIN.hasNext()){
dicList.add(dicIN.next());
} // <-- Add closing brace here.
String[] dicArr = dicList.toArray(new String[dicList.size()]);
// } // <-- Remove closing brace here.
Try to declare this String[] dicArr = null; before all loop like this:
String[] dicArr = null;
ArrayList<String> dicList = new ArrayList<String>();
while(dicIN.hasNext()){
dicList.add(dicIN.next());
dicArr = dicList.toArray(new String[dicList.size()]);
}
//Scan through checkMe file to see if the words occur in the dictionary
Scanner checkMe = (spellCheckFile);
while(checkMe.hasNext())
{
if(checkMe.next().equals(dicArr[i])){
.....}

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

How to fix this bubble sort program?

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

Categories