Im getting errors with some methods - java

I'm writing this java class which is the TUI for the Class loyaltyCard, However, I'm facing some errors with the methods below. Would appreciate any help, Thanks.
public void addLoyalty Card
public void ShowAllLoyaltyCards (it should print details of all loyaltycards with a space between each)
public void showLoyaltyCard (print out loyaltycard with the choose card number, if unsuccessful "message"
Here is my code:
import java.util.ArrayList;
import java.util.Scanner;
public class LoyaltyCardTUI
{
private LoyaltyCardList loyaltyCardList;
private Scanner myScanner;
public LoyaltyCardTUI()
{
myScanner = new Scanner(System.in);
LoyaltyCardList loyaltyCardList = new LoyaltyCardList();
}
public void menu()
{
int command = -1;
while (command != 0)
{
displayMenu();
command = getCommand();
execute (command);
}
}
**public void addLoyaltyCard(**)
{
loyaltyCardList.addLoyaltyCard(new LoyaltyCard());
}
private void displayMenu()
{
System.out.println( "Options are" );
System.out.println( "Enter 1" );
System.out.println( "Enter 2" );
System.out.println( "Enter 3" );
System.out.println( "Enter 4" );
}
private void execute( int command)
{
if ( command == 1)
addLoyaltyCard();
else
if ( command == 2 )
getNumberOfLoyaltyCards();
else
if ( command == 3)
quitCommand();
else
if ( command == 4)
quitCommand();
else
if ( command == 5)
quitCommand();
else
System.out.println("Unknown Command");
}
private int getCommand()
{
System.out.print ("Enter command: ");
int command = myScanner.nextInt();
myScanner.nextLine();
return command;
}
public void getNumberOfLoyaltyCards()
{
int command = myScanner.nextInt();
System.out.println("We have" + loyaltyCardList.getNumberOfLoyaltyCards() + "loyaltyCards");
}
public void quitCommand()
{
int command = myScanner.nextInt();
System.out.println("Application Closing");
System.exit(0);
}
private void removeLoyaltyCard()
{
System.out.print("Enter card number : ");
String cardNumber = myScanner.nextLine();
if (loyaltyCardList.removeLoyaltyCard(cardNumber))
System.out.println("LoyaltyCard with card number " + cardNumber + " removed from class list");
else
System.out.println("LoyaltyCard with card number " + cardNumber + " not found");
}
**public void showAllLoyaltyCards()**
{
for(LoyaltyCard loyaltyCard : loyaltyCards)
{
loyaltyCard.printCustomerDetails();
System.out.println();
}
}
**public void showLoyaltyCard()**
{
for (LoyaltyCard loyaltyCard : loyaltyCards)
{
if (cardNumber.equals(loyaltyCard.getCardNumber()))
{
return System.out.println(loyaltyCard);
}
else
{
return System.out.println("Could not find loyalty card for card number"+cardNumber);
}
}
}
private void unknownCommand(int command)
{
System.out.println("Invalid Command : "+ command);
}
}

Related

Having issues with code, How can I reinitialize my player

So when I run the code(there are 5 more files that go with this) It is supposed to run a card game up to 10 rounds and determine a winner. However I only get up to the first round and then it terminates. I got some help with what might be wrong. I need to reinitialize my player so it stops giving me a
NullPointerException
import java.util.ArrayList;
import java.util.Random;
public class Game
{
private static deckOfCards deck = new deckOfCards();
private static ArrayList<Card> table = new ArrayList<>();
private static Card topCard;
private static Player p1 = new Player("Player One");
private static Player p2 = new Player("Player Two");
private static Player currentPlayer = p1;
private static int rounds = 1;
private static boolean gameOver = false;
public static void startGame()
{
System.out.println("Starting game now:");
dealCards();
chooseFirstPlayer();
playRounds();
declareWinner();
}
public static void dealCards()
{
for (int i = 0; i < 26; i++)
{
p1.takeCard(deck.deal());
p2.takeCard(deck.deal());
}
}
public static void chooseFirstPlayer()
{
Random r = new Random();
int n = r.nextInt(2);
if (n == 1)
{
Player temp = p1;
p1 = p2;
p2 = temp;
}
}
public static void playRounds()
{
while (rounds <= 10 && (gameOver == false))
{
System.out.println("Round " + rounds);
System.out.println();
showHand();
playRound();
rounds++;
}
}
public static void playRound()
{
boolean suitMatch = false;
Card cardToPlay;
if ((p1.handSize() == 52) || (p2.handSize() == 52))
{
gameOver = true;
}
while (suitMatch == false)
{
cardToPlay = currentPlayer.playCard();
table.add(cardToPlay);
suitMatch = checkSuitMatch();
if (suitMatch == false)
switchCurrentPlayer();
}
collectCards();
System.out.println();
try
{
Thread.sleep(500);
}
catch (InterruptedException e){
}
}
public static void switchCurrentPlayer()
{
if (currentPlayer == p1)
currentPlayer = p2;
else if (currentPlayer == p2)
currentPlayer = p1;
}
public static boolean checkSuitMatch()
{
int tableSize = table.size();
int lastSuit;
int topSuit;
if (tableSize < 2)
{
return false;
}
else
{
lastSuit = table.get(tableSize - 1).getSuit();
topSuit = table.get(tableSize - 2).getSuit();
}
if (lastSuit == topSuit)
{
System.out.println();
System.out.println(currentPlayer.getName() + " wins the round!");
System.out.println();
return true;
}
return false;
}
public static void collectCards()
{
System.out.print(currentPlayer.getName() + " takes the table (" + table.size() + "): ");
displayTable();
for (int i = 0; i < table.size(); i++)
{
Card cardToTake = table.get(i);
currentPlayer.takeCard(cardToTake);
}
table.clear();
}
public static void displayTable()
{
for (int i = 0; i < table.size(); i++)
{
if (table.get(i) != null)
{
System.out.print(table.get(i).getName() + " ");
}
}
System.out.println();
System.out.println();
}
public static void showHand()
{
p1.showHand();
p2.showHand();
}
public static void declareWinner()
{
if (p1.handSize() > p2.handSize())
{
System.out.println(p1.getName().toUpperCase() + " wins " + "by having " + p1.handSize() + " cards!");
}
else if (p2.handSize() > p1.handSize())
{
System.out.println(p2.getName().toUpperCase() + " wins " + "by having " + p2.handSize() + " cards!");
}
else
{
System.out.println("It's a draw.");
}
System.out.println();
}
public static void main(String[] args)
{
startGame();
}
}
Here is my player class just incase:
public class Player
{
private Hand hand; //for the player's hand
private String name;
//Constructors
public Player(String name)
{
hand = new Hand();
this.name = name;
}
//prints and determines the card the player will play
public Card playCard()
{
Card playerCard = hand.playCard();
System.out.println(String.format("%5s", name) + playerCard.getName());
return playerCard;
}
//takes the card if player can match
public void takeCard(Card card)
{
hand.addCard(card);
}
public String getName()
{
return name;
}
//how the hand of player
public void showHand()
{
System.out.println(name + " hand " + hand.getSize() + ":");
hand.show();
System.out.println();
}
//get the size of players' hand
public int handSize()
{
return hand.getSize();
}
}

clearing memory to create a new item

how do I clear my memory after the fifth action?
to be able to create a new basket again and fill it with new balls.
Because now, when you re-create the basket and fill it with balls,
the error appears on the second action (filling the basket)
how to clear the cache with the first bucket so that you can enter the second one?
//main
public class Dialogue {
private static Scanner scanner = new Scanner(System.in);
private static boolean buildBasket = false;
private static boolean completedBasket = false;
private Basket basket;
private static int volumeOfBasket = 0;
public static void main(String[] args) {
boolean buildBasket = false;
boolean completedBasket = false;
Basket basket =null;
int volumeOfBasket = 0;
try {
while (true) {
System.out.println("1 - build а basket");
System.out.println("2 - add balls to basket");
System.out.println("3 - output information about basket");
System.out.println("4 - weight of balls in the basket");
System.out.println("5 - quantity red balls");
int i = ScunnerInformation.checkInformatio();
if (i == 1) {
System.out.println("what max count of ball will into basket?");
volumeOfBasket = ScunnerInformation.getVolumeBasket();
Basket newBasket = new Basket("<Basketballs>", volumeOfBasket);
System.out.println("Basket was build with name: " + newBasket.getNameBasket() +
" and with the size " + newBasket.getVolume());
buildBasket = true;
basket = newBasket;
} else if (i == 2) {
if (buildBasket) {
basket = WorkWithBasket.fillBasket(basket);
completedBasket = true;
System.out.println("you have successfully added balls to the basket");
}else {
System.out.println("error");
}
} else if (i == 3) {
if (completedBasket) {
WorkWithBasket.InfoOut(basket);
} else {
System.out.println("error");
}
}else if (i == 4) {
if (completedBasket) {
System.out.println("weight basket: " + WorkWithBasket.countWeight(basket));
} else {
System.out.println("error");
}
}else if (i==5) {
if (completedBasket) {
System.out.println(WorkWithBasket.countRedBalls(basket) + " it it number of red balls");
} else {
System.out.println("error");
}
} else if (i == 6) {
break;
}
}
}finally {
if (scanner!=null){
scanner.close();
}
}
}
//fillBasket
public class WorkWithBasket {
public static Basket fillBasket(Basket basket){
for(int i =0; i < basket.getVolume(); i++){
Ball temp = new Ball(Color.getRandomColor(), WorkWithBall.CostBall(),WorkWithBall.WeightBall());
basket.addBall(temp);
}
return basket;
}
//addBall
public void addBall(Ball ball){
if (ball !=null){
basket[ball.getId() -1] = ball;
}
}
//basket initialization
public class Basket {
private Ball[] basket;
public Basket(){
this.basket = new Ball[this.volume];
}
public Basket (String nameBasket, int volume){
this.basket = new Ball[volume];
}
public Ball[] getBasket(){
return basket.clone();
}
public void addBall(Ball ball){
if (ball !=null){
basket[ball.getId() -1] = ball;
}
}

How to scan and respond to a user's input?

Creating a simple ATM menu with few options on it.
Want to know how to let user inputs something to select the options, and then the codes can respond to the input.
For example, "readLine(string)"
Following is my code:
public class Menu
{
private String menuText;
private int optionCount;
public Menu()
{
menuText = "";
optionCount = 0;
}
public void addOption(String option)
{
optionCount = optionCount + 1;
menuText = menuText + optionCount + ") " + option + "\n";
}
public void display()
{
System.out.println(menuText);
}
}
public class MenuDemo{
public MenuDemo()
{
}
public static void main(String[] args)
{
Menu mainMenu = new Menu();
mainMenu.addOption("Log In Account");
mainMenu.addOption("Deposit Check");
mainMenu.addOption("Help");
mainMenu.addOption("Quit");
mainMenu.display();
}
}
You can read the user Input with Scanner class. And then with switch statement do your required actions:
import java.util.Scanner;
class Menu
{
private String menuText;
private int optionCount;
public Menu()
{
menuText = "";
optionCount = 0;
}
public void addOption(String option)
{
optionCount = optionCount + 1;
menuText = menuText + optionCount + ") " + option + "\n";
}
public void display()
{
System.out.println(menuText);
}
}
public class MenuDemo{
public MenuDemo()
{
}
public static void main(String[] args)
{
Menu mainMenu = new Menu();
mainMenu.addOption("1. Log In Account");
mainMenu.addOption("2. Deposit Check");
mainMenu.addOption("3. Help");
mainMenu.addOption("4. Quit");
mainMenu.display();
Scanner input = new Scanner(System.in);
System.out.println("Enter Choice: ");
String i = input.nextLine();
switch(i){
case "1":
//do something
System.out.println("User Entered 1 : " + i);
break;
case "2":
//do something
System.out.println("User Entered 2 : " + i);
break;
case "3":
//do something
System.out.println("User Entered 3 : " + i);
break;
case "4":
//do something
System.out.println("User Entered 4 : " + i);
break;
default:
System.out.println("Quit" + i);
}
}
}

Java Suit Application using enums, methods and user input updated

I have got through all of this paper except the last part(Part 5) I have attached the picture of the paper for the part I am struggling with above.
When running my application tester, when I press 3, nothing happens. Does anyone know why? the code of my classes is below. NOTE: the updateBrand() method which is called in the tester in the makeChangeToSuit method is in the morningSuit and suit classes.
I would appreciate any help on this matter.
package SuitProg;
import java.util.Scanner;
public abstract class Suit {
//instance variables
private String Colour;
private double dailyCost;
private int trouserLength;
private int jacketChestSize;
private boolean available;
protected double totalPrice;
//constructor
public Suit(String colour, double dailyCost, int trouserLength, int jacketChestSize, boolean available) {
super();
Colour = colour;
this.dailyCost = dailyCost;
this.trouserLength = trouserLength;
this.jacketChestSize = jacketChestSize;
this.available = available;
this.totalPrice = totalPrice;
}
//accessors & mutators
public String getColour() {
return Colour;
}
public double getDailyCost() {
return dailyCost;
}
public int getTrouserLength() {
return trouserLength;
}
public int getJacketChestSize() {
return jacketChestSize;
}
public boolean getAvailability() {
return available;
}
public double getTotalPrice() {
return totalPrice;
}
public void setDailyCost(double dailyCost) {
this.dailyCost = dailyCost;
}
public void setTrouserLength(int trouserLength) {
this.trouserLength = trouserLength;
}
public void setJacketChestSize(int jacketChestSize) {
this.jacketChestSize = jacketChestSize;
}
public void setAvailability(boolean available) {
this.available = available;
}
//methods
public String toString() {
return " Suit [ Colour: " + getColour() + ", Daily Cost: " + String.format("%.2f", getDailyCost())
+ "\nTrouser Length: " + getTrouserLength() + ", Jacket Chest Size: " + getJacketChestSize()
+ " Is it available? " + getAvailability();
}
public void calcTotalPrice (int numDaysHired) {
totalPrice = totalPrice + (getDailyCost() * numDaysHired);
}
public String printDailyCost() {
getDailyCost();
return "£" + String.format("%.2f", getDailyCost());
}
public void makeChange(Scanner input) {
boolean valid = false;
do {
System.out.println("Are you sure you want to change the branding of a suit?");
String response = input.nextLine().toLowerCase();
if (response.equalsIgnoreCase("Y")) {
valid = true;
updateBrand(null);
}
else
if (response.equalsIgnoreCase("N")) {
valid = true;
System.exit(0);
break;
}
} while (!valid);
}
public void updateBrand(Scanner input) {
boolean valid = false;
int selection;
System.out.println("The list of available brands are below:");
System.out.println("1 - " + Brand.Highstreet);
System.out.println("2 - " + Brand.TedBaker);
System.out.println("3 - " + Brand.FrenchConnection);
do {
System.out.println("Please enter the number of the Brand you wish to change.");
if (input.hasNextInt()) {
selection = input.nextInt();
if (selection < 1 || selection > 3) {
valid = false;
System.out.println("Please enter a number betwen 1 and 3");
} else
valid = true;
System.out.println("You have selected number: " + selection);
if (selection == 1) {
System.out.println("Please enter the changes you want to make");
System.out.println("New brand name : ");
//
}
}
} while (!valid);
}
}
package SuitProg;
import java.util.Scanner;
public class MorningSuit extends Suit implements Brandable {
//instance variables
private boolean boutonniere;
private boolean topHat;
public Brand brand;
//constructor
public MorningSuit(String colour, double dailyCost, int trouserLength, int jacketChestSize, boolean available, boolean boutonniere, boolean topHat) {
super(colour, dailyCost, trouserLength, jacketChestSize, available);
this.boutonniere = boutonniere;
this.topHat = topHat;
}
//accessors & mutators
public boolean getBout() {
return boutonniere;
}
public boolean getTopHat() {
return topHat;
}
public void setBout(boolean boutonniere) {
this.boutonniere = boutonniere;
}
public void setTopHat(boolean topHat) {
this.topHat = topHat;
}
public void setBrand(Brand brand) {
this.brand = brand;
}
//methods
public String toString() {
return "Morning Suit [ Boutonniere " + getBout() + " TopHat " + getTopHat() + " Colour: " + getColour() + ", Daily Cost: £" + String.format("%.2f", getDailyCost())
+ "\nTrouser Length: " + getTrouserLength() + ", Jacket Chest Size: " + getJacketChestSize()
+ " Is it available? " + getAvailability() + "]";
}
public void calcTotalPrice(int numDaysHired) {
if (getBout()) {
totalPrice = totalPrice + 3;
}
if (getTopHat()) {
totalPrice = totalPrice + 10;
}
totalPrice = totalPrice + (numDaysHired * getDailyCost());
System.out.println("The morning suit was hired for " + numDaysHired + " days.");
System.out.println("The total cost for the hire was: £" + String.format("%.2f", totalPrice));
}
public String getBrand() {
return "The brand of this Morning Suit is " + brand.toString().toLowerCase();
}
public void makeChange(Scanner input) {
boolean valid = false;
do {
System.out.println("Are you sure you want to change the branding of a suit?");
String response = input.nextLine().toLowerCase();
if (response.equalsIgnoreCase("Y")) {
valid = true;
updateBrand(input);
}
else
if (response.equalsIgnoreCase("N")) {
valid = true;
System.exit(0);
break;
}
} while (!valid);
}
public void updateBrand(Scanner input) {
boolean valid = false;
int selection;
System.out.println("The list of available brands are below:");
System.out.println("1 - " + Brand.Highstreet);
System.out.println("2 - " + Brand.TedBaker);
System.out.println("3 - " + Brand.FrenchConnection);
do {
System.out.println("Please enter the number of the Brand you wish to change.");
if (input.hasNextInt()) {
selection = input.nextInt();
if (selection < 1 || selection > 3) {
valid = false;
System.out.println("Please enter a number betwen 1 and 3");
} else
valid = true;
System.out.println("You have selected number: " + selection);
if (selection == 1) {
System.out.println("Please enter the changes you want to make");
System.out.println("New brand name : ");
//
}
}
} while (!valid);
}
}
package SuitProg;
public enum Brand {
Highstreet,TedBaker,FrenchConnection
}
package SuitProg;
public interface Brandable {
public String getBrand();
}
package SuitProg;
import java.util.Scanner;
public class EveningSuit extends Suit implements Brandable {
//variables
private boolean cufflinks;
private boolean waistcoat;
public Brand brand;
public EveningSuit(String colour, double dailyCost, int trouserLength, int jacketChestSize, boolean available, boolean cufflinks, boolean waistcoat) {
super(colour, dailyCost, trouserLength, jacketChestSize, available);
this.cufflinks = cufflinks;
this.waistcoat = waistcoat;
this.brand = Brand.Highstreet;
}
//accessors & mutators
public boolean getCuffs() {
return cufflinks;
}
public boolean getWaistcoat() {
return waistcoat;
}
public void setCuffs(boolean cufflinks) {
this.cufflinks = cufflinks;
}
public void setWaistcoat(boolean waistcoat) {
this.waistcoat = waistcoat;
}
//methods
public String toString() {
return "Evening Suit [ Cufflinks " + getCuffs() + " Waistcoat " + getWaistcoat() + " Colour: " + getColour() + ", Daily Cost: £" + String.format("%.2f", getDailyCost())
+ "\nTrouser Length: " + getTrouserLength() + ", Jacket Chest Size: " + getJacketChestSize()
+ " Is it available? " + getAvailability() + "]";
}
public void calcTotalPrice (int numDaysHired) {
if (getCuffs()) {
totalPrice = totalPrice + 5;
}
if (getWaistcoat()) {
totalPrice = totalPrice + 10;
}
totalPrice = totalPrice + (getDailyCost() * numDaysHired);
System.out.println("The evening suit was hired for " + numDaysHired + " days.");
System.out.println("The total cost for the hire was: £" + String.format("%.2f", totalPrice));
}
public String getBrand() {
return "The brand of this Evening Suit is " + brand.toString().toLowerCase();
}
public void makeChange(Scanner input) {
boolean valid = false;
do {
System.out.println("Are you sure you want to change the branding of a suit?");
String response = input.nextLine().toLowerCase();
if (response.equalsIgnoreCase("Y")) {
valid = true;
System.out.println("You can not change the brand name of an evening suit.");
}
else
if (response.equalsIgnoreCase("N")) {
valid = true;
System.exit(0);
break;
}
} while (!valid);
}
}
package SuitProg;
import java.util.ArrayList;
import java.util.Scanner;
public class Tester05 {
public static void main(String[] args) {
//create arrayList of suits
ArrayList<Suit> suits = new ArrayList<Suit>();
//create morningSuit object
MorningSuit MorningSuit1 = new MorningSuit("Black", 80.00, 32, 36, true, true, false);
MorningSuit1.setBrand(Brand.FrenchConnection);
//create evening suit
EveningSuit EveningSuit1 = new EveningSuit("White", 70.25, 34, 36, true, true, true);
//add suits to arrayList
suits.add(MorningSuit1);
suits.add(EveningSuit1);
//print all details of arrayList
for (Suit eachSuit : suits) {
System.out.println(eachSuit .toString()+"\n");
}
System.out.println(MorningSuit1.getBrand());
System.out.println(EveningSuit1.getBrand());
printMenu(suits);
}
public static void printMenu(ArrayList<Suit> suits) {
Scanner input = new Scanner(System.in);
System.out.println("----------------Suit Hire-----------------");
System.out.println("What would you like to do?");
System.out.println("\n1)Display all suits\n2)Display available suits\n3)Change Suit brand\n4)Finished");
System.out.println("Please select an option: ");
int selection = input.nextInt();
if (selection == 1) {
displayAllSuits(suits);
} else
if (selection == 2) {
displayAllSuits(suits);
}
else
if (selection ==3) {
makeChangeToSuits(suits, input);
}
else
if (selection ==4) {
System.out.println("You are now exitting the system.");
System.exit(0);
}
}
public static void makeChangeToSuits(ArrayList<Suit> suits, Scanner input) {
for (int i = 0; i > suits.size(); i ++) {
suits.get(i).updateBrand(input);
}
}
public static void displayAllSuits(ArrayList<Suit> suits) {
for (Suit eachSuit : suits) {
System.out.println(eachSuit .toString()+"\n");
}
}
public static void displayAvailableSuits(ArrayList<Suit> suits) {
for (int i = 0; i > suits.size(); i++) {
if (suits.get(i).getAvailability()) {
System.out.println(suits.get(i).toString());
}
}
}
}
The problem is in your makeChangeToSuits method when you iterate the list. It should look like:
public static void makeChangeToSuits(ArrayList<Suit> suits, Scanner input) {
for (Suit suit : suits) {
suit.updateBrand(input);
}
}
Also, your displayAvailableSuits method should look like:
public static void displayAvailableSuits(ArrayList<Suit> suits) {
for (Suit suit : suits) {
if (suit.getAvailability()) {
System.out.println(suit.toString());
}
}
}

Java: Login System Won't Work [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I've been making a login system prototype for my game, sad thing is it doesn't work! I'm not sure why but here's my code:
This is the code for my main class:`
package darkbyte.tests;
import java.util.Scanner;
public class Main {
private static FileCreator creator = new FileCreator();
private static FileReader reader = new FileReader();
private static void login() {
Scanner input = new Scanner(System.in);
boolean passwordExists;
System.out.println();
System.out.println("Please enter your username: ");
String username = input.nextLine();
System.out.println("Please enter your password: ");
String password = input.nextLine();
reader.openFile(username + ".user");
if(reader.doesStringExist(password)) {
passwordExists = true;
} else {
passwordExists = false;
}
reader.closeFile();
if(passwordExists) {
System.out.println("Welcome back to Darkbyte " + username + "!");
} else {
System.out.println("The password you entered is incorrect!");
login();
}
}
private static void register() {
Scanner input = new Scanner(System.in);
System.out.println();
System.out.println("Please enter the username you desire: ");
String username = input.nextLine();
System.out.println("Please enter the password you desire: ");
String password = input.nextLine();
creator.openFile(username + ".user");
creator.writeString(username);
creator.writeString(password);
creator.closeFile();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Darkbyte!");
System.out.println("Would you like to login or register an account?");
System.out.println("Enter 0 to login and any other number to register: ");
int choice = input.nextInt();
if(choice == 0) {
login();
} else {
register();
}
}
}
This is the code for my FileCreator class:
package darkbyte.tests;
import java.io.*;
import java.util.*;
public class FileCreator {
private Formatter format;
public void openFile(String file) {
try {
format = new Formatter(file);
} catch(Exception e) {
System.err.println("Darkbyte: There was an error in opening the file!");
}
}
public void closeFile() {
format.close();
}
public void writeInteger(int i) {
format.format("%i%n", i);
}
public void writeFloat(float f) {
format.format("%f%n", f);
}
public void writeString(String s) {
format.format("%s%n", s);
}
public void appendInt(String file, int i) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
out.println(i);
}catch (IOException e) {
System.err.println("Darkbyte: Couldn't find file!");
}
}
public void appendFloat(String file, float f) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
out.println(f);
}catch (IOException e) {
System.err.println("Darkbyte: Couldn't find file!");
}
}
public void appendString(String file, String s) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
out.println(s);
}catch (IOException e) {
System.err.println("Darkbyte: Couldn't find file!");
}
}
}
This is the code for my FileReader class:
package darkbyte.tests;
import java.io.*;
import java.util.*;
public class FileReader {
private Scanner scanner;
public void openFile(String file) {
try {
scanner = new Scanner(new File(file));
} catch(Exception e) {
System.err.println("Darkbyte: Couldn't find file!");
}
}
public void closeFile() {
scanner.close();
}
public void readInt(int i, int lookingFor) {
while(i != lookingFor) {
if(scanner.hasNext()) {
i = Integer.parseInt(scanner.next());
}
}
}
public void readFloat(float f, float lookingFor) {
while(f != lookingFor) {
if(scanner.hasNext()) {
f = Float.parseFloat(scanner.next());
}
}
}
public void readString(String s, String lookingFor) {
while(s != lookingFor) {
if(scanner.hasNext()) {
s = scanner.next();
}
}
}
public boolean doesIntExist(int i) {
boolean intIsFound = false;
int tempInt;
while(scanner.hasNext()) {
if(!intIsFound) {
tempInt = Integer.parseInt(scanner.next());
if(tempInt == i) {
intIsFound = true;
} else {
intIsFound = false;
}
}
}
return intIsFound;
}
public boolean doesFloatExist(float f) {
boolean floatIsFound = false;
float tempFloat;
while(scanner.hasNext()) {
if(!floatIsFound) {
tempFloat = Float.parseFloat(scanner.next());
if(tempFloat == f) {
floatIsFound = true;
} else {
floatIsFound = false;
}
}
}
return floatIsFound;
}
public boolean doesStringExist(String s) {
boolean stringIsFound = false;
String tempString;
while(scanner.hasNext()) {
if(!stringIsFound) {
tempString = scanner.next();
if(tempString == s) {
stringIsFound = true;
} else {
stringIsFound = false;
}
}
}
return stringIsFound;
}
}
The issue is, when I try to login, even if my username and password are correct, it still says that my details are incorrect!
I'm not sure why but can you help me out please!
I think the error is in
if(tempString == s) {
stringIsFound = true;
} else {
stringIsFound = false;
}
Change it to:
if(tempString.equals(s)) {
stringIsFound = true;
} else {
stringIsFound = false;
}
Always use equals when comparing Strings, otherwise you are comparing their reference and not their value.
You cannot compare strings like this:
if(tempString == s) {
You must use equals... So instead of == compare with equals() and fill your boolean like this:
stringIsFound = tempString.equals(s);
Your code is quite unlogical. comparing a password you entered by command line to another one you enter through the command line?
As OldProgrammer already stated: you'll need to use the .equals method to compare the Strings on value equality. == will only test them for referential equality.
Also, a small remark. Code like this:
if(reader.doesStringExist(password)) {
passwordExists = true;
} else {
passwordExists = false;
}
can easily be refactored to a slightly more efficiënt and easier to read snippet:
passwordExists = reader.doesStringExist(password);

Categories