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.
Related
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 :)
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);
first I want to say that I'm beginer and that this is my first Java program. I'd like to make a program that will read text file, find specific line, and save it to my string variable.
So I want to find line that starts with "Dealt to ", and then in that line, copy everything after that till this char '[' and put it in my string variable.
So let's say that I have this line in my text file:
Dealt to My NickName [text]
I want to have a program that will find text "My Nickname" and put it in my string variable.
I'm trying to work with classes and trying to use setters and getters just to practice, please let me know how my code looks like and how I can improve it and make it work.
this is Main.java:
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException{
HandHistory hh1 = new HandHistory();
String hero1 = null;
hero1 = hh1.getHero();
System.out.println(hero1);
}
}
My HandHistory.java:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class HandHistory {
private String hero;
public HandHistory(){}
public String getHero() throws IOException {
FileReader in = new FileReader("G:/Java/workspace/HandHistory/src/File.txt");
BufferedReader br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
if (line.contains("Dealt to ")){
hero = line.substring(9,(line.indexOf("["))-1);
}
}
return hero;
}
public void setHero(String hero){
this.hero = hero;
}
}
It's a good start, good way to read a file line by line. The one problem worth fixing is closing the FileReader resource by using a try-finally block, or since Java 7 the new try-with-resources block:
try (FileReader in = new FileReader("G:/Java/workspace/HandHistory/src/File.txt")) {
...
}
Other tips and comments I can think of:
You don't have to have a setter in your class if you don't actually need it
Your code doesn't work will if there are lines contain the string "Dealt to" but don't start with that string. E.g. "Foobar Dealt to My NickName [text]" will still be matched but will return a wrong value
If you really only want to match lines that start with "Dealt to" then use String.startsWith() instead of String.contains()
You should handle the case when there's no "[" in the string, otherwise your code crashes with a hard to understand error
Regular expressions are useful if they remove complexity from your code. In your case the problem can be solved by using startsWith and indexOf relatively easily, so I'd not use RegExps in this case
It's not obvious what HandHistory.getHero() does without looking at the actual code. It's always very helpful even for yourself to assign names to things that express what the class or method is actually doing.
It can be said that getHero() method does too many things and so does the class HandHistory, but that's maybe something to consider when using the code for something bigger than a learning hello-world example.
My advise would be to use a Regex. You can try with
(?<=beginningstringname)(.*\n?)(?=endstringname)
So, for your problem this would be
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
public static void main( String args[] ){
// String to be scanned to find the pattern.
String line = "Dealt to My NickName [text]";
String pattern = "(?<=Dealt to )(.*\n?)(?=[)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
//m now haves what you desire. You can loop it if you want.
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
} else {
System.out.println("NO MATCH");
}
}
}
Try this tutorial for using regular expressions in Java http://www.tutorialspoint.com/java/java_regular_expressions.htm
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.
The first assignment of my algorithms class is that I have to create a program that reads a series of book titles from a provided csv file, sorts them, and then prints them out. The assignment has very specific parameters, and one of them is that I have to create a static List getList(String file) method. The specifics of what this method entails are as follows:
"The method getList should readin the data from the csv
file book.csv. If a line doesn’t follow the pattern
title,author,year then a message should be written
to the standard error stream (see sample output) The
program should continue reading in the next line. NO
exception should be thrown ."
I don't have much experience with the usage of List, ArrayList, or reading in files, so as you can guess this is very difficult for me. Here's what I have so far for the method:
public static List<Book> getList(String file)
{
List<Book> list = new ArrayList<Book>();
return list;
}
Currently, my best guess is to make a for loop and instantiate a new Book object into the List using i as the index, but I wouldn't know how high to set the loop, as I don't have any method to tell the program how, say, many lines there are in the csv. I also wouldn't know how to get it to differentiate each book's title, author, and year in the csv.
Sorry for the long-winded question. I'd appreciate any help. Thanks.
The best way to do this, would be to read the file line by line, and check if the format of the line is correct. If it is correct, add a new object to the list with the details in the line, otherwise write your error message and continue.
You can read your file using a BufferedReader. They can read line by line by doing the following:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// do something with the line here
}
br.close();
Now that you have the lines, you need to verify they are in the correct format. A simple method to do this, is to split the line on commas (since it is a csv file), and check that it has at least 3 elements in the array. You can do so with the String.split(regex) method.
String[] bookDetails = line.split(",");
This would populate the array with the fields from your file. So for example, if the first line was one,two,three, then the array would be ["one","two","three"].
Now you have the values from the line, but you need to verify that it is in the correct format. Since your post specified that it should have 3 fields, we can check this by checking the length of the array we got above. If the length is less than 3, we should output some error message and skip that line.
if(bookDetails.length<3){ //title,author,year
System.err.println("Some error message here"); // output error msg
continue; // skip this line as the format is corrupted
}
Finally, since we have read and verified that the information we need is there, and is in the valid format. We can create a new object and add it to the list. We will use the Integer wrapper built into Java to parse the year into a primitive int type for the Book class constructor. The Integer has a function Integer.parseInt(String s) that will parse a String into an int value.
list.add(new Book(bookDetails[0], bookDetails[1], Integer.parseInt(bookDetails[2])));
Hopefully this helps you out, and answers your question. A full method of what we did could be the following:
public static List<Book> getList(String file) {
List<Book> list = new ArrayList<Book>();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
String[] bookDetails = line.split(",");
if (bookDetails.length < 3) { // title,author,year
System.err.println("Some error message here");
continue;
}
list.add(new Book(bookDetails[0], bookDetails[1], Integer.parseInt(bookDetails[2])));
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
And if you would like to test this, a main method can be made with the following code (this is how I tested it).
public static void main(String[] args) {
String file = "books.csv";
List<Book> books = getList(file);
for(Book b : books){
System.out.println(b);
}
}
To test it, make sure you have a file (mine was "books.csv") in your root directory of your Java project. Mine looked like:
bob,jones,1993
bob,dillon,1994
bad,format
good,format,1995
another,good,1992
bad,format2
good,good,1997
And with the above main method, getList function, and file, my code generator the following output (note: the error messages were in red for the Std.err stream, SO doesn't show colors):
Some error message here
Some error message here
[title=bob, author=jones, years=1993]
[title=bob, author=dillon, years=1994]
[title=good, author=format, years=1995]
[title=another, author=good, years=1992]
[title=good, author=good, years=1997]
Feel free to ask questions if you are confused on any part of it. The output shown is from a toString() method I wrote on the Book class that I used for testing the code in my answer.
You can use a do while loop and read it till the end of file. Each new line will represent a Book Object detail.
In a csv all details are comma separated, So you can read the string and each comma will act as a delimiter between attributes of Book.