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);
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 am new to Java (along with programming in general). I was working on a personal project where a user types one character to which it is converted to another character. More specifically, a user would type a romanization of a Japanese character to which the Japanese hiragana equivalent is outputted. I am using two separate classes at the moment:
RomaHiraCore.java
import java.util.*;
public class RomaHiraCore
{
public static void main(String[] args)
{
Table.initialize(); // Table.java needed!
Map<String, String> table = Table.getTable();
Scanner roma = new Scanner(System.in);
System.out.println("Romaji: ");
String romaji = roma.nextLine().toLowerCase();
if (table.containsKey(roma))
{
System.out.println(table.get(roma));
}
else
{
System.out.println("Please enter a valid character (e. g. a, ka)");
}
roma.close();
}
}
Tables.java
import java.util.*;
public class Table
{
private static Map<String, String> table = new LinkedHashMap<>();
public static Map<String, String> getTable()
{
return table;
}
public static void initialize()
{
// a - o
table.put("a", "あ");
table.put("i", "い");
table.put("u", "う");
table.put("e", "え");
table.put("o", "お");
// ka - ko
table.put("ka", "か");
table.put("ki", "き");
table.put("ku", "く");
table.put("ke", "け");
table.put("ko", "こ");
}
}
If anyone can point me in the right direction, I would greatly appreciate it. I've attempted to go over the documentation, but I can't seem to grasp it (maybe I'm overthinking it). When I run the program, it allows me to enter a character; however, it will only continue to the "else" statement rather than scan Table.java to see if the input matches any of the values listed. Either I'm overlooking something or need to use an entirely different method altogether.
In your map, you have String keys, and the String which you provide is in the romaji variable. So your if should look like this: if (table.containsKey(romaji)). What is more, in this situation I think that using LinkedHashMap doesn't give you anything, simple HashMap would be as good as LinkedHashMap(even better), because you don't need to maintain insertion order of your characters.
In your main method, you are currently storing the string value inputted by the user however you never access that variable anywhere else.
You wrote table.containsKey(roma) however roma is the Scanner object and not the string they entered so you should be checking if that string is a valid key by using table.containsKey(romaji).
Next, in your else clause, you ask them to reenter an input but never provide them the chance to because you just terminate the scanner.
What you should be doing is something more like this.
String romaji = roma.nextLine().toLowerCase();
while (true) {
if (table.containsKey(romaji)) {
System.out.println(table.get(romaji));
break;
}
else {
System.out.println("Enter a valid char:";
romaji = roma.nextLine().toLowerCase();
}
}
roma.close();
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.
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.
I used the following coding to display user accounts in my domain.But in that coding it display only first 100 records.But in my domain nearly 500 users account.I don't know what problem in this coding
import java.net.URL;
import java.util.List;
import com.google.gdata.client.appsforyourdomain.UserService;
import com.google.gdata.data.appsforyourdomain.provisioning.UserEntry;
import com.google.gdata.data.appsforyourdomain.provisioning.UserFeed;
public class Readuser {
public int i3;
public String rn[]=new String[100];
public void read(){
try
{
// Create a new Apps Provisioning service
UserService myService = new UserService("My Application");
myService.setUserCredentials(admin,password);
// Get a list of all entries
URL metafeedUrl = new URL("https://www.google.com/a/feeds/"+domain+"/user/2.0/");
System.out.println("Getting user entries...\n");
UserFeed resultFeed = myService.getFeed(metafeedUrl, UserFeed.class);
List<UserEntry> entries = resultFeed.getEntries();
for(i3=0; i3<entries.size(); i3++) {
UserEntry entry = entries.get(i3);
rn[i3]= entry.getTitle().getPlainText();
System.out.println(rn[i3]);
}
System.out.println("\nTotal Entries: "+entries.size());
}
catch(Exception e) { System.out.print(e);}
}
public static void main(String args[])
{
Readuser ru=new Readuser();
ru.read();
}
}
You only allocate 100 entries.
public String rn[]=new String[100];
Hint from your code : public String rn[]=new String[100];
Do you really need to have i3 and rn as class members ? Do you really need rn ? A List seems more comfortable as an Object than a String[].
There is no need for the string array (String[]).
Arrays are fixed size; and in this case you have allocated 100 "slots" for Strings, and when You try to assign a string to position 100 ( you know, the 101:th string) it fails.
You catch an exception in the end. Print the stack trace to find out whats going on
catch(Exception e) {
e.printStackTrace();
}
Learn to read it an find out what is says... However you should not catch the exception in this method. It is better to abort whatever the program was doing. Catch it in your main method - just printing or logging it is fine, so that you can correct the programming error.
Anyway; The result you get is a List of user entries. Lists are part of the (java.util)collections framework. Collections have a lot of features; in this case you want to iterate over all entries in the list. You can do this by using the iterator() method -read the javadoc...OR you can use for-loop syntactic sugar for doing this:
for( UserEntry user : entries ) {
// user is the current UserEntry
System.out.println(user.getTitle().getPlainText());
}
The variables i3 and rn are no good... They shouldn't be class variables, and if you need "temporary" variables, define them close to where you are going to use them.
As for naming of variables, a name like "entry" is less useful than "user". Actually a class called UserEntry should probably be called just User, but I don't know about this API, so...