I am basically making a hangman game...
package wordguessinggame2;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class WordGuessingGame2 {
private static String playerInput;
private static String randomWord;
static class RandomWordProvider {
public final List<String> words;
public RandomWordProvider() {
words = readFile();
}
public int randomInteger() {
int randomInt = (int) (Math.random() * words.size());
return randomInt;
}
public String getWord() {
int randomPosition = randomInteger();
String randomWord = words.get(randomPosition);
return randomWord;
}
private List<String> readFile() {
List<String> wordsList = new ArrayList<>();
try {
File fourLetterWords = new File(System.getProperty("user.home"),"Documents/FourLetterWords.txt");
Scanner in = new Scanner(fourLetterWords);
while (in.hasNextLine()) {
String line = in.nextLine();
if (line!=null && !line.isEmpty()) {
wordsList.add(line);
}
}
}
catch (FileNotFoundException ex) {
System.out.println("\nFile not found.");
System.exit(0);
}
return wordsList;
}
}
public WordGuessingGame2(String playerInput) {
WordGuessingGame2.playerInput = playerInput;
}
public String getPlayerInput() {
return playerInput;
}
public void setPlayerInput(String playerInput) {
WordGuessingGame2.playerInput = playerInput;
}
public static class PlayerCharacterEntry{
private String playerEntry() {
Scanner characterEntry = new Scanner(System.in);
System.out.print("Enter a character: ");
String playerInput = characterEntry.next();
playerInput = playerInput.toUpperCase();
return playerInput;
}
}
public static void main(String[] args) {
Scanner wantToPlay = new Scanner(System.in);
System.out.print("Welcome to the word guessing game! Would you like to play? ");
String playerAnswer = wantToPlay.next();
if (playerAnswer.equalsIgnoreCase("Yes")) {
System.out.print("\nYour objective is to guess a four letter word by entering"
+ "\nletters on your keyboard. If you can not guess the word in seven attempts,"
+ "\nyou lose! You will be told if the letter you entered is in the word, and"
+ "\nyou will be told if the letter you entered is not in the word. You will be"
+ "\nallowed to guess the word any time during your seven attempts. If at anytime"
+ "\nyou would like to terminate the game, enter the word 'terminate'. Good Luck!"
+ "\n \n");
}
if (playerAnswer.equalsIgnoreCase("No")) {
System.out.print("Maybe another time!");
System.exit(0);
}
RandomWordProvider randomWordProvider = new RandomWordProvider();
PlayerCharacterEntry playerCharacterEntry = new PlayerCharacterEntry();
randomWordProvider.getWord();
playerCharacterEntry.playerEntry();
if (randomWord.contains(playerInput)){
System.out.println(playerInput);
} else {
System.out.println("That letter is not in the word!");
}
}
}
Here at the bottom I am trying to determine if the letter that the player enters is in the word, then to display that letter, but when I run the program and I input a letter, I get a NullPointerException where I say:
if(randomWord.contains(playerInput))
I believe it has something to do with randomWord but I don't know how to fix it.
You never assign anything to WordGuessingGame2.randomWord to it stays null.
You need to replace
randomWordProvider.getWord();
with
randomWord = randomWordProvider.getWord();
you have to put a correct path.. try this :
File fourLetterWords = new File(System.getProperty("user.home"),"/Documents/FourLetterWords.txt");
you never initialize the class variable randomWord
Related
I wanna make a condition if somebody input a word the program will return "That is a string" if it is an integer the program will return "That is an integer ". What's wrong with my if condition ?
package folder;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner skaner = new Scanner(System.in);
while (skaner.hasNext()){
if (skaner.next() != int) {
System.out.println("That is a string" + skaner.next());
}
else {
System.out.println("That is an integer " + skaner.next());
}
}
skaner.close();
}
}
Here skaner.next() will return a String object whereas int is a primitive data type and therefore both are not comparable. To check if token returned by skaner.next() is an int or not, you can use Integer.parseInt(skaner.next()) which converts String to int and throws a NumberFormatException if input is not a valid integer.
package folder;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner skaner = new Scanner(System.in);
while (skaner.hasNext()){
String x = skaner.next();
try {
int y = Integer.parseInt(x);
System.out.println("That is an integer " + y);
}
catch(NumberFormatException e) {
System.out.println("That is a string " + x);
}
}
skaner.close();
}
}
Check this link for reference.
I am a beginner to Java; I am trying to append text to a text file that was previously created using the File class and writing to the file using PrintWriter. When I call the first method in my main class the file is created and works. However, when I call the second method "try" is called, but no new text is added to the .txt file. I put the second method into a separate public class but I ran into the same issue. Do I need to initialize the fileName variable again?
Many thanks.
package project;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class WriteOut {
private int NumberOfMember;
private String ProjectName;
private String[] TeamMember;
public static String fileName;
private int[][] Vote;
public int FirstExport(int NumberOfMember, String ProjectName, String[] TeamMember) {
Scanner scan = new Scanner(System.in);
String fileName="ok"; //initializing the file name
System.out.println("Enter a file name to hold the Project:");
fileName = scan.nextLine( );
File fileObject = new File(fileName+".txt");
while (fileObject.exists( ))
{
System.out.println("There already is a file named "
+ fileName);
System.out.println("Enter a different file name:");
fileName = scan.nextLine( );
fileObject = new File(fileName+".txt");
}
PrintWriter outputStream = null;
try
{
outputStream =
new PrintWriter(new FileOutputStream(fileName+".txt"));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName +".txt");
System.exit(0);
}
for (int MemberCount = 1; MemberCount <= NumberOfMember; MemberCount ++) //For as long as the member count is less than the total number of members, the program will ask for the user input
{
//Statement of variable allocation to corresponding member position
outputStream.println("Team Member"+(MemberCount)+ ":"+TeamMember[MemberCount - 1]);
}
outputStream.println("Number of Members:"+ NumberOfMember+ "\nProject Name:"+ProjectName);
outputStream.close();
return NumberOfMember;
}
public int[][] SecondExport(int[][] Vote) {
System.out.println("hello"); //test to see if this is being called correctly
try
{
String content = "This is the content to write into file"; //Test content
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName+".txt", true));
bw.append(content);
System.out.println("Done"); //Test to see if this is being called
bw.flush();
bw.close();
} catch (IOException e)
{
e.printStackTrace();
}
return Vote;
}
}
My main class calls the WriteOut class under the EnterVotes() method:
package project:
import java.util.Scanner; //Importing the scanner tool
import java.util.stream.IntStream; //for summing arrays
import java.io.FileNotFoundException;
import java.text.DecimalFormat; //Importing the decimal tool
public class Project
{
public static void main(String[] args)
{
Project run = new Project();
run.StartMenu();
}
public static String option; //Declaring the strings representing the menu option buttons
private static int NumberOfMember; //Entering the number of members
public static int index=NumberOfMember; //used for later, declaring a square matrix
public static String[] TeamMember; //Declaring the strings representing the names of the members
public static int[][] Vote;
public static String ProjectName; // Declaring the project name variable as a string
private static boolean CorrectInput, ShowMenu; //Booleans CorrectInput, which determines whether the user has entered a valid input and ShowMenu, which determines whether the main menu is displayed again
public String fileName;
static Scanner scan = new Scanner(System.in); // Importing the scanner tool
DecimalFormat twoDecPlcFormatter = new DecimalFormat("0.00"); //Although not used currently, having a decimal formatter could come in handy later
//----------------------------------------------
//Declaration of StartMenu(): listing Menu Options and equalsIgnoreCase to accept either upper or lower case
//----------------------------------------------
Project(){
}
public void StartMenu()
{
Scanner scan = new Scanner(System.in);
System.out.println();
System.out.print("\nWelcome to Splitit ");
do
{
printMenu();
char input = scan.next().charAt(0); //Asking user to input a character
option = Character.toString(input); //Converting from characters to string
checkInput(option);
}
while (CorrectInput == false || ShowMenu == true); //Run StartMenu() while either the CorrectInput is false or ShowMenu is true
}
//----------------------------------------------
//Declaration of checkInput(String OneInput) method
//----------------------------------------------
private void checkInput(String OneInput)
{
if (OneInput.equalsIgnoreCase("A") == true)
{
About();
}
else if (OneInput.equalsIgnoreCase("C") == true)
{
CreateProjectTitle();
}
else if (OneInput.equalsIgnoreCase("V") == true)
{
EnterVotes();
}
else if (OneInput.equalsIgnoreCase("S") == true)
{
ShowProject();
}
else if (OneInput.equalsIgnoreCase("Q") == true)
{
Quit();
}
else
{
System.out.print("\tIncorrect input. "); //If the user has entered an incorrect input, force them to enter in correct input
CorrectInput = false;
}
}
private void printMenu()
{
System.out.println("\n\n\tAbout\t\t(A)");
System.out.println("\tCreate Project\t(C)");
System.out.println("\tEnter Votes\t(V)");
System.out.println("\tShow Project\t(S)");
System.out.println("\tQuit\t\t(Q)");
System.out.print("\n\tPlease choose an option: ");
}
//----------------------------------------------
//Declaration of About() method
//----------------------------------------------
public void About()
{
System.out.println("\tThis is a program designed to assign grades for a project based on each member's \n \tparticipation. ");
}
//----------------------------------------------
//Declaration of ShowProject()
//----------------------------------------------
public void ShowProject()
{
CorrectInput = true;
ShowMenu = true;
StoreVariables getThings = new StoreVariables();
System.out.println("Number of members: " + getThings.getNumberofMember(NumberOfMember));
System.out.println("Project name: " + getThings.getProjectName(ProjectName));
String[] abc = getThings.getTeamMember();
for (int Counter = 1; Counter <= NumberOfMember; Counter ++) //Returning each team member's name and corresponding member number
{
System.out.println("Name of member " + Counter + " : " + getTeamMemberName(Counter));
}
for (int Counter = 1; Counter <= NumberOfMember; Counter ++) //Returning each team member's name and corresponding member number
{
System.out.println("Votes for Member " + TeamMember[Counter-1] + " : ");
System.out.print(getThings.getVotes(Vote));
}
}
//----------------------------------------------
//Declaration of EnterVotes()
//----------------------------------------------
public int[][] EnterVotes()
{
CorrectInput=true;
Vote = new int [NumberOfMember][index];
index=NumberOfMember;
if (NumberOfMember==0) {
System.out.println("Please Create a Project Before Entering Votes!"); //Error Message
ShowMenu=true;
}
for (int row=0; row < Vote.length; row++)
{
System.out.println("Enter "+ TeamMember[row]+"'s votes, points must add up to 100:");
System.out.println();
for (int col=0; col < Vote[row].length; col++)
{
System.out.println("Enter "+TeamMember[row]+ "'s points for"+ TeamMember[col]+":");
Vote[row][col] = scan.nextInt();
}
}
//if (sum!=100){
//System.out.println("Error. Please make sure all votes add up to 100.");
//EnterVotes();
//}
sumRow(Vote, NumberOfMember);
return Vote;
}
public int[] sumRow(int[][] Vote, int NumberOfMember)
{
int sum[] = new int[NumberOfMember];
for (int i = 0; i < Vote.length; i++){
int total = 0;
for (int j = 0; j < Vote[0].length; j++)
total +=Vote[i][j];
sum[i] = total;}
for(int i = 1; i < sum.length; i++)
{
if (sum[i] != 100) {
System.out.println("Please Make Sure the points add to 100!");
EnterVotes();
}
}
WriteOut getsecond = new WriteOut();
getsecond.SecondExport(Vote);
return sum;
}
//----------------------------------------------
//Declaration of CreateProject()
//----------------------------------------------
public String CreateProjectTitle()
{
CorrectInput = true;
ShowMenu = true; //Still show Menu
System.out.print("\n\tEnter the project name: "); //Asking user for a project name
ProjectName = scan.next();
CreateProjectNumberofMembers(); //calling methods within the resulting methods
CreateProjectNamesofMembers();
return ProjectName;
}
public int CreateProjectNumberofMembers(){ //ENTER NUMBER OF TEAM MEMBERS
System.out.print("\tEnter the number of team members: "); //Asking user to input a number for all members count
NumberOfMember = scan.nextInt();
System.out.print("\n");
return NumberOfMember;
}
public String[] CreateProjectNamesofMembers(){
TeamMember = new String[NumberOfMember];
for (int MemberCount = 1; MemberCount <= NumberOfMember; MemberCount ++) //For as long as the member count is less than the total number of members, the program will ask for the user input
{
//Statement of variable allocation to corresponding member position
System.out.print("\tEnter the name of team member " + MemberCount + ": ");
TeamMember[MemberCount - 1] = scan.next();
}
WriteOut getThings2= new WriteOut();
getThings2.FirstExport(NumberOfMember, ProjectName, TeamMember);
System.out.print("Press any key to return to the main menu: ");
String DummyInput = scan.next(); //This is a dummy variable where the input is never used again
ShowMenu = true; //Irrespective of the input, the menu will be shown again by assigning this boolean to tr
return TeamMember;
}
//----------------------------------------------
//Declaration of Quit() method
//----------------------------------------------
public void Quit()
{
CorrectInput = true;
ShowMenu = false; //if ShowMenu is false, the program's menu will terminate
//WriteOut();
System.out.println("\tGoodbye. ");
scan.close();
}
//--------------------------------------------------------------------------------
//Declaration of toString() method to check for all variable values when necessary
//--------------------------------------------------------------------------------
private String getNumberOfMember()
{
return Integer.toString(NumberOfMember);
}
private String getProjectName(int NumberOfProjects)
{
return ProjectName;
}
private String getTeamMemberName(int index)
{
return TeamMember[index - 1];
}
}
You have a field in class WriteOut:
public static String fileName;
and then a local variable in FirstExport with the same name:
String fileName="ok"; //initializing the file name
the local variable takes precedence inside FirstExport and the field is null when you get in SecondExport. You'll get what I understand is the expected behaviour if you just delete the local variable declaration.
Delete the local variable in your method FirstExport:
String fileName="ok";
You only want to use your public field
public static String fileName;
so you can access it from both methods.
My code creates a set of sport results using a scanner, the user enters input in this format "Home team : Away team : Home score : Away score" - each part is split into a string in the array. I want to create an error message if one part is missing for example "Error, Home team seems to be missing" for each corresponding section however;
I am a beginner and have been trying to put an else-if condition in the for loop to help make this error message however I am doing something wrong judging by the amount of errors I am getting (delete this token).
This code will help your program to validate the user-input as per the your requirements in your question, if any of the inputs is missed by the user it is reported to him:
import java.util.Scanner;
public class Test4 {
public static void ismissing(int i)
{
switch(i)
{
case 0:
System.out.println("Home team missing");
break;
case 1:
System.out.println("Away team missing");
break;
case 2:
System.out.println("Home score missing");
break;
case 3:
System.out.println("Away score missing");
break;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input as follows; ");
System.out.println("Home team : Away team : Home score : Away score");
String str=scanner.nextLine();
String array[]=str.split(":");
for(int i=0;i<array.length;i++)
{
if(array[i].equals(" "))
{
ismissing(i);
System.exit(0); //will exit program if something is missing
}
}
System.out.println("Correct Input");
}
}
If you are going to be creating numerous games, I would recommend you make a Game class as this will make it easier to manage a Game object as opposed to 2 Strings and 2 Integer values. With a Game object you can also output your desired string output using the toString method of your Game object. When getting the user input, the criteria I used is such that team names cannot be blank and team scores cannot be less than 0. If the user enters and empty string or an invalid integer, then we simply output a message indicating the invalid input and have the user try again until they get valid input. If you want to exit when this happens you could change this to accommodate a graceful exit of the program when the user enters invalid data.
I made two methods in the main, one to get a valid String team name, and another to get a valid Integer for the score. Again if the user inputs invalid data we will loop until the input is valid.
Game Class:
public class Game
{
String homeTeam = "";
String awayTeam = "";
int homeScore = -1;
int awayScore = -1;
public Game(String inHomeTeam, int inHomeScore, String inAwayTeam, int inAwayScore)
{
super();
this.homeTeam = inHomeTeam;
this.awayTeam = inAwayTeam;
this.homeScore = inHomeScore;
this.awayScore = inAwayScore;
}
#Override
public String toString()
{
return homeTeam + "[" + homeScore + "] | " + awayTeam + "[" + awayScore + "]";
}
public String getHomeTeam() {
return homeTeam;
}
public void setHomeTeam(String homeTeam) {
this.homeTeam = homeTeam;
}
public String getAwayTeam() {
return awayTeam;
}
public void setAwayTeam(String awayTeam) {
this.awayTeam = awayTeam;
}
public int getHomeScore() {
return homeScore;
}
public void setHomeScore(int homeScore) {
this.homeScore = homeScore;
}
public int getAwayScore() {
return awayScore;
}
public void setAwayScore(int awayScore) {
this.awayScore = awayScore;
}
}
Main
public class Main
{
static Scanner scanner = new Scanner(System.in);
static Game[] allGames;
static String homeTeam = "";
static String awayTeam = "";
static int homeScore = -1;
static int awayScore = -1;
static int numberOfGames = 0;
public static void main(String[] args)
{
numberOfGames = GetUserInt("How many games do you want to enter - 100 or less: ");
if (numberOfGames > 100)
numberOfGames = 100;
allGames = new Game[numberOfGames];
for (int i = 0; i < numberOfGames; i++) {
homeTeam = GetUserString("Enter the home team name: ");
homeScore = GetUserInt("Enter the home team score: ");
awayTeam = GetUserString("Enter the away team name: ");
awayScore = GetUserInt("Enter the away team score: ");
allGames[i] = new Game(homeTeam, homeScore, awayTeam, awayScore);
}
// output the users games
for(Game curGame : allGames)
{
if (curGame != null)
System.out.println(curGame.toString());
}
}
private static String GetUserString(String prompt)
{
String input = "";
while(true) {
System.out.print(prompt);
input = scanner.nextLine();
if (input.length() > 0)
return input;
else
System.out.println("Invalid input: Can not be empty string!");
}
}
private static int GetUserInt(String prompt)
{
String input = "";
while(true) {
System.out.print(prompt);
input = scanner.nextLine();
if (input.length() > 0) {
if (isValidInt(input)) {
int value = Integer.parseInt(input);
if (value >= 0) {
return value;
}
else {
System.out.println("Invalid input: Score can not be negative");
}
}
else {
System.out.println("Invalid input: Score must be a valid integer");
}
}
else {
System.out.println("Invalid input: Score can not be empty");
}
}
}
private static boolean isValidInt(String inString)
{
try {
Integer.parseInt(inString);
return true;
}
catch (NumberFormatException e) {
return false;
}
}
}
Hope this helps!
There are some things you can do, like checking the values with an if statement. You can say something like:
if(stringIsEmpty)
{
print ("Error");
}
else
{
/*Keep executing program*/
}
You could also use a try/catch block. This could help because if a string is null (empty), you can throw a null pointer exception and define it the way you want, like this:
try
{
/*blank string code*/
}catch(NullPointerException e)
{
System.out.println("Empty strings are not allowed");
}
I am making a game-ish type of thing with three classes, combined. NOT HOMEWORK; hobby.
Codes for three classes:
Runner:
public class CounterGameRunner
{
// instance variables - replace the example below with your own
public static void main(String [] args){
Scanner input = new Scanner(System.in);
CounterGameCounter game = new CounterGameCounter();
System.out.println("You want to play a game I see. What is your name?");
String name = input.next();
game.NameIn(name);
CounterGAME game1 = new CounterGAME();
game1.actual();
}
}
Actual Game:
public class CounterGAME
{
// instance variables - replace the example below with your own
Scanner input = new Scanner(System.in);
int number;
int count=1;
boolean loop = true;
public CounterGAME(){
}
public void actual(){
CounterGameCounter game2 = new CounterGameCounter();
System.out.println("Guess a number between 1 and 101, see how many times you get it!");
number=input.nextInt();
int r = (int)(Math.random() * (100) + 1);
while(loop==true){
if(number < r){
System.out.println("Too small, try again");
number = input.nextInt();
count++;
game2.Counter(count);
} else if(number == r){
System.out.println("Wow, you won! Who'd have thought?");
count++;
game2.Counter(count);
break;
System.out.println(game2.done());
} else if(number > r){
System.out.println("Too large, try again");
number = input.nextInt();
count++;
game2.Counter(count);
}
}
}
}
Counter Class:
public class CounterGameCounter
{
// instance variables - replace the example below with your own
private String Name;
String done1;
int correct;
public CounterGameCounter(){
}
public String NameIn (String nm){
Name = nm;
return Name;
}
public String NameOut(){
return Name;
}
public void Counter(int count){
correct = count;
}
public int getCount(){
return correct;
}
public String done(){
done1 = "Name: " + NameOut() + "\n" +
"Times Answered: " + getCount();
return done1;
}
}
Problem:
The counter works properly and everything else displays and functions properly in the end. However, any name I input in the beginning always shows "null" while running the program. Why?
Your variable names are really confusing, and there are a lot of bad practices in your code, but null in name is because you create a new Counter in CounterGAME:
public void actual(){
// here
CounterGameCounter game2 = new CounterGameCounter();
// more code
}
Change actual to receive a CounterGameCounter:
public void actual(CounterGameCounter game2){
// more code
}
And call it like:
public static void main(String [] args){
Scanner input = new Scanner(System.in);
CounterGameCounter game = new CounterGameCounter();
System.out.println("You want to play a game I see. What is your name?");
String name = input.next();
game.NameIn(name);
CounterGAME game1 = new CounterGAME();
game1.actual(game);
// more stuff
}
FREE TIPS:
use String getName() and void setName(String)
start variable, object and attribute names with lowercase
String name;
Object object;
Variable names must be representative and descriptive
CounterGameCounter counterGameCounter = new CounterGameCounter();
This is also applicable to Object names:
GameCounter gameCounter = new CounterGameCounter();
try this:
String name = input.nextLine();
instead of:
String name = input.next();
This project is a dictionary program that is editable. Short and sweet i am trying to loop through the words already added to the dictionary and compare the users input with a scanner to the words already added.
My issue is that no matter how accurate the input, the exception i created is always being called.
I am not sure if the exception is wrong or if the strings are not comparing correctly. The dictionary words are read from a file called "dictionary.txt" The program uses input/output if that helps. Here is the code....
Please help!!
import java.util.ArrayList;
public class Dictionary {
ArrayList <Word> Words;
public Dictionary(){
Words = new ArrayList <Word>();
}
public void addWord(String name, String definition){
Word word = new Word(name, definition);
Words.add(word);
}
public String findWord(String name){
String word = "";
for (int i = 0; i < Words.size(); i++){
if (name.equalsIgnoreCase(Words.get(i).getName())){
Words.get(i);
}
word += Words.get(i).getName();
}
return word;
}
public String findDefinition(String name){
String def = "";
for (int i = 0; i < Words.size(); i++){
if (name.equalsIgnoreCase(Words.get(i).getName())){
Words.get(i);
}
def += Words.get(i).getDefinition();
}
return def;
}
public String toString(){
String temp = "";
for (int i = 0; i < Words.size(); i++ ){
temp += Words.get(i).getName() + " - " + Words.get(i).getDefinition() + "\n";
}
return temp;
}
public class Word {
String name;
String definition;
public Word(String name, String definition){
this.name = name;
this.definition = definition;
}
public String getName(){
return name;
}
public String getDefinition(){
return definition;
}
}//End Word
}//End dictionary
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
public class Read {
private static Scanner in;
public static void main(String[] args) throws FileNotFoundException {
File Read = new File ("Dictionary.txt");
in = new Scanner (Read);
//ArrayList called save
Dictionary save = new Dictionary();
while (in.hasNext()){
String w1 = in.next();
String w2 = in.nextLine();
save.addWord(w1, w2);
}
System.out.println(save);
String newLine = System.getProperty("line.separator");
System.out.println("Press 1 for Menu");
Scanner en = new Scanner(System.in);
int choice = en.nextInt();
while (choice == (1)){
System.out.println("What would you like to do?"
+ newLine + "1 - List all Words and Definitions"
+ newLine + "2 - List definition for word"
+ newLine + "3 - Change definition"
+ newLine + "4 - Add new word"
+ newLine + "5 - Exit");
int input = en.nextInt();
switch(input){
case 1: System.out.println(save);
break;
case 2: System.out.println("Which word definition would you like to see?");
try{
String type = en.next();
if (type.equalsIgnoreCase(save.findWord(type))){
System.out.println("The word you chose is: " + save.findWord(type));
}
else{
throw new InvalidNameException();
}
}
catch (InvalidNameException n){
}
finally {System.out.println("Sorry, that word cannot be found.");
}
break;
case 3: System.out.println("Which word definition would you like to change?");
try{
String def = en.next();
if (def.equalsIgnoreCase(save.findWord(def))){
System.out.println("What will be the new definition for: " + save.findWord(def));
String define = en.next();
save.addWord(def, define);
}
else{
throw new InvalidNameException();
}
}
catch (InvalidNameException n){
}
finally {System.out.println("Sorry, that word cannot be found.");
}
break;
case 4: System.out.println("Enter your new word");
String wrd = en.next();
System.out.println("What is the definition of this word?");
String define = en.next();
save.addWord(wrd, define);
break;
case 5: PrintStream fin = new PrintStream(new File("Dictionary.txt"));
fin.println(save);
break;
}
}
}
}//End Read
public class InvalidNameException extends Exception{
public InvalidNameException() {
System.out.println("Not a valid word");
}
}//End exception
I changed te findWord metod to this:
public Word findWord(String name){
Word word = new Word("","");
for (int i = 0; i < Words.size(); i++){
if (name.equalsIgnoreCase(Words.get(i).getName())){
word = Words.get(i);
}
}
return word;
}
but now there is an issue with the object types in my Read class in this area:
try{
String def = en.next();
if (def.equalsIgnoreCase(save.findWord(def))){
System.out.println("What will be the new definition for: " + save.findWord(def));
String define = en.next();
save.addWord(def, define);
}
Scanner#next() just returns the next token. What you want is Scanner#nextLine().
your findWord/findDef is wrong,
public String findWord(String name){
String word = "";
for (int i = 0; i < Words.size(); i++){
if (name.equalsIgnoreCase(Words.get(i).getName())){
Words.get(i);
}
word += Words.get(i).getName();
}
return word;
}
The if block doesn't actually do anything useful, try moving the line below into your if block (do this for both methods)