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)
Related
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.
So, basically I have an assignment that requires for me to Write a java program to help maintain a class roll. The program must contain four classes: Student, Exams, ClassRoll and Assignment4(Main).
I have developed all the classes but the ClassRoll constructor it s not performing correctly. When I run the program I am prompted with the file name option, once i enter the file name I see null then the options to modify and / or display the list, but when I enter a command, it does not work, it gives me an error.
The Output should be
Expected input/output:
Assuming that the file data.txt contains:
COP2210
John Doe 50 60 70
Marco Boyle 50 60 73
Eric Munzon 45 100 90
Marry Able 95 100 100
Jack Smith 100 100 100
Elizabeth Gomez 100 100 100
The following is a sample input output run:
What is the name of input file: data.txt
Enter one of the following commands
a or add to add a student in the class roll
sa or average to sort the students based on their average
sn or names to sort the students based on their last names
r or remove to remove a student from the class roll
s or save to save the list of students back to the datafile
Here are my classes;
public class Student {
private String fName = "";
private String lName = "";
private Exam scores;
public Student(String f, String l){
fName=f;
lName=l;
scores = new Exam();
}
public void setScore1(int score) {
scores.setScore1(score);
}
public void setScore2(int score) {
scores.setScore2(score);
}
public void setScore3(int score) {
scores.setScore3(score);
}
public String toString() {
return lName + "\t" + fName + "\t" +
scores.toString();
}
public double getAverage() {
return (scores.getScore1() + scores.getScore2() +
scores.getScore3())/3.0;
}
public boolean equals(String f, String l) {
return f.equals(fName) && l.equals(lName);
}
public int compareTo(Student s){
if (lName.compareTo(s.lName) > 0)
return 1;
else if (lName.compareTo(s.lName) < 0)
return -1;
else if (fName.compareTo(s.fName) > 0)
return 1;
else if (fName.compareTo(s.fName) < 0)
return -1;
else return 0;
}}
public class Exam {
private int score1;
private int score2;
private int score3;
public Exam(){
score1=0;
score2=0;
score3=0;
}
public void setScore1(int score) {
score1=score;
}
public int getScore1() {
return score1;
}
public void setScore2(int score) {
score2=score;
}
public int getScore2() {
return score2;
}
public void setScore3(int score) {
score3=score;
}
public int getScore3() {
return score3;
}
public String toString() {
return Integer.toString(score1) + "\t"
+Integer.toString(score2)
+ "\t" + Integer.toString(score3) + "\t";
}}
public class ClassRoll {
ArrayList students = new ArrayList();
String title;
String fileName;
public ClassRoll(String f) throws IOException {
Scanner fileScan, lineScan;
String line;
fileName = f;
fileScan = new Scanner(new File(f));
title = fileScan.nextLine();
System.out.println("Title =" + title);
while (fileScan.hasNext()) {
line = fileScan.nextLine();
lineScan = new Scanner(line);
lineScan.useDelimiter("\t");
String lastName = lineScan.next();
String firstName = lineScan.next();
Student s = new Student(firstName, lastName);
s.setScore1(lineScan.nextInt());
s.setScore2(lineScan.nextInt());
s.setScore3(lineScan.nextInt());
students.add(s);
//display(students);
ClassRoll c = new ClassRoll();
c.display();
}
}
void display() {
DecimalFormat fmt = new DecimalFormat("0.00");
System.out.println("\t\t\t" + title);
double classAverage = 0.0;
for (int i = 0; i < students.size(); i++) {
Student s = (Student) students.get(i);
System.out.print(s.toString());
System.out.println("\t" + fmt.format(s.getAverage()));
classAverage = classAverage + s.getAverage();
}
System.out.println("\t\t\t" + fmt.format(classAverage /
students.size()));
}
public void insert() {
Scanner input = new Scanner(System.in);
System.out.print("First Name -> ");
String firstName = input.next();
System.out.print("Last Name -> ");
String lastName = input.next();
System.out.print("Score 1 -> ");
int score1 = input.nextInt();
System.out.print("Score 2 -> ");
int score2 = input.nextInt();
System.out.print("Score 3 -> ");
int score3 = input.nextInt();
Student s = new Student(firstName, lastName);
s.setScore1(score1);
s.setScore2(score2);
s.setScore3(score3);
students.add(s);
}
private int search(String f, String l) {
int i = 0;
while (i < students.size()) {
Student s = (Student) students.get(i);
if (s.equals(f, l)) {
return i;
} else {
i++;
}
}
return -1;
}
public Student find() {
Scanner input = new Scanner(System.in);
System.out.print("First Name -> ");
String firstName = input.next();
System.out.print("Last Name -> ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
return (Student) students.get(i);
} else {
return null;
}}
public void delete() {
Scanner input = new Scanner(System.in);
System.out.print("First Name -> ");
String firstName = input.next();
System.out.print("Last Name -> ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
students.remove(i);
} else {
System.out.println("Student not found");
}
}
public void sortLastNames() {
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.compareTo(s2) > 0) {
students.set(i, s2);
students.set(j, s1);
}
}
}}
public void sortAverage() {
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.getAverage() < s2.getAverage()) {
students.set(i, s2);
students.set(j, s1);
}
}}}
public void save() throws IOException {
PrintWriter out = new PrintWriter(fileName);
out.println(title);
for (int i = 0; i < students.size(); i++) {
Student s = (Student) students.get(i);
out.println(s.toString());
}
out.close();
}}
public class Assignment4bis {
public static void main(String[] args) throws IOException {
Scanner input=new Scanner(System.in);
System.out.print("Enter the name of the input file ->");
String fileName=input.next();
ClassRoll c = new ClassRoll();
c.display();
prompt();
System.out.print("Enter a command --> ");
String ans=input.next();
while (!(ans.equalsIgnoreCase("q") || ans.equalsIgnoreCase("quit")))
{
if(!(ans.equalsIgnoreCase("i") ||ans.equalsIgnoreCase("insert") ||
ans.equalsIgnoreCase("a") || ans.equalsIgnoreCase("average") ||
ans.equalsIgnoreCase("n") || ans.equalsIgnoreCase("names") ||
ans.equalsIgnoreCase("r") || ans.equalsIgnoreCase("remove") ||
ans.equalsIgnoreCase("f") || ans.equalsIgnoreCase("find") ||
ans.equalsIgnoreCase("d") || ans.equalsIgnoreCase("display")))
System.out.println("Bad Command");
else
switch (ans.charAt(0))
{
case 'i': c.insert();
break;
case 'a': c.sortAverage();
c.display();
break;
case 'n': c.sortLastNames();
c.display();
break;
case 'r': c.delete();
c.display();
break;
case 'f': Student s=c.find();
if (s == null)
System.out.println("Student not found");
else System.out.println(s.toString());
break;
case 'd': c.display();
break;
}
prompt();
System.out.print("Enter a command --> ");
ans=input.next();
}
c.save();
System.out.println("Thank you for using this program");
}
public static void prompt(){
System.out.println("Enter one of the following commands");
System.out.println("i or insert to insert a student in the class
roll");
System.out.println("a or average to sort the students based on
their average");
System.out.println("n or names to sort the students based on their
last names");
System.out.println("r or remove to remove a student from the class
roll");
System.out.println("f or find to find a student in the class
roll");
System.out.println("d or display to display the class roll");
System.out.println("q or quit to exit the program");
}}
Errors that I m still getting...
run:
Enter the name of the input file ->data.txt
Title =COP2210
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at assignment4bis.ClassRoll.<init>(ClassRoll.java:40)
at assignment4bis.Assignment4bis.main(Assignment4bis.java:28)
Java Result: 1
Your ClassRoll "constructor" is a "pseudo-constructor":
public class ClassRoll {
ArrayList students = new ArrayList();
String title;
String fileName;
public void ClassRoll(String f) throws IOException {
Constructors have no return type, so get rid of the void:
public class ClassRoll {
ArrayList students = new ArrayList();
String title;
String fileName;
public ClassRoll(String f) throws IOException {
As a bit of side recommendations:
You look to be mixing user interface with one of your "model" or logical classes, ClassRoll, something you probably shouldn't do. I'd keep all user interface code, including use of a Scanner and File I/O separate from ClassRoll, which likely should just have code to create the collection, to allow other classes to add or remove from the collection, and to allow other classes to query the collection.
Take care to learn and follow Java code formatting rules. You've got some deviations from the standard, including have your class declaration lines indented the same as the method body and variable declaration lines, bunching up of end braces,... This makes your code hard for other Java coders to read and understand.
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
I have an assignment where the user is asked for baby name using a scanner. Then it reads through files names.txt and meanings.txt and returns the popularity of the name for each decade ranging from 1890 - 2010 then it prints out the meaning. Some names have multiple meanings and some are used in both genders. The assignment states to print only the first line where the name is found. I am having trouble only returning the first line in which the name is found. PLEASE HELP ME!
import java.io.*;
import java.util.*;
public class BabyNames4 {
public static void main(String[] args) throws FileNotFoundException {
printIntro();
Scanner console = new Scanner(System.in);
System.out.print("Name: ");
String searchWord = console.next();
Scanner fileScan = new Scanner(new File("names.txt"));
String dataLine = find(searchWord, fileScan);
if (dataLine.length() > 0) {
while (dataLine.length() > 0) {
printName(dataLine);
dataLine = find(searchWord, fileScan);
}
}
Scanner fileScan2 = new Scanner(new File("meanings.txt"));
String dataLine2 = find(searchWord, fileScan2);
if (dataLine2.length() > 0) {
while (dataLine2.length() > 0) {
printMeaning(dataLine2);
dataLine2 = find(searchWord, fileScan2);
}
}
}
public static void printIntro() {
System.out.println("This program allows you to search through the");
System.out.println("dada from the Social Security Administration");
System.out.println("to see how popular a particular name has been");
System.out.println("since 1890");
System.out.println();
}
public static String find(String searchWord, Scanner fileScan) {
while (fileScan.hasNextLine()) {
String dataLine = fileScan.nextLine();
String dataLineLC = dataLine.toLowerCase();
if (dataLineLC.contains(searchWord.toLowerCase())) {
return dataLine;
//} else { runs a continuous loop
//System.out.println(search" not found.");
}
}
return "";
}
public static void printName(String dataLine) {
Scanner lineScan = new Scanner(dataLine);
String name = lineScan.next();
String gender = lineScan.next();
String rank = "";
while (lineScan.hasNext()) {
rank += lineScan.next() + " ";
}
System.out.println(name + (" ") + gender + (" ") + rank);
}
public static void printMeaning(String dataLine2) {
Scanner lineScan2 = new Scanner(dataLine2);
String name2 = lineScan2.next();
String gender2 = lineScan2.next();
String language = lineScan2.next();
String meaning = "";
while (lineScan2.hasNext()) {
meaning += lineScan2.next() + " ";
}
System.out.println(name2 + (" ") + gender2 + (" ") + language + (" ") + meaning);
}
}
It looks like sushain hit it with his comment.
The loop:
while (dataLine2.length() > 0) {
printMeaning(dataLine2);
dataLine2 = find(searchWord, fileScan2);
}
could be changed to:
while (dataLine2.length() > 0) {
printMeaning(dataLine2);
break;
}
This way you do not find the second definition and do not print it.
In this loop, you don't need to find the next line, correct?
if (dataLine.length() > 0) {
while (dataLine.length() > 0) {
printName(dataLine);
dataLine = find(searchWord, fileScan); // remove this line
}
}
If you remove the next find to dataLine and remove the while blocks in both instances where you search the file, you won't need a break, and you'll only end up printing one instance.
Do this:
String dataLine = find(searchWord, fileScan);
if (dataLine.length() > 0) {
printName(dataLine);
}
I have a question with the display array method. I can't figure how to make it to format this:
Credit Card # 4:
8908 9014 8812 1331
What I need to do is for each array element call the display method and pass the index of the array in a string for the label, I just cant figure out how to do this, I tried this but it is wrong:
System.out.println(display("Credit Card # %d", cred1[i]));
Can anyone please suggest a way to do this?
package homework4;
import java.util.Scanner;
public class Prog4 {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{ CreditCardNumber[] cred1;
CreditCardNumber cred2 = getInput();
Display("The complete number from your input:", cred2);
cred1 = getInputArray();
DisplayArray(cred1);
TryAnother();
}
public static CreditCardNumber getInput() {
String ID;
String accNum;
CreditCardNumber tempCred;
System.out.printf("Please enter issuer ID:");
ID = scanner.next();
System.out.printf("Please enter account number:");
accNum = scanner.next();
tempCred = new CreditCardNumber(ID, accNum);
return tempCred;
}
public static void Display(String ch, CreditCardNumber cred2)
{
System.out.println(ch);
System.out.println(cred2.toString().replaceAll(".{4}", "$0 "));
}
public static CreditCardNumber[] getInputArray()
{
CreditCardNumber[] tempArray;
String tempID;
int size;
System.out.printf("Please enter size of the aray:");
size = scanner.nextInt();
if(size < 1)
{
size = 1;
}
tempArray = new CreditCardNumber[size];
System.out.printf("Please enter issuer ID:");
tempID = scanner.next();
System.out.print(tempArray.length);
for(int i = 0; i < tempArray.length; i++)
{
tempArray[i] = new CreditCardNumber();
tempArray[i].CreateCred(tempID);
}
return tempArray;
}
public static void DisplayArray(CreditCardNumber[] cred1)
{
for(int i = 0; i< cred1.length; i++)
{
System.out.println(display("Credit Card # %d", cred1[i]));
}
}
public static boolean TryAnother()
{
String s;
System.out.printf("Get more credit card numbers? (n for no):");
s = scanner.next();
if(s.charAt(0) != 'N' && s.charAt(0) != 'n')
{
return true;
}
return false;
}
}
sounds like all you need is a new line character. For example.
System.out.println("Credit Card # " + cred1[i] + "\n" + cred2.toString());
The new line character "\n" will drop the output onto it's own line.
Do this:
System.out.format("Credit Card # %d:\n%s", i, cred1[i].toString());