Receive input from method using File IO (Java) - java

I need to allow the user to tell the program where the file is and output that data in a particular way. I cannot seem to pass the data to the separate class file. What am I doing wrong?
import java.util.Scanner;
import java.io.*;
public class Student_Test {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in); // sets up scanner
System.out.print("Enter file name: "); //user provides file name and location
String userFile = in.nextLine(); // accepts input from user
File file = new File(userFile); //uses the file method to import the data
Scanner inputFile = new Scanner(file); // uses scanner to read the data
System.out.print(inputFile.Out());
}
}
Also can I have some tips on how to start a separate Student class to do the work. The file that I'll be reading in has multiple lines of text. I will have to take some of that text and convert it into integers. Then I have to output it in a certain way. Should I use a void method or a return method?

Just a few tips
First you have to think what attributes a Student class needs.For example:
A student has a full name ,a social security number (maybe?)
Then you can create something like this as a seperate class
public class Student {
private String fullName,socialSecurityNumber;
public Student(String fullname,String secNumb){
fullName=fullname;
socialSecurityNumber=secNumb;
}
}
But mostly you have to think of what the student class has to do .

I've just been working a bit with file processing myself. Still learning the basic concepts of java and to my level I found this tutorial quite helpful: http://www.functionx.com/java/Lesson23.htm.
It goes through how you create, save, open and read from a file.
As seen in the tutorial one way to output the contents of your file would be to save each line to a variable. Assuming that you know what information is placed on each line this will give you some flexibility in regard to how you want to present the file contents. You can use the nextLine() for that as well. You can do this in a while loop, which reads every line in the file.
while(inputFile.hasNext()){
String studentName = inputFile.nextLine();
String studentCourse = inputFile.nextLine();
}
The hasNext() returns true until the Scanner gets to the end of the file and there are no more lines to read.
If you want to print your file contents to the console you can probably then use a void method as it doesn't require you to return anything.

Related

How do I read files as a object or is there a better solution to this? Please see code bellow for context

So in my java class, we need to read this file and somehow converts its content into an object
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Calendar {
public Appointment[] appointments;
Calendar()
{
appointments = null;
}
Calendar(int capacity, String filename)
{
Appointment[] appointments = new Appointment[capacity];
//you can see that appointments is an Appointment object
readCalendarFromFile(filename);}
private void readCalendarFromFile(String fileName){
Scanner fileRead = null;
try
{
fileRead = new Scanner(new FileInputStream("appointments.txt"));
for(int r = 0; r < 30; r++)
appointments[r]= fileRead.nextLine(); ----> This is where I am getting my error from as I cannot convert String into an object. Is there a way that I can pass this
fileRead.close();
}
catch (FileNotFoundException fe)
{
fe.printStackTrace();
System.err.println("Unable to open the file " + fileName + " for reading.");
}
}
}
Is there any way that I can convert filetext into an object or do I have to do something else with it? I have to make an appointment an object so I can't change it into anything else sadly.
You have to have a class Appointment somewhere, and what you are trying to do is add an object of the type Appointment to the array appointments, based on the info you get from the text file, right?
So, you have your for loop that reads every line from the text file, and then you need to create instances of Appointment for each line.
The class Appointment has some kind of constructor, that you need to call to create a new object (read: "a new instance") from it.
Let's assume it looks like this:
public Appointment(String title, String time, String location) {
this.title = title;
this.time = time;
this.location = location;
}
Let's also assume that every line in the file appointments.txt is formatted in the following way:
<Title>, <Time>, <Location>
Which means, that you would have to parse the line that you read from the file by splitting it (the delimiter in this case would be the ",". Just do a quick research on the internet on how to split Strings in Java, it's pretty easy actually.
When you have all the bits of information in separate variables, you have to call the constructor of Appointment, to create a new appointment that you can then add to your array. Assuming that you have three Strings with the title, the time and the location of the appointment (or whatever info you have in the text file), this would look like this:
try{
fileRead = new Scanner(new FileInputStream("appointments.txt"));
int counter = 0;
while(fileRead.hasNext()) {
String lineRead = fileRead.nextLine();
// here comes the parsing of the line into three String variables
appointments[counter] = new Appointment(title, time, location);
fileRead.close();
}
} catch(FileNotFoundException ex) {
// Do some exception handling in here, or just print the stacktrace
}
The line I want you to pay the most attention to is the Line, where it says new Appointment(title, time, location). The difference between this and the code that you posted is, that here I create a new object of the type Appointment, that corresponds with the type of the array you created earlier, in the line Appointment[] appointments = new Appointment[capacity].
You tried to directly add a String to the array, although you declared an array of the type Appointment, not of the type String.
You should read up on the topic of objects in Java in general, and what constructors are, what they do and how you use them.
For example, this topic gets explained really well and exhaustive in the official Java tutorials from Oracle (the company that develops the Java Language). I linked you the specific section that talks about constructors, but I would suggest that you read at least the whole chapter and everything before it that helps you understand what they actually talk about.
Hope this helps :)

Putting words from an input file into canonical form

I'm trying to write a code where it takes words from a text file, and puts each word in canonical order, and when run prints the original word next to its canonical form like this:
coding cdgino
games aegms
All I have so far is this:
import java.util.*;
import java.io.*;
public class CanonicalWords
{
public static void main(String[] args) throws Exception
{
if (args.length<1)
{
System.out.println("You must provide an input file.");
system.exit(0);
}
String infileName = args[0];
BufferedRead infile = new BufferedReader(new FileReader(infileName));
while(infile.ready())
{
//arraylist.add(infile.readLine())
}
//sort arraylist
for (int i=0;i<arrayList.size;i++)
{
}
}
static String canonical(String word)
{
char[] canonicalWord = word.toCharArray();
Arrays.sort(canonicalWord);
String cWord = new String(canonicalWord);
return cWord;
}
}
Please let me know if you need clarification on anything I have writen. I do not know how to take these words to put them into canonical form.
Right now there is no real output, it doesn't even compile. I'm just very confused. If someone could help me to understand what is the basic formula (if there is one) to put words into canonical form and do what I stated above that'd be wonderful, but I understand that what I'm asking may come off as a bit confusing. Thank you.
First, from the looks of this code:
BufferedRead infile = new BufferedReader(new FileReader(infileName));
should look like this:
BufferedReader infile = new BufferedReader(new FileReader(infileName));
Be careful that you fully spell out correctly; variable names and they're data types!
Another thing to take note of is, the method:
static String canonical(String word)
isn't being called. Try accessing it in the main method.

Trying to create hashmap and print out it's contents (keys)

I have a text file that I'm reading from and I'm trying to use the words in the text as file as keys in a hashmap. I then want to print the hashmap to see it's contents. This is a prelude to a larger project. I know I could simply print out the text file, but I'm trying to experiment with the hashmap data structure.
Here's the code I have so far:
import java.io.*; //needed for File class below
import java.util.*; //needed for Scanner class below
public class readIn {
public static void readInWords(String fileName){
try{
//open up the file
Scanner input = new Scanner(new File(fileName));
HashMap hm = new HashMap();
while(input.hasNext()){
//read in 1 word at a time and increment our count
String x = input.next();
System.out.println(x);
hm.put(x);
}
System.out.println(hm);
}catch(Exception e){
System.out.println("Something went really wrong...");
}
}
public static void main(String args[]){
int x = 10; //can read in from user or simply set here
String fileName = "test.txt";
readInWords(fileName);
}
}
When I run, I get a "no suitable method found for put(string)" error. My larger goal is to create this hash map and store a list of places where a certain keys appears as a value. However right now I'm just trying to learn more about hashmaps through practice and wanted to see if anyone knows why this doesn't work.
There are no .put(x) method in Map iterface. You must use put() method with key argument. In your situation do it like this: hm.put(x, x);

Reading words from wordlist.txt into array list, sorting, and writing new file

I can't figure this out for the life of me.
Steps:
Create a new project in Eclipse
Copy the provided wordlist.txt file into the Project folder
Write a single Class named "Reverser" that performs the requested tasks:
Tasks:
Use a java.util.Scanner to load each word in the wordlist.txt file into an ArrayList
Provide the Scanner a reference to a FileReader
Report the number of words placed into the ArrayList
Use the java.util.Collections class to reverse the order of the references in the ArrayList
Use a java.util.Formatter to write the re-ordered words into a new text file named "reversed.txt"
Provide the Formatter with a reference to a FileWriter
Make sure that each word is placed onto a separate line
Additionally, write code so that Java provides the correct end of line terminator for each line. Note: No \n, or \r\n allowed!
Write code to help ensure your program has no resource leaks.
Here is what I have so far
public class Reverser {
public static void main(String[] args) {
Scanner scan = null;
File file = new File("C:\\Users\\Nick\\JavaWorkspace\\Lab 7\\wordlist.txt");
ArrayList<String> list;
try {
scan = new Scanner(new FileReader(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
list = new ArrayList<String>();
while((scan.nextLine()) != null){
list.add(scan.next());
}
String[] stringArr = list.toArray(new String[0]);
}
}
I will give you general guideline to follow.
This is a nice task to get some hands on experience in the following areas:
Using Input to read (from a file) and Output stream to write (to a file)
Using the size() method for your List object.
Using finally block with your try/catch block to clean up resources(close scanner in finally block)
Using Collections.reverseOrder() method.
You can look up those things individually and then try to integrate piece by piece in your code.

How to use Scanner to read file and pass it to a method in Java

I am confused with how to use Scanner to read a file (given in command line argument), and use the information from that file in a method. What's the best way to do this?
I know there must be numerous errors in my code. i.e. Which type of parameter shall I pass to the method, string or file? I have commented my questions in the code. Many thanks!
public class Read {
int [] store;
public Read() {
store = new int[200];
}
public static void main(String[] args) throws FileNotFoundException {
File inputFile = new File (args[0]); //shall I declare a File variable here?
Read readFile = new Read();
readFile.doSomething(inputFile);//Should the parameter of doSomething be String type?
}
public void doSomething (String inputFile) throws FileNotFoundException{
Scanner sc; //I intend to use the info. from the file to do something here
sc = new Scanner(new FileReader(inputFile));
while (sc.hasNext()){
.....
}
}
}
I would suggest you to pass String means file path to the method in that sense after reading from file the Objects gets garbage collected after the execution of method while in main method you may want to perform some other stuff and File object remain accessible until the execution of main method.
What if you want to read more than one file and you are passing multiple command line argument ? So passing String to method sounds convenient as it will allow you to manage File object.In this situation creating File Objects and than passing it to method becomes more time consuming.
So it Should be...
public static void main(String[] args){
Read readFile = new Read();
readFile.doSomething(args[0]);
readFile.doSomething(args[1]);//You can read multiple files
....
}
public void doSomething (String inputFile) throws FileNotFoundException{
File inputFile = new File (inputFile);
//Read File With Scanner
}
It is possible to do it that way, but then you'll have to pass the filename into the commandline when starting the program. Like this:
java [program] [filename]
Another solution is hardcoding:
File inputFile = new File ("filename");
As stated above these are the two ways but note your harcoded file must be present in the project where your packages reside.

Categories

Resources