Error: Could not find or load main class Disneyland - java

My code compiles and I have two text files that need to be read from the program but when I run the program I get the following error: the menuItems.txt contains:
Churro
Ice Cream
Hamburger
Cheese burger
Turkey Leg
Corn Dog
Pizza
Funnel Cake
Soda
The priceItems contains:
5
4
9
10
13
7
9
6
5
All Files are located on my desktop
Error: Could not find or load main class Disneyland
package com.Kassie$;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class Disneyland {
//Initialize the items 1D array
public static String[] getItems() {
try {
//Read from file
String[] aItems = new String(Files.readAllBytes
(Paths.get("src/com/Kassie$/desktop/menuItems.txt")))
.split("\n");
return aItems;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//Initialize the items 1D array
public static String[] getPrices() {
try {
//Read from file
String[] aPrices = new String(Files.readAllBytes
(Paths.get("src/com/Kassie$/desktop/menuPrices.txt")))
.split("\n");
return aPrices;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Find the character's location
public static String findLocation(String[][] storedValue, String name) {
for(int i = 0; i < storedValue.length; i++) {
if(storedValue[i][0].equals(name)) {
return (storedValue[i][1]);
}
}
return null;
}
public static void main(String[] args) {
char choice = ' ';
int totPrice = 0;
Scanner s = new Scanner(System.in);
String[][] characterLocation = {{"Mickey Mouse","Main Street USA"},
{"Minnie Mouse", "Toon Town"},
{"Goofy","Frontier Land"},
{"Pluto","Tomorrowland"},
{"Belle","Fantasyland"},
{"Jasmine", "Adventureland"}};
System.out.println("Do you like to know the "
+ "Disney Character's location(Y/N)?");
choice = s.next().charAt(0);
if(choice == 'Y' || choice == 'y') {
System.out.println("Enter the name of the character");
String aName = s.next();
String location = findLocation(characterLocation,aName);
if( location != null) {
System.out.println("The character is located in " + location);
}
else {
System.out.println("Sorry! The character you are looking for "
+ "is not in park today");
}
}
String[] items = getItems();
String[] prices = getPrices();
choice = ' ';
System.out.println("Would you like to view the menu?(Y/N)");
choice = s.next().charAt(0);
if(choice == 'N' || choice == 'n') {
System.exit(0);
}
while(choice == 'Y' || choice == 'y') {
for(int i = 0; i < items.length; i++) {
System.out.println("Enter " + (i+1) + " for " + items[i]);
}
int option = s.nextInt();
System.out.println("Item : " + items[option-1]);
System.out.println("Price : " + prices[option-1]);
totPrice = totPrice + Integer.parseInt(prices[option-1]);
System.out.println("Do you want to order more(Y/N)?");
choice = s.next().charAt(0);
}
System.out.println("Are you an Annual Pass Holder?(Y/N)?");
choice = s.next().charAt(0);
if(choice == 'Y' || choice == 'y') {
System.out.println("Your bill amount due : $" + ((double)totPrice -
((double)(totPrice*15))/100));
System.exit(1);
}
System.out.println("Your bill amount due : $" + totPrice);
}
}

You need to escape the dollar sign in your path.
To match a dollar sign, use "\$"
public static String[] getPrices() {
try {
//Read from file
String[] aPrices = new String(Files.readAllBytes
(Paths.get("src/com/Kassie\\$/desktop/menuPrices.txt")))
.split("\n");
return aPrices;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

Related

Where to close FileWriter when reusing it in different methods?

I have encountered a problem: I need to be able to filewrite after I have added to the array (dock) and removed from the array (undock) on the fly. But I do not know where to put the flush() and close(). I get errors when I but it after the write function wherever I put them because they have already closed the filewriter. Can you help?
try {
portLog.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
portLog.close();
} catch (IOException e) {
e.printStackTrace();
}
Here is my code:
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class Main {
static Scanner scan = new Scanner(System.in);
private static Ship[] dock1 = new Ship[10];
private static Ship[] waitingList = new Ship[10];
static FileWriter portLog;
static DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
//get current date time with Date()
static Date date = new Date();
static {
try {
portLog = new FileWriter("\\Users\\Smith\\Desktop\\PortLog.txt", true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
menu();
}
public static void menu() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Choose an option: 1-3");
System.out.println("1. Dock");
System.out.println("2. Undock");
System.out.println("3. Status");
int menu = scan.nextInt();
switch (menu) {
case 1:
System.out.println("1. Dock");
dock();
break;
case 2:
System.out.println("2. Undock");
undock();
break;
case 3:
System.out.println("3. Status");
printDock();
printWaitingList();
break;
case 4:
System.out.println("4. Exit");
System.exit(0);
default:
System.out.println("No such option");
break;
}
}
}
public static void dock() {
System.out.println("Enter ship's name: ");
String name = scan.nextLine();
System.out.println("Enter ship's size: ");
String size = scan.nextLine();
System.out.println("Enter the ships dock:");
//Check if the dock number is valid
int i = Integer.valueOf(scan.nextLine());
if (i >= 0 && i < 10 && dock1[i] == null) {
int c = 0;
int co = 0;
int sco = 0;
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] != null && dock1[j].getShipSize().equals("Cargo")) {
c++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Container")) {
co++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Super-Container")) {
sco++;
}
}
if (c < 10 && co < 5 && sco < 2) {
//Add ship to the dock
dock1[i] = new Ship(name, size);
System.out.println("Enough space you can dock");
System.out.println("Ship has been docked");
try {
portLog.write("\n" + " Docked: " + dock1[i].getShipName() + " Size: " + dock1[i].getShipSize() + " at " + dateFormat.format(date));
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("You cannot dock");
waitingList(name, size);
}
} else {
System.out.println("Couldn't dock");
waitingList(name, size);
}
}
public static void undock() {
System.out.println("Status of ships: ");
printDock();
System.out.println("Enter ship's name to undock: ");
String name = scan.nextLine();
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) {
try {
portLog.write("\n" + "Undocked: " + dock1[i].getShipName() + " Size: " + dock1[i].getShipSize() + " at " + dateFormat.format(date));
} catch (IOException e) {
e.printStackTrace();
}
dock1[i] = null;
System.out.println("Ship removed");
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null && waitingList[j] != null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j] = null;
return;
} else {
return;
}
}
} else {
}
}
System.out.println("Ship not found");
}
public static void waitingList(String name, String size) {
System.out.println("Dock 1 is full, ship will try to be added to Waiting List");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
//Add ship to the dock
waitingList[i] = new Ship(name, size);
System.out.println("Enough space added to waiting list");
return;
} else {
}
}
System.out.println("No space on waiting list, ship turned away.");
}
public static void printDock() {
System.out.println("Docks:");
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + dock1[i].getShipName() + " " + dock1[i].getShipSize());
}
}
}
private static void printWaitingList() {
System.out.println("Waiting List:");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + waitingList[i].getShipName() + " " + waitingList[i].getShipSize());
}
}
}
}
That is the thing when you are new to Java, and first start using all static variables within a single class. That is good for the first steps, and getting a hello world printed, or some simple calculations.
But then this approach quickly gets into your way. You see, in the "real" world of OOP, such code is much more of an anti-pattern.
Meaning: that is where you should starting thinking of creating classes of your own. A class has a distinct purpose, like modelling a Ship, or maybe a Dock. Then you add think about the properties that belong into such classes (and for sure: these fields are not static) then.
In that sense, the real answer here is that you "fully" step back and start thinking about better ways to organize the functionalities that you intend to create. As said, in your case, that boils down to define proper Ship/Dock classes. That will then allow you to abstract lower level details, such as "some stuff is stored in files". Because then you can have a DockPersistenceService class for example. Which you pass a list of Dock objects, to somehow persist them. Or that reads a list of Dock objects from a file.
As a general principle, it's a good idea for a resource like this to have a well-defined lifetime. That will typically mean that it's not static. #GhostCat is right that you should really consider a more robust approach, but as a starting point, I'd suggest this.
public static void menu() {
Scanner scan = new Scanner(System.in);
boolean keepProcessing = true; // use this to control the loop, don't call System.exit!
// use try-with-resources to control resource lifetime
try (FileWriter portLog = new FileWriter("\\Users\\Smith\\Desktop\\PortLog.txt", true)) {
while (keepProcessing) {
int choice = scan.nextInt();
switch (choice) {
case 1:
System.out.println("1. Dock");
dock(portLog);
break;
// Other cases skipped for brevity
case 4:
keepProcessing = false;
break;
// Other cases skipped for brevity
}
}
}
}
Then, have your other methods accept the portLog as a parameter.
public static void dock(FileWriter portLog) {
// ...
}
With this setup, the menu method will open the portLog file when it starts up, and close it when the method is finished. It also makes it clearer that the dock, undock, etc. methods require the use of the FileWriter object.

Creating a library with book objects and member objects

I've just started programming recently and have ran into a few minor errors. I'm creating a library object which holds references to book objects and member objects, however I'm having trouble accessing methods from the member class and using them in the library class without errors popping up in the LibraryTester class. This is what I've coded
Library class
package assignment;
import java.nio.channels.MembershipKey;
import java.util.ArrayList;
import java.util.Scanner;
import org.omg.Messaging.SyncScopeHelper;
public class Library {
// Declared an array list of type book
private ArrayList<Book> Books;
private MemberList members;;
public Library(ArrayList<Book> Books, Member member) {
this.Books = Books;
this.members=members;
};
public void displayBooks() {
System.out.println("\t\t\t-----The Current Books in the library are-----");
for (int i = 0; i < Books.size(); i++) {
System.out.println("\n" + "\t\t" + Books.get(i).getTitle() + "\t\t\t" + "\n\t\tAuthor: "
+ Books.get(i).getAuthor() + "\n\t\tThis Books ID is: " + Books.get(i).getBookID() + "\t\t\t\t\t\t"
+ "\n\t\tIs this book on loan? " + Books.get(i).getOnLoan() + "\t\t\t\t\t"
+ "\n\t\tThe number of times which this book has been loaned: " + Books.get(i).getNumOfLoans()
+ "\t\t");
}
}
// method to remove permanently a book object
public void removeBook() // the parameter that is passed through
// is the book id of the book that is to
// be removed
{
Scanner input = new Scanner(System.in);
int bookID = 0;
boolean successful = false;
try {
do {
System.out.println("Please enter the book ID of the book you wish to delete");
bookID = input.nextInt();
for (int i = 0; i < Books.size(); i++) {
if (bookID == Books.get(i).getBookID())
{
System.out.println("The Book " + Books.get(i).getTitle() + " was removed");
Books.remove(i);
successful = true;
break;
}
}
if (!successful) {
System.out.println("Book ID " + bookID + " does not exist");
}
} while (successful == false);
} catch (Exception e) {
System.out.println("ERROR: Invalid input" + "\nYou have been returned to the main menu");
}
}
public void editBook() {
boolean successful = false;
try {
do {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the book ID of the book who's details you wish to change");
int bookID = sc.nextInt();
sc.nextLine();
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getBookID() == bookID) {
System.out.println("Please enter the new name of the book:");
String newTitle = sc.nextLine();
Books.get(i).setTitle(newTitle);
System.out.println("Please enter the name of the author of the book:");
String newAuthor = sc.nextLine();
Books.get(i).setAuthor(newAuthor);
System.out.println("Change of book details successful" + "\nNew book title: " + newTitle
+ "\nNew author: " + newAuthor);
successful = true;
}
}
if (!successful) {
System.out.println("This book does not exist ");
}
} while (successful == false);
} catch (Exception e) {
System.out.println("ERROR: Invalid input" + "\nYou have been returned to the main menu");
}
}
public void addBook() {
boolean successful = false;
int bookID = 0;
String title = "";
String author = "";
Scanner input = new Scanner(System.in);
do {
System.out.println("Please assign a 3 digit number for the books ID ");
bookID = input.nextInt();
input.nextLine();
if(bookID > 99 && bookID <1000){
for (int i = 0; i < Books.size(); i++) {
if(Books.get(i).getBookID()!= bookID){
successful = true;
} else {
System.out.println("This book ID already exists ");
}
}
} else { System.out.println("You must enter a number between 99 and 1000 ");
}
} while (successful == false);
do {
System.out.println("Please enter the name of book");
title = input.nextLine();
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getTitle().equalsIgnoreCase(title)) {
System.out.println("ERROR: This book already exists");
successful = false;
} else {
successful = true;
}
}
} while (successful == false);
do {
System.out.println("Please enter the author of the book");
author = input.nextLine();
successful = true;
} while (successful == false);
Book Book = new Book(bookID, title, author, false, 0, 0);
Books.add(Book);
System.out.println(
"Book creation succcessful:" + "\nTitle: " + title + "\nAuthor: " + author + "\nBook ID:" + bookID);
}
public void loanBook() {
Scanner input = new Scanner(System.in);
boolean successful = false;
do {
System.out.println(
"\nPlease enter the book ID of the book that you wish to take out (Press 9 to exit to the main menu)");
int bookID = input.nextInt();
if (bookID == 9) {
successful = true;
break;
}
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getBookID() == bookID) {
do {
System.out.println("\nHow long would you like to loan the book for (20 Days maximum):");
int durationOnLoan = input.nextInt();
if (durationOnLoan <= 20 && 1 <= durationOnLoan) {
Books.get(i).setDurationOnLoan(durationOnLoan);
successful = true;
} else {
System.out.println("The number of days you have entered is invalid");
}
} while (successful == false);
System.out.println("\nThe book " + Books.get(i).getTitle() + " is now on loan");
Books.get(i).setOnLoan(true);
Books.get(i).setNumOfLoan(Books.get(i).getNumOfLoans() + 1);
successful = true;
}
}
if (successful == false) {
System.out.println("This book does not exist ");
}
} while (successful == false);
}
public void returnBook() {
boolean successful = false;
Scanner input = new Scanner(System.in);
try {
do {
System.out.println(
"Please enter the book ID of the book you wish to return (Press 9 to exit to the main menu");
int bookID = input.nextInt();
input.nextLine();
if (bookID == 9) {
successful = true;
}
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getBookID() == bookID) {
if (Books.get(i).getOnLoan() == true) {
System.out.println("How long did you loan the book for?");
int durationOnLoan = input.nextInt();
if (durationOnLoan > Books.get(i).getDurationOnLoan()) {
durationOnLoan -= Books.get(i).getDurationOnLoan();
if (durationOnLoan < 3) {
System.out.println("You are " + durationOnLoan
+ " day(s) late in returning the book" + "\nYou have been fined £3."
+ "\n The book " + Books.get(i).getTitle() + " is now returned");
successful = true;
} else {
System.out.println("You are " + durationOnLoan + " days late in returning the book"
+ "\nYou have been fined £6.");
System.out
.println("The book " + Books.get(i).getTitle() + " has now been returned");
successful = true;
}
} else {
Books.get(i).setOnLoan(false);
System.out.println("The book " + Books.get(i).getTitle() + " has now been returned");
successful = true;
}
} else if (Books.get(i).getOnLoan() == false) {
System.out.println("\nThis book was not on loan");
System.out.println("\nYou have been returned to the main menu");
successful = true;
}
} else if (successful == false) {
System.out.println("This book does not exist");
}
}
} while (successful == false);
} catch (Exception e) {
System.out.println("ERROR: Invalid input" + "\nYou have been returned to the main menu");
}
}
}
MemberList class
package assignment;
import java.util.Scanner;
import java.util.ArrayList;
public class MemberList {
private ArrayList<Member> Members;
public MemberList(ArrayList<Member> Members) {
this.Members = Members;
}
public void addNewMember() {
Scanner input = new Scanner(System.in);
boolean successful = false;
int memberID = 0;
String memberName = "";
int memberAge;
String address;
int contactNumber;
System.out.println("\t\tCreate new member");
do {
System.out.println("Please enter your full name:");
memberName = input.nextLine();
if (!input.hasNextInt()) {
successful =true;
} else {
input.next();
System.out.println("Your name cannot contain a number");
}
} while (successful == false);
do {
try{
input.nextLine();
System.out.println("please create your unique 2 digit member ID");
memberID = input.nextInt();
for (int i = 0; i < Members.size(); i++) {
if (Members.get(i).getMemberID() == memberID) {
System.out.println("This member ID is already in use");
successful =false;
}
if (memberID <= 9 || memberID > 99) {
System.out.println("PLease enter 2 digit ID (between 10 and 100) ");
}
if(Members.get(i).getMemberID() != memberID && memberID > 9 && memberID < 100) {
successful = true;
}
}
} catch(NumberFormatException e)
{
System.out.println("Invalid input");
}
} while (successful == false);
do{
System.out.println("Please enter your age: ");
memberAge = input.nextInt();
if(!input.hasNextInt())
{
System.out.println("Invalid input");
} else{successful =true;}
}while(successful == false);
do{
System.out.println("Please enter your adress");
address = input.nextLine();
successful =true;
}while(successful==false);
do {
System.out.println("please enter your contact number:");
contactNumber = input.nextInt();
if(!input.hasNextInt())
{
System.out.println("Invalid input");
} else{successful = true;}
}while(successful==false);
Member newMember = new Member(memberID,memberName,memberAge,0,0,address,contactNumber);
Members.add(newMember);
}
public void displayMembers()
{
System.out.println("\t\t\t-----The current members in the library are-----");
for (int i = 0; i < Members.size(); i++)
{
System.out.println("\n" + "\t\t" + Members.get(i).getMemberName() + "\t\t\t" + "\n\t\tMember ID: "
+ Members.get(i).getMemberID() + "\n\t\tAge: " + Members.get(i).getMemberAge() + "\t\t\t\t\t\t"
+ "\n\t\tAddress: " + Members.get(i).getAddress() + "\t\t\t\t\t"
+ "\n\t\tContact number: " + Members.get(i).getContactNumber()
+ "\t\t" + "\n\t\tNumber of books loaned: " + Members.get(i).getNumOfBooksLoaned()
+ "\t\t" + "\n\t\tNumber of Late Fees: " + Members.get(i).getPenalties());
}
}
}
LibraryTester Class
package assignment;
import java.util.Scanner;
import java.util.ArrayList;
public class LibraryTester {
public static void main(String[] args) {
String title = "";
String author = "";
int bookID = 0;
ArrayList<Member> List = new ArrayList<Member>();
MemberList memberlist = new MemberList(List){};
Member John = new Member(10,"John McLaughlin", 44, 5, 0,"75 B Loughbeg Road Toomebridge",123456789);
List.add(John);
Member Cathy = new Member(11,"Cathy McLaughlin", 43, 7, 0,"75 B Loughbeg Road Toomebridge",123456789);
List.add(Cathy);
ArrayList<Book> list = new ArrayList<Book>();
Library library = new Library(list, );
Book HarryPotter = new Book(100, "Harry Potter and The Philosopher's Stone", "J.K Rowling", false, 5, 0);
list.add(HarryPotter);
Book theOriginOfSpecies = new Book(101, "The Origin Of Species", "Charles Darwin", false, 3, 0);
list.add(theOriginOfSpecies);
Book LOTR = new Book(102, "The Lord of The Rings: The Fellowship of The Ring", "J.R.R Tolkien", false,7,0);
list.add(LOTR);
Scanner input = new Scanner(System.in);
boolean B = true;
while (B == true) {
System.out.println(" \nMenu ");
System.out.println("Press 1 to add a book");
System.out.println("Press 2 to edit a books details");
System.out.println("Press 3 to delete a book");
System.out.println("Press 4 to take out a book on loan");
System.out.println("Press 5 to return a book");
System.out.println("Press 6 to see all the books in the library");
System.out.println("Press 7 to become a member");
System.out.println("Press 8 to see the members of the library");
System.out.println("Press 9 to exit the program");
switch (input.nextInt()) {
case 1:
library.addBook();
B = true;
break;
case 2:
library.displayBooks();
library.editBook();
B = true;
break;
case 3:
library.displayBooks();
library.removeBook();
B = true;
break;
case 4:
library.displayBooks();
library.loanBook();
B = true;
break;
case 5:
library.displayBooks();
library.returnBook();
break;
case 6:
library.displayBooks();
B = true;
break;
case 7:
memberlist.addNewMember();
break;
case 8:
memberlist.displayMembers();
B = true;
break;
case 9:
System.out.println("Exiting .....");
System.exit(1);
break;
default:
System.out.println("You have not entered a valid option");
break;
}
}
}
}
The error occurs at the code
Library library = new Library(list , ) {
};
I'm not sure what to put after the comma, I've tried everything and nothing seems to work. Any thoughts?
EDIT
Edited Library class
package assignment;
import java.nio.channels.MembershipKey;
import java.util.ArrayList;
import java.util.Scanner;
import org.omg.Messaging.SyncScopeHelper;
public class Library {
// Declared an array list of type book
private ArrayList<Book> Books;
private ArrayList<Member> members;;
public Library(ArrayList<Book> Books, ArrayList<Member> member) {
this.Books = Books;
this.members=member;
};
Edited LibraryTester class
ArrayList<Member> List = new ArrayList<Member>();
MemberList memberList = new MemberList(List){};
ArrayList<Book> list = new ArrayList<Book>();
Library library = new Library(list, memberList ){};
The error says "The constructor Library(ArrayList, MemberList) is undefined" But i've changed the relevant things in the library class?
You need to pass an array of Book and, a Member :
public Library(ArrayList<Book> Books, Member member)
Since Library class is having the constructor
public Library(ArrayList<Book> Books, Member member){};
you can't just create a object as you are doing in LibraryTester class.
you need to pass the second parameter i.e, object of Member class.
Here you miss a member:
Library library = new Library(list, );
Try to add it like this creating an object of Member:
Member memberlist = new Member(10,"Joe Blogs", 44, 5, 0,"Bleaker Street",123456789);
Library library = new Library(list, memberlist);

Only run program if input is single letter

I've been working on a java project for me class, and I am almost done. the program is a hangman game, where the user inputs a letter, and the program continues depending whether the letter is in the word or not. The issue I am having is that I cannot figure out how to make it so when the user enters more than one letter, a number or a symbol, the program prints out a statement that says "Invalid input, try again" and has the user input something again, instead of showing it to be a missed try or the " letter" not being in the word. Here is my code:
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Hangman {
private Scanner in = new Scanner(System.in);
private boardPiece[] board = {new boardPiece(0),new boardPiece(0),new boardPiece(3),
new boardPiece(1),new boardPiece(2),new boardPiece(0)};
private String puzzle;
private String puzzleWord;
private int puzzleIndex;
private Random generator = new Random(System.currentTimeMillis());
private boolean win;
private boolean over;
private String correct = "";
private char guesses[] = new char[26];
private int guessed;
private int misses;
private String puzzles[] = new String[5];
public static void main(String [] args){
String letter;
String again = "y";
Hangman game = new Hangman();
try{
BufferedReader in =
new BufferedReader(new FileReader("puzzles.txt"));
int count = 0;
while (in.ready()) { //while there is another line in the input file
game.puzzles[count] = in.readLine(); //get line of data
count++; //Increment CWID counter
}
in.close();
}
catch(IOException e){
System.out.println("Error during reading/writing");
}
System.out.println("Welcome to HangMan!");
System.out.println("To play, guess a letter to try to guess the word.");
System.out.println("Every time you choose an incorrect letter another");
System.out.println("body part appears on the gallows. If you guess the");
System.out.println("word before you're hung, you win");
System.out.println("If you get hung, you lose");
System.out.println();
System.out.println("Time to guess...");
while(again.charAt(0) == 'y'){
game.displayGallows();
while(!game.over){
game.printBoard();
game.printLettersGuessed();
System.out.println("The word so far: " + game.puzzle);
System.out.println("Choose a letter: ");
letter = game.in.next();
game.guesses[game.guessed] = letter.charAt(0);
game.guessed++;
game.sort();
if(game.puzzleWord.indexOf(letter.charAt(0)) != -1){
game.correct = game.correct + letter.charAt(0);
game.puzzle = game.puzzleWord.replaceAll("[^"+game.correct+" ]","-");
if(game.puzzleWord.replaceAll("["+game.correct+" ]","").length() == 0){
game.win = true;
game.over = true;
}
}
else
game.PrintWrongGuesses();
}
game.printBoard();
System.out.println("Solution: " + game.puzzleWord);
if(game.win)
System.out.println("Congratulations! You've solved the puzzle!");
else
System.out.println("You failed, failer!");
System.out.println();
System.out.println("Congratulations, you win!");
System.out.println("Do you want to play again? (y/n)");
again = game.in.next();
}
System.out.println("Goodbye!");
}
public void displayGallows(){
win = false;
over = false;
board[0].piece = " ______ ";
board[1].piece = " | | ";
board[2].piece = " | ";
board[3].piece = " | ";
board[4].piece = " | ";
board[5].piece = " _______| ";
puzzleIndex = generator.nextInt(puzzles.length);
puzzleWord = puzzles[puzzleIndex];
puzzle = puzzleWord.replaceAll("[A-Za-z]","-");
correct = "";
for(int x=0;x<26;x++)
guesses[x] = '~';
guessed = 0;
misses = 0;
}
public void printBoard(){
for(int x =0;x<6;x++)
System.out.println(board[x].piece);
}
public void PrintWrongGuesses(){
misses++;
System.out.println();
if(misses == 1){
board[2].piece = " 0 | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 2){
board[2].piece = " \\0 | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 3){
board[2].piece = " \\0/ | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 4){
board[3].piece = " | | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 5){
board[4].piece = " / | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 6){
board[4].piece = " / \\ | ";
System.out.println("Number of misses: " + misses);
over = true;
}
}
public void printLettersGuessed(){
System.out.print("Letters guessed already: ");
for(int x=0;x<26;x++){
if(guesses[x] != '~')
System.out.print(guesses[x] + " ");
}
System.out.println();
}
public void sort(){
boolean doMore = true;
while (doMore) {
doMore = false; // assume this is last pass over array
for (int i=0; i<guesses.length-1; i++) {
if (guesses[i] > guesses[i+1]) {
char temp = guesses[i];
guesses[i] = guesses[i+1];
guesses[i+1] = temp;
doMore = true; // after an exchange, must look again
}
}
}
}
class boardPiece{
public String piece;
public int total;
public int used;
boardPiece(int x){
used = 0;
total = x;
}
}
}
System.out.println("Choose a letter: ");
letter = game.in.next();
if(letter.length() == 1)
{
game.guesses[game.guessed] = letter.charAt(0);
game.guessed++;
game.sort();
if(game.puzzleWord.indexOf(letter.charAt(0)) != -1){
game.correct = game.correct + letter.charAt(0);
game.puzzle = game.puzzleWord.replaceAll("[^"+game.correct+" ]","-");
if(game.puzzleWord.replaceAll("["+game.correct+" ]","").length() == 0){
game.win = true;
game.over = true;
}
}
else
game.PrintWrongGuesses();
}else
{
System.out.println("Invalid input, try again");
}
You can use a regular expression to check the input.
if (!letter.matches("[a-zA-Z]{1}")) {
System.out.println("Invalid Input") {
else {
<your other code>
}
Try this,
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Hangman {
private Scanner in = new Scanner(System.in);
private boardPiece[] board = {new boardPiece(0),new boardPiece(0),new boardPiece(3),
new boardPiece(1),new boardPiece(2),new boardPiece(0)};
private String puzzle;
private String puzzleWord;
private int puzzleIndex;
private Random generator = new Random(System.currentTimeMillis());
private boolean win;
private boolean over;
private String correct = "";
private char guesses[] = new char[26];
private int guessed;
private int misses;
private String puzzles[] = new String[5];
public static void main(String [] args){
String letter;
String again = "y";
Hangman game = new Hangman();
try{
BufferedReader in =
new BufferedReader(new FileReader("puzzles.txt"));
int count = 0;
while (in.ready()) { //while there is another line in the input file
String input = in.readLine();
if(input.length() == 1){
game.puzzles[count] = ; //get line of data
count++; //Increment CWID counter
}
else{
System.out.println("INVALID INPUT");
}
}
in.close();
}
catch(IOException e){
System.out.println("Error during reading/writing");
}
System.out.println("Welcome to HangMan!");
System.out.println("To play, guess a letter to try to guess the word.");
System.out.println("Every time you choose an incorrect letter another");
System.out.println("body part appears on the gallows. If you guess the");
System.out.println("word before you're hung, you win");
System.out.println("If you get hung, you lose");
System.out.println();
System.out.println("Time to guess...");
while(again.charAt(0) == 'y'){
game.displayGallows();
while(!game.over){
game.printBoard();
game.printLettersGuessed();
System.out.println("The word so far: " + game.puzzle);
System.out.println("Choose a letter: ");
letter = game.in.next();
game.guesses[game.guessed] = letter.charAt(0);
game.guessed++;
game.sort();
if(game.puzzleWord.indexOf(letter.charAt(0)) != -1){
game.correct = game.correct + letter.charAt(0);
game.puzzle = game.puzzleWord.replaceAll("[^"+game.correct+" ]","-");
if(game.puzzleWord.replaceAll("["+game.correct+" ]","").length() == 0){
game.win = true;
game.over = true;
}
}
else
game.PrintWrongGuesses();
}
game.printBoard();
System.out.println("Solution: " + game.puzzleWord);
if(game.win)
System.out.println("Congratulations! You've solved the puzzle!");
else
System.out.println("You failed, failer!");
System.out.println();
System.out.println("Congratulations, you win!");
System.out.println("Do you want to play again? (y/n)");
again = game.in.next();
}
System.out.println("Goodbye!");
}
public void displayGallows(){
win = false;
over = false;
board[0].piece = " ______ ";
board[1].piece = " | | ";
board[2].piece = " | ";
board[3].piece = " | ";
board[4].piece = " | ";
board[5].piece = " _______| ";
puzzleIndex = generator.nextInt(puzzles.length);
puzzleWord = puzzles[puzzleIndex];
puzzle = puzzleWord.replaceAll("[A-Za-z]","-");
correct = "";
for(int x=0;x<26;x++)
guesses[x] = '~';
guessed = 0;
misses = 0;
}
public void printBoard(){
for(int x =0;x<6;x++)
System.out.println(board[x].piece);
}
public void PrintWrongGuesses(){
misses++;
System.out.println();
if(misses == 1){
board[2].piece = " 0 | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 2){
board[2].piece = " \\0 | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 3){
board[2].piece = " \\0/ | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 4){
board[3].piece = " | | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 5){
board[4].piece = " / | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 6){
board[4].piece = " / \\ | ";
System.out.println("Number of misses: " + misses);
over = true;
}
}
public void printLettersGuessed(){
System.out.print("Letters guessed already: ");
for(int x=0;x<26;x++){
if(guesses[x] != '~')
System.out.print(guesses[x] + " ");
}
System.out.println();
}
public void sort(){
boolean doMore = true;
while (doMore) {
doMore = false; // assume this is last pass over array
for (int i=0; i<guesses.length-1; i++) {
if (guesses[i] > guesses[i+1]) {
char temp = guesses[i];
guesses[i] = guesses[i+1];
guesses[i+1] = temp;
doMore = true; // after an exchange, must look again
}
}
}
}
class boardPiece{
public String piece;
public int total;
public int used;
boardPiece(int x){
used = 0;
total = x;
}
}
}
You can use String.length() for checking the length of the input, e.g. in your case
if(letter.length() != 1) {
// do something to handle error
}
String.length() can be used to determine, if the input has one letter. To check if the read String is a letter you can use Character.isLetter(char):
try{
BufferedReader in =
new BufferedReader(new FileReader("puzzles.txt"));
int count = 0;
String line = null;
while (in.ready()) { //while there is another line in the input file
line = in.readLine();
if (line.length() == 1 && Character.isLetter(line.charAt(0)) {
game.puzzles[count] = line; //get line of data
count++; //Increment CWID counter
} else {
// handle the else-case
}
}
in.close();
}
catch(IOException e){
System.out.println("Error during reading/writing");
}

how to recognise capital letters and not just lower case

Hi i have done this program it works fine except if the user tries to write in capital letters i tried .toUpperCase but it still closes the program if you try to use capital letter to search can anyone help please thank you
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class database
{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//my arrays
static String country [] = new String[1000];
static String capital [] = new String[1000];
static double population [] = new double[1000];
static List<String> countriesList = Arrays.asList (country); //a new array for user to add data to
public static void main (String args [])throws IOException
{
// now i am adding data to the arrays
country[0] = "Barbados";
capital[0] = "Bridgetown";
population[0] = 65.3;
country[1] = "france";
capital[1] = "paris";
population[1] = 315.8;
country[2] = "nigeria";
capital[2] = "abuja";
population[2] = 170.1;
country[3] = "USA";
capital[3] = "washington";
population[3] = 2840;
country[4] = "japan";
capital[4] = "tokoyo";
population[4] = 126.7;
int option = 0;
System.out.println("WELCOME TO MY COUNTRY DATABASE\n");
while(option!= 5){ //Only five options
options();
option = Integer.parseInt(br.readLine());
if(option > 5 || option < 1)
{
System.out.println("Wrong input! Try Again");
System.out.println("CHOOSE FROM 1 - 5 \n ");
}
if(option == 1) {
addCountry();
}
else if(option == 2){
searchCountry(); //Search from an array
}
else if(option == 3){
ListCountry();
}
else if(option == 4){
getFare(); //show fare to travel
}
else if(option == 5) {
System.out.print("\n Thank you and Goodbye ");
}
}
}
public static void options()
{
System.out.println("Main menu");
System.out.println("=========");
System.out.println("1. Add a new country");
System.out.println("2. Search for a country");
System.out.println("3. Show list of countries available");
System.out.println("4. Get fare from London to countries listed");
System.out.println("5. Exit");
System.out.print("\n Choose an option from 1 - 5: ");
}
public static void addCountry()throws IOException
{
System.out.println("\n Adding a country");
System.out.println("===================");
System.out.print("Enter name of country: ");
String countryInput = br.readLine();
System.out.print("Enter Capital: ");
String capitalInput = br.readLine();
System.out.print("Enter population: ");
String populationInput = br.readLine();
int spareSlot = -1;
for (int i = 0; i < country.length; i++) // loop so data can be added to arraylist
{
if(country[i] == null)
{
spareSlot = i;
break;
}
}
country[spareSlot] = countryInput;
capital[spareSlot] = capitalInput;
population[spareSlot] = Double.parseDouble(populationInput);
System.out.println("\n You added the country " + countryInput + ", the capital is " + capitalInput + ", with a population of " + populationInput + "\n" );
//System.out.println("================================================================================================================");
}
public static void searchCountry() throws IOException
{
Scanner in = new Scanner (System.in);//Scanner to obtain input from command window
String output;
int size, i;
System.out.println("\n Searching countries");
System.out.println("========================= \n");
System.out.print("Search a Country: ");
output = br.readLine();
boolean found = false;
//A loop to search from the array
for(i = 0; i < country.length; i++)
if(output.equals(country[i]))
{
found = true;
break;
}
if (found)
System.out.println(output + " is found at index " + i +"\n");
else
System.out.println(output + ": This country is not found, choose option 1 to Add country \n");
if (output == country[0])
{
System.out.println("The capital of "+ output + "is " + capital[1] + " with a population of " + population[3]);
}
if(output == country[1]) {
System.out.println("The capital is" + capital[4]);
}
if(output == country[2]) {
System.out.println("The capital is" + capital[1]);
}
if(output == country[3]) {
System.out.println("The capital is " + capital[2]);
}
if(output == country[4]) {
System.out.println("The capital is " + capital[3]);
}
}
public static void ListCountry()throws IOException
{
for (String c : countriesList)
{
if(c!=null)
System.out.println("\n" + c +"\n"); // to list all countries so far in the array
}
}
public static void getFare()
{
Scanner input = new Scanner (System.in);
String destination;
int fare;
System.out.println("\n Get a fare:");
System.out.println("============== \n");
System.out.print("Select destination by entering number from 1 -5: \n");
System.out.println("1 Caribbean");
System.out.println("2 Europe");
System.out.println("3 Africa");
System.out.println("4 America");
System.out.println("5 Japan");
destination = input.nextLine(); //get destination from user
fare = Integer.parseInt(destination);
switch(fare)
{
case 1: System.out.println("To travel to the Carribbean the fare is from £600 \n");
break;
case 2: System.out.println("To travel to Europe the fare is from £199 \n");
break;
case 3: System.out.println("To travel to Africa the fareis from £500 \n");
break;
case 4: System.out.println("To travel to America the fare is from £290 \n");
break;
case 5: System.out.println("To travel to Japan the fare is from £550 \n");
break;
default: System.out.println("INVALID ACTION START AGAIN \n");
System.out.println("======================================");
}
}
}
You have one comparison reading
if(output.equals(country[i]))
If you want this to be case-insensitive, you want to change that to
if(output.equalsIgnoreCase(country[i]))
Later in your code, you have lines similar to
if (output == country[0])
which compares object identity rather than string equality. You want to change all these to at least properly compare strings, and possibly to be case-insensitive as above.

How to re load an different file in java after having printed a previous one

Ok So this code I have below is compiling but I have a logic error. Ok so After i enter the file with the data i would like it to read and I choose to print that data on screen I have the choice of loading a different file. However, when I do enter the name of the new file that I would like to load it does not load the file and the error message that I designated for that particular situation it outputted. I think i have to flush the stream buffer after each write or something like that. So um if anyone can point of why this is happening then I would appreciate it.
import java.util.Scanner;
import java.io.*;
public class Driver {
private static int numberOfCustomer = 0;
private static Customer[] customerList = new Customer[10];
private static void readInCustomer(String file){
FileReader freader;
BufferedReader inputFile;
try{
freader = new FileReader(file);
inputFile = new BufferedReader(freader);
String strLine;
while ((strLine = inputFile.readLine()) != null) {
customerList[numberOfCustomer] = new Customer();
customerList[numberOfCustomer].ID = strLine;
customerList[numberOfCustomer].name = inputFile.readLine();
customerList[numberOfCustomer].address = inputFile.readLine();
customerList[numberOfCustomer].phone = inputFile.readLine();
numberOfCustomer++;
}
inputFile.close();
}catch(Exception e){
System.out.println("Could not find file "+file+" System will now exit");
System.exit(1);
}
return;
}
private static void printCustomer(Customer customer){
System.out.println("The Customer Data corresponding to Customer Number " + customer.ID + " is:");
System.out.println("Name:\t\t\t"+customer.name);
System.out.println("Address:\t\t"+customer.address);
System.out.println("Telephone:\t\t"+customer.phone);
System.out.println();
return;
}
private static void printAll(){
boolean hasID = false;
Scanner keyboard = new Scanner(System.in);
System.out.println("All customers from data file "+numberOfCustomer);
System.out.println(" Here they are!!! ");
for(int i=0; i<numberOfCustomer; i++){
if(customerList[i] != null){
System.out.println("The Customer Data corresponding to Customer Number " + customerList[i].ID + " is:");
System.out.println("Name:\t\t\t"+customerList[i].name);
System.out.println("Address:\t\t"+customerList[i].address);
System.out.println("Telephone:\t\t"+customerList[i].phone);
}
}
if(!hasID){
System.out.println("");
}
System.out.println("Would you like to go to the menu? (Y or N):");
String input = keyboard.nextLine();
char repeat = input.charAt(0);
if(repeat == 'Y' || repeat == 'y'){Menu();}
return;
}
private static void Menu(){
boolean hasID = false;
Scanner keyboard = new Scanner(System.in);
System.out.println("YOU MAY CHOOSE FROM THE FOLLOWING OPTIONS:");
System.out.println("A. SEARCH for a customer by ID number");
System.out.println("B. DISPLAY the entire Customer List");
System.out.println("C. RE-LOAD DATA from a different data file");
System.out.println("D. QUIT:");
String choice = keyboard.nextLine();
char repeat = choice.charAt(0);
if(repeat == 'A' || repeat == 'a'){Scostomer();}
if(repeat == 'B' || repeat == 'b'){printAll();}
if(repeat == 'C' || repeat == 'c'){mainn();}
return;
}
public static void Scostomer(){
boolean hasID = false;
Scanner keyboard = new Scanner(System.in);
System.out.println("Type in the Id you are search for");
String customerID = keyboard.nextLine();
for(int i=0; i<numberOfCustomer; i++){
if((customerList[i]!=null) && (customerID.equals(customerList[i].ID))){
hasID = true;
printCustomer(customerList[i]);
i=customerList.length;
}
}
if(!hasID){
System.out.println("Sorry, customer not found.");
}
System.out.println("Would you like to search for another custnomer? (Y or N):");
String input = keyboard.nextLine();
char repeat = input.charAt(0);
if(repeat == 'Y' || repeat == 'y'){Scostomer();}
if(repeat == 'N' || repeat == 'n'){Menu();}
return;
}
public static void main(String arg[]){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the fileName that contains the data of your customers: ");
readInCustomer(keyboard.nextLine());
Menu();
return;
}
public static void mainn(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the fileName that contains the data of your customers: ");
readInCustomer(keyboard.nextLine());
Menu();
return;
}
}
Works for me (load a file, type c to load new file, type b to display all). I'd suggest there's something simple wrong (wrong filename or something silly), so you you'll want to log the exception details, instead of ignoring them in your catch block.
} catch(Exception e) {
e.printStackTrace(); // should tell you what's wrong!
System.out.println("Could not find file "+file+" System will now exit");
System.exit(1);
}
Flushing is not relevant here as you are reading, not writing. You could probably tidy up the whole menu/input loop too, it's a bit wacky (but it works!). For example, your main and mainn methods are identical - have you considered abstracting that out into a separate method?
Instead of limiting yourself to 10 customers, you can use a List and not have to worry about how many customers you're going to read in (I've only changed your code to use a List instead of an array):
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Driver {
private static int numberOfCustomer = 0;
// List instead of array!
private static List<Customer> customerList = new ArrayList<Customer>();
private static void readInCustomer(String file) {
FileReader freader;
BufferedReader inputFile;
try {
freader = new FileReader(file);
inputFile = new BufferedReader(freader);
String strLine;
while ((strLine = inputFile.readLine()) != null) {
Customer customer = new Customer();
customer.ID = strLine;
customer.name = inputFile.readLine();
customer.address = inputFile.readLine();
customer.phone = inputFile.readLine();
customerList.add(customer); // add to the List!
}
inputFile.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Could not find file " + file
+ " System will now exit");
System.exit(1);
}
return;
}
private static void printCustomer(Customer customer) {
System.out
.println("The Customer Data corresponding to Customer Number "
+ customer.ID + " is:");
System.out.println("Name:\t\t\t" + customer.name);
System.out.println("Address:\t\t" + customer.address);
System.out.println("Telephone:\t\t" + customer.phone);
System.out.println();
return;
}
private static void printAll() {
boolean hasID = false;
Scanner keyboard = new Scanner(System.in);
System.out.println("All customers from data file " + numberOfCustomer);
System.out.println(" Here they are!!! ");
for (Customer customer : customerList) {
System.out
.println("The Customer Data corresponding to Customer Number "
+ customer.ID + " is:");
System.out.println("Name:\t\t\t" + customer.name);
System.out.println("Address:\t\t" + customer.address);
System.out.println("Telephone:\t\t" + customer.phone);
}
if (!hasID) {
System.out.println("");
}
System.out.println("Would you like to go to the menu? (Y or N):");
String input = keyboard.nextLine();
char repeat = input.charAt(0);
if (repeat == 'Y' || repeat == 'y') {
Menu();
}
return;
}
private static void Menu() {
boolean hasID = false;
Scanner keyboard = new Scanner(System.in);
System.out.println("YOU MAY CHOOSE FROM THE FOLLOWING OPTIONS:");
System.out.println("A. SEARCH for a customer by ID number");
System.out.println("B. DISPLAY the entire Customer List");
System.out.println("C. RE-LOAD DATA from a different data file");
System.out.println("D. QUIT:");
String choice = keyboard.nextLine();
char repeat = choice.charAt(0);
if (repeat == 'A' || repeat == 'a') {
Scostomer();
}
if (repeat == 'B' || repeat == 'b') {
printAll();
}
if (repeat == 'C' || repeat == 'c') {
mainn();
}
return;
}
public static void Scostomer() {
boolean hasID = false;
Scanner keyboard = new Scanner(System.in);
System.out.println("Type in the Id you are search for");
String customerID = keyboard.nextLine();
// iterate over the List!
for (Customer customer : customerList) {
if (customerID.equals(customer.ID)) {
hasID = true;
printCustomer(customer);
break;
}
}
if (!hasID) {
System.out.println("Sorry, customer not found.");
}
System.out
.println("Would you like to search for another custnomer? (Y or N):");
String input = keyboard.nextLine();
char repeat = input.charAt(0);
if (repeat == 'Y' || repeat == 'y') {
Scostomer();
}
if (repeat == 'N' || repeat == 'n') {
Menu();
}
return;
}
public static void main(String arg[]) {
Scanner keyboard = new Scanner(System.in);
System.out
.println("Enter the fileName that contains the data of your customers: ");
readInCustomer(keyboard.nextLine());
Menu();
return;
}
public static void mainn() {
Scanner keyboard = new Scanner(System.in);
System.out
.println("Enter the fileName that contains the data of your customers: ");
readInCustomer(keyboard.nextLine());
Menu();
return;
}
}

Categories

Resources