Dictionary in Java hashtables - java

I have a trouble with my program. I should to create a program like a dictionary. So I probably did it but it does not work. I have a menu so it should add/edit/delete word in file. please can you help me with my program, i think there are all understandable in my code. the problem is it can not find words in file in function
editWord, deleteWord. and serachTranslation
import java.util.*;
import java.io.*;
public class Dictionary{
public static Hashtable<String, String> dictionary = new Hashtable<String, String>();
public static void main(String []args)throws InputMismatchException, IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("dict.in")));
String line = null;
while((line = br.readLine())!= null ){
String [] words = line.split("\\s+");
String kaz = words[0];
String eng = words[1];
Dictionary.dictionary.put(kaz,eng);
}
menu();
}
public static void menu(){
//Runtime.getRuntime().exec("clear");
System.out.println("1 - Add/Edit/Delete word");
System.out.println("2 - Search translation");
//System.out.println("3 - Switch language");
Scanner sc = new Scanner(System.in);
System.out.println("Enter your choice: ");
int choose = sc.nextInt();
switch(choose){
case 1: secondMenu();
break;
case 2: searchTranslation();
break;
//case 3: System.out.print("It works 3 case");
//break;
default: menu();
break;
}
}
public static void secondMenu() throws InputMismatchException{
System.out.println("1 - Add");
System.out.println("2 - Edit");
System.out.println("3 - Delete");
System.out.println("4 - Back");
Scanner sc = new Scanner(System.in);
System.out.println("Enter your choice: ");
int choose = sc.nextInt();
switch(choose){
case 1: addWord();
break;
case 2: editWord();
break;
case 3: deleteWord();
break;
case 4: menu();
break;
default: secondMenu();
break;
}
}
public static void addWord(){
Scanner w = new Scanner(System.in);
System.out.println("Enter word in Kazakh language: ");
String kaz = w.next();
System.out.println("Enter word in English language: ");
String eng = w.next();
Dictionary.dictionary.put(kaz,eng);
System.out.println("Sucsess");
menu();
}
public static void editWord(){
Scanner w = new Scanner(System.in);
System.out.println("Enter word which you want to change: ");
String word = w.next();
Iterator s = Dictionary.dictionary.keySet().iterator();
while (s.hasNext()) {
String key = (String) s.next();
Object value = Dictionary.dictionary.get(key);
if(word==key){
System.out.println("Enter new meaning of this word: ");
String newWord = w.next();
Dictionary.dictionary.remove(key);
Dictionary.dictionary.put(word,newWord);
menu();
}
if(word==value){
System.out.println("Enter new meaning of this word: ");
String newWord = w.next();
Dictionary.dictionary.remove(value);
Dictionary.dictionary.put(newWord,word);
menu();
}
}
}
public static void deleteWord(){
Scanner w = new Scanner(System.in);
System.out.println("Enter word which you want to delete: ");
String word = w.next();
Iterator s = Dictionary.dictionary.keySet().iterator();
while (s.hasNext()) {
String key = (String) s.next();
Object value = Dictionary.dictionary.get(key);
if(word==key){
Dictionary.dictionary.remove(key);
menu();
}
if(word==value){
Dictionary.dictionary.remove(value);
menu();
}
}
}
public static void searchTranslation(){
Scanner w = new Scanner(System.in);
System.out.println("Enter word which you want to translate: ");
String word = w.next();
Iterator s = Dictionary.dictionary.keySet().iterator();
while (s.hasNext()) {
String key = (String) s.next();
Object value = Dictionary.dictionary.get(key);
if(word==key){
System.out.println(word+" : "+Dictionary.dictionary.get(value));
menu();
}
if(word==value){
System.out.println(word+" : "+Dictionary.dictionary.get(key));
menu();
}
}
}
}

The whole point of a Hashtable (you should use HashMap, by the way), is to be able to find a value by key without iterating. Use its get() method to find the meaning of a word, put() to insert/update a meaning of a word, and delete() to delete a word with its meaning.
The problem is that you're using == to compare Strings, instead of equals(), but you shouldn't even have to compare anything if you used to map as it should be used, since the map would do the comparisons for you.

Related

How to alphabetize a phonebook in a string

I have my PhoneBook program but I am trying to get the entries to automatically be put in alphabetical order when the user enter "l" for the list of entries. I can't figure out though how to do that. I've tried putting it into a list a sorting it that way but it only takes the first name of the entry.
import java.io.*;
import java.util.*;
class Entry {
public String fname, number, note, lname;
}
public class Main {
public static Entry[] contactList;
public static int num_entries;
public static Scanner stdin = new Scanner(System.in);
public static void main(String args[]) throws Exception{
int i; char C;
String code, Command;
contactList = new Entry[200];
num_entries = 0;
readPhoneBook("PhoneBook.txt");
System.out.println("Please Enter A Command.\nUse" +
" \"e\" for enter," +
" \"f\" for find," +
" \"l\" for listing all the entries," +
" \"m\" to merge duplicate entries," +
" \"d\" to delete an entry," +
" \"q\" to quit.");
Command = null;
C = ' ';
while(C != 'q'){
System.out.print("Command: ");
Command = stdin.next();
C = Command.charAt(0);
switch (C) {
case 'e': addContact(); break;
case 'f':
code = stdin.next();
stdin.nextLine();
i = index(code);
if (i >= 0) displayContact(contactList[i]);
else System.out.println("**No entry with code " + code); break;
case 'l':
listAllContacts(); break;
case 'q':
CopyPhoneBookToFile("PhoneBook1.txt");
System.out.println("Quitting the application. All the entries are "
+ "stored in the file PhoneBook1.txt"); break;
case 'm':
break;
case 'd':
break;
default:
System.out.println("Invalid command Please enter the command again");
}
}
}
public static void readPhoneBook(String FileName) throws Exception {
File F;
F = new File(FileName);
Scanner S = new Scanner(F);
while (S.hasNextLine()) {
contactList[num_entries]= new Entry();
contactList[num_entries].fname = S.next();
contactList[num_entries].lname = S.next();
contactList[num_entries].number = S.next();
contactList[num_entries].note = S.nextLine();
num_entries++;
}
S.close();
}
public static void addContact() {
System.out.print("Enter First Name: ");
String fname = stdin.next(); //First Name
stdin.nextLine();
System.out.print("Enter Last Name: ");
String lname = stdin.next(); //Last Name
String number;
stdin.nextLine();
contactList[num_entries] = new Entry();
contactList[num_entries].fname = fname; //Saves first name as fname
contactList[num_entries].lname = lname; //Saves last name as lname
System.out.print("Enter Number: ");
number = stdin.nextLine();
contactList[num_entries].number = number; //Saves phone number as number
System.out.print("Enter Notes: ");
contactList[num_entries].note = stdin.nextLine(); //saves any notes
num_entries++;
}
public static int index(String Key) {
// Function to get the index of a key from an array
// if not found, returns -1
for (int i=0; i < num_entries; i++) {
if (contactList[i].fname.equalsIgnoreCase(Key))
return i; // Found the Key, return index.
}
return -1;
}
public static void displayContact(Entry contact) {
System.out.println("--"+ contact.fname+"\t"+
contact.lname+"\t"+
contact.number+"\t"+
contact.note);
}
public static void listAllContacts() {
int i = 0;
while (i < num_entries) {
displayContact(contactList[i]);
i++;
}
}
public static void CopyPhoneBookToFile(String FileName) throws Exception{
FileOutputStream out = new FileOutputStream(FileName);
PrintStream P = new PrintStream( out );
for (int i=0; i < num_entries; i++) {
P.println(contactList[i].fname + "\t" + contactList[i].lname + "\t" + contactList[i].number +
"\t" + contactList[i].note);
}
}}
this is the bit for entering a new contact
public static void addContact() {
System.out.print("Enter First Name: ");
String fname = stdin.next(); //First Name
stdin.nextLine();
System.out.print("Enter Last Name: ");
String lname = stdin.next(); //Last Name
String number;
stdin.nextLine();
contactList[num_entries] = new Entry();
contactList[num_entries].fname = fname; //Saves first name as fname
contactList[num_entries].lname = lname; //Saves last name as lname
System.out.print("Enter Number: ");
number = stdin.nextLine();
contactList[num_entries].number = number; //Saves phone number as number
System.out.print("Enter Notes: ");
contactList[num_entries].note = stdin.nextLine(); //saves any notes
num_entries++;
}
I would make a compareTo method in your Entry class and set it up to compare how you want it to. The most important part would be how you store your Entries though. If you use a sorted array, you can just sort everything as you enter it into the array, and blast through linearly when you want to read it out

Why is my compiler giving the error "not a loop label 'moviesMenu'"

I don't know why but my compiler is giving "not a loop label 'moviesMenu'". I want to continue the menu.
I have made 5 classes
Games
Movies
TvShows
Music
Portal
This is Portal Test File. Have I made a mistake? I can't find it. This is a project for my OOP course and I'm making this as my project.
import java.util.*;
import java.util.Scanner;
public class PortalTest {
public static void main(String[] args) {
int moviesMenuInput;
Portal portal = new Portal();
Movies movies = new Movies();
Games games = new Games();
TvShows tvShows = new TvShows();
Music music = new Music();
portal.displayData();
Scanner input1 = new Scanner(System.in);
int menuInput = input1.nextInt();
moviesMenu:
{
switch (menuInput) {
case 1:
System.out.println("1 - ADD MOVIES");
System.out.println("2 - REMOVE MOVIES");
System.out.println("3 - SEARCH MOVIES");
System.out.println("4 - RETURN TO MENU");
Scanner input2 = new Scanner(System.in);
moviesMenuInput = input2.nextInt();
switch (moviesMenuInput) {
case 1:
System.out.println("Enter Movie Name : ");
Scanner input6 = new Scanner(System.in);
String addMoviesNameInput = input6.nextLine();
movies.setMovieName(addMoviesNameInput);
System.out.println("Enter Movie Release Date : ");
Scanner input7 = new Scanner(System.in);
String addMoviesReleaseDateInput = input7.nextLine();
movies.setMovieReleaseDate(addMoviesReleaseDateInput);
System.out.println("Enter Movie Genre : ");
Scanner input8 = new Scanner(System.in);
String addMoviesGenreInput = input8.nextLine();
movies.setMovieGenre(addMoviesGenreInput);
System.out.println("Enter Movie Download Link : ");
Scanner input9 = new Scanner(System.in);
String addMoviesDownloadLinkInput = input9.nextLine();
movies.setDownloadLink(addMoviesDownloadLinkInput);
System.out.println("MOVIE ADDED");
break;
case 2:
System.out.println("Enter Name of Movie to Delete : ");
Scanner input10 = new Scanner(System.in);
String deleteMoviesInput = input10.nextLine();
if (movies.getMovieName() == deleteMoviesInput) {
movies.setMovieName(null);
System.out.println("MOVIE DELETED ! ");
}
break;
case 3:
System.out.println("Enter Name of Movie to Search : ");
break;
}
continue moviesMenu;
}
}
Your label moviesMenudoesn't have a loop. That's why the error you're getting is not a loop label 'moviesMenu'.
To fix that, add a loop to your label:
moviesMenu:
while (true){
switch (menuInput) {
//The rest of your code...
break;
}
break;
}

My program method will not ouput anything

I am writing a program for homework where I am to modify a string using a menu. The rest of the code works fine except for one part that has me in a bind. I am using a method in order to find a word and all its occurrences in the String. Whenever I execute this method outside of a loop, I get the result I need, but whenever I use it inside of a while or switch statement, the program does not give me anything back. The method needs to return an int for the number of occurrences. This is the excerpt of that code:
import java.util.Scanner;
public class test {
public static Scanner scnr = new Scanner(System.in);
public static int findWord(String text, String userText) {
int occurance = 0;
int index = 0;
while (index != -1) {
index = userText.indexOf(text, index);
if (index != -1) {
occurance++;
index = index + text.length();
}
}
return occurance;
}
public static void main(String[] args) {
System.out.println("Enter a text: ");
String userText = scnr.nextLine();
System.out.println("Enter a menu option");
char menuOption = scnr.next().charAt(0);
switch (menuOption) {
case 'f':
System.out.println("Enter a phrase from text: ");
String text = scnr.nextLine();
int occurance = (findWord(text, userText));
System.out.println("" + text + " occurances : " + occurance + "");
break;
default:
System.out.println("Goodbye");
}
return;
}
}
Now a couple things I have noticed. If I prompt the user while inside the method, i do get back my integer, but not the text that i was looking for in order to complete my println inside the switch statement. And whenever i prompt the user for the word inside the switch statement, i get nothing back. If anyone has any solutions for me, i would greatly appreciate it, since i haven't a clue what i could be overlooking or missing.
You need to change char menuOption = scnr.next().charAt(0); to char menuOption = scnr.nextLine().charAt(0);.
The problem is with your Scanner method, which you are reading the continuously with scnr.next(), but should be changed to scnr.nextLine()` as shown below:
public static void main(String[] args) {
Scanner scnr = null;
try {
scnr = new Scanner(System.in);
System.out.println("Enter a text: ");
String userText = scnr.nextLine();
System.out.println("Enter a menu option");
char menuOption = scnr.nextLine().charAt(0);
switch (menuOption) {
case 'f':
System.out.println("Enter a phrase from text: ");
String text = scnr.nextLine();
int occurance = (findWord(text, userText));
System.out.println("" + text + " occurances : " + occurance + "");
break;
default:
System.out.println("Goodbye");
}
return;
} finally {
if(scnr != null)
scnr.close();
}
}
Also, ensure that you are closing the scanner object properly in thefinally block.

How can I properly read a line while I convert it into pig latin?

I got and I don't know why Exception in thread "main" java.util.InputMismatchException...I want to create a menu and transform a sentence inputed from the user into pig latin . How I can read a line properly without getting that exception ?
public class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
String options = "1.Print the options\n2.Transform a sentence into PIG latin\n" +
"3.quit";
System.out.println(options);
boolean quit = false;
while (!quit) {
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println(options);
break;
case 2:
encryptIntoPigLatin();
break;
case 3:
quit = true;
break;
}
}
}
private static void encryptIntoPigLatin() {
System.out.println("Please enter the sentence: ");
String sentence = "";
sentence = scanner.nextLine();
System.out.println(sentence);
StringTokenizer st = new StringTokenizer(sentence);
}
private static void printLatinWord(String s) {
String firstLetter = s.substring(0, 1);
StringBuilder result = new StringBuilder();
result.append(s.substring(1) + firstLetter + "ay");
System.out.println(result.toString());
}
}
Create 2 Scanners instances, one for the menu and the other one for the sentence
private static Scanner scannerMenu = new Scanner(System.in);
private static Scanner scannerSentence = new Scanner(System.in);
Your problem is that you are using the same scanner for the menu and the sentence. Keep in mind the the scanner you are using in the encryptIntoPigLatin() method is also nested in the while loop.

Programming "Add Method" array seems to not be working

Hi, I'm very new to java and I'm currently trying to create a student name and mark menu but I'm having trouble with my add method, I think it's something to do with my Arrays but I can't figure it out, any help would be appreciated.
Below is my unitResult method
public class UnitResults
{
private String unitTitle;
private String [] fName;
private String [] surname;
//private String [] UnitResults;
private int [] Marks;
private int Mark;
private int pointer ;
private static String course = "HND Computing";
public UnitResults(int Size,String title)
{
this.fName = new String [Size];
this.surname = new String [Size];
this.Marks = new int [Size];
pointer = 0;
fName[pointer] = "Daniel";
surname[pointer] = "Scullion";
Marks[pointer] = 60;
unitTitle = title;
pointer ++;
}
public Boolean add( String tempfName, String tempsName, int newGrade)
{
if (pointer == fName.length)
{
System.out.println("The Students Database is full");
return false;
}
else
{
fName [pointer] = tempfName;
surname [pointer] = tempsName;
Marks[pointer] = newGrade;
pointer ++;
return true;
}
}// end Add
but when I try to add this using a menu system below
int option = 0;
option = menuSystem();
while (option != 6)
{
System.out.println("");
switch(option)
{
case 1:
System.out.println(" Please Enter The Students First Name");
String tempfName = keyb.nextLine();
System.out.println("Please Enter The Students Last Name");
String tempsName = keyb.nextLine();
System.out.println(" Please Enter The Students Mark");
int newGrade = keyb.nextInt();
myUnit.add(tempfName, tempfName,newGrade);
break;
When I enter my option 1 the output that I get is :
Please Enter The Students First Name
Please Enter The Students Last Name
Any ideas what's wrong here been searching for a long time, probably something simple but I've no idea :/
Edit: below is my menu class
import java.util.Scanner;
public class MenuResults {
static Scanner keyb = new Scanner(System.in);
public static int menuSystem()
{
System.out.println("*********************************");
System.out.println(" ");
System.out.println("1.Add New Student");
System.out.println("2.Display Students Details");
System.out.println("3.Delete a Students");
System.out.println("4.Update Student Details");
System.out.println("5.Sort Students By Mark");
System.out.println("6.Sort Students By Surname");
System.out.println("7.Search For A Student");
System.out.println(" ");
System.out.println("**********************************");
System.out.print("\n Enter choice:");
int option = keyb.nextInt();
return option;
}
public static void main(String[] args) {
UnitResults myUnit = new UnitResults(3, "Java");
int option = 0;
option = menuSystem();
while (option != 6)
{
System.out.println("");
switch(option)
{
case 1:
System.out.println(" Please Enter The Students First Name");
String tempfName = keyb.nextLine();
System.out.println("Please Enter The Students Last Name");
String tempsName = keyb.nextLine();
System.out.println(" Please Enter The Students Mark");
int newGrade = keyb.nextInt();
myUnit.add(tempfName, tempsName,newGrade);
break;
case 2:
myUnit.display();
break;
case 3:
break;
case 4:
break;
case 5:
case 6:
break;
default:
System.out.println(" Invalid Entry");
}//end switch
}
}
}
There is my whole menu class as asked for.
EDIT: when I forget the user input and hard input it using: myUnit.add("John","tommy",12);
I get "Student Database is full" about one hundred times..
Wild guess, when you use your menu and type 1 then ENTER a carriage return (\n) for the ENTER is still present in your Scanner after nextInt() is called.
So next call to readLine() will use the \n (remaining ENTER) for the line and will not wait for user input.
Possible correction:
public static int menuSystem()
{
final Scanner keyb = new Scanner(System.in);
// ...
}
public static void main(String[] args) {
final UnitResults myUnit = new UnitResults(3, "Java");
int option = menuSystem();
while (option != 6) {
final Scanner keyb = new Scanner(System.in);
// ...
option = menuSystem();
}
}
And removal of the static kbd declaration
A better solution is to simply call keyb.nextLine() after calling keyb.nextInt() to handle the end of line token. Quite simply change this:
System.out.println(" Please Enter The Students Mark");
int newGrade = keyb.nextInt();
myUnit.add(tempfName, tempsName,newGrade);
to this:
System.out.println(" Please Enter The Students Mark");
int newGrade = keyb.nextInt();
keyb.nextLine(); // ****** add this *******
myUnit.add(tempfName, tempsName,newGrade);

Categories

Resources