How can I access my private variables across different classes? - java

I am working on creating a hangman-like game. It reads from a .txt file of four letter words and randomly selects one of the words and the player will then have 7 tries to guess the word...I have not completed that all yet, I am having trouble accessing my variables from one class to the other. Here is my code:
package wordguessinggame2;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class WordGuessingGame2 {
static class RandomWordProvider {
public final List<String> words;
public RandomWordProvider() {
words = readFile();
}
public int randomInteger() {
int randomInt = (int) (Math.random() * words.size());
return randomInt;
}
private 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("File not found.");
}
return wordsList ;
}
}
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.containsIgnoreCase(playerInput)){
}
}
}
Here at the bottom I am trying to access randomWord and playerInput from my other classes but I don't know how to do that. I am still fairly new to programming so I don't know how to do everything yet. Would I do a get and set method for each variable? I have tried doing that and I'm having a lot of trouble with that. If someone could show me how to access variables across classes it would be greatly appreciated!

Here's a slightly simplified example where the RandomWordProvider and PlayerCharacterEntry classes are NOT nested inside WordGuessingGame2.
I show only the methods I needed to modify:
class RandomWordProvider {
String getWord() {
int randomPosition = randomInteger();
String randomWord = words.get(randomPosition);
return randomWord;
}
// ...
}
class PlayerCharacterEntry {
String playerEntry() {
Scanner characterEntry = new Scanner(System.in);
System.out.print("Enter a character: ");
String playerInput = characterEntry.next();
playerInput = playerInput.toUpperCase();
return playerInput;
}
}
class WordGuessingGame2 {
public static void main(String[] args) {
// ...
RandomWordProvider randomWordProvider = new RandomWordProvider();
PlayerCharacterEntry playerCharacterEntry = new PlayerCharacterEntry();
randomWordProvider.getWord();
playerCharacterEntry.playerEntry();
}
}
Notice that I dropped the private modifier from the getWord and playerEntry methods,
otherwise they are not accessible from WordGuessingGame2.
It's good to start with the strictest possible modifiers,
and then reduce the restrictions as necessary.

No, private variables are only accessable from within the class it self. It's highly recommended that you create public getters and setters to maintain the OO principle of encapsulation.

Related

User input and object creation inside method

I have a Java Class named Real
public class Real {
private long wholeNumPart;
private long decimalPart;
public Real(){
wholeNumPart =0;
decimalPart=0;
}
public Real(long wholeNumPart, long decimalPart) {
this.wholeNumPart =wholeNumPart;
this.decimalPart = decimalPart;
}
public long getWholeNumPart() {
return wholeNumPart;
}
public long getDecimalPart() {
return decimalPart;
}}
I have another class name RealApplication where I need to create two methods
createRealObject() that allows a user to input a real number and creates an object representing
that number.
2.createRealNumber() which accepts an object of type Real and returns a real number represented
by that object.
I am having difficulty creating these two methods
Here is what I've done so far
import java.util.Scanner;
public class RealApplication {
public void createRealNumber() {
Scanner sc=new Scanner(System.in);
//Allows user input
System.out.print("Please, enter a real number: ");
long n = sc.nextLong();
//Creates Real object ( is this correct????)
Real in = new Real();
}
public long createRealNumber(Real num) {
long realNum=0;
//I do not know what to write here :(
return realNum;
}
}
Your Real class looks good with some changes in the RealApplication class we can achieve what you want:
import java.util.Scanner;
public class RealApplication {
public static Real createRealObject() {
Scanner sc=new Scanner(System.in);
//Allows user input
System.out.print("Please, enter a real number: ");
String n = sc.nextLine();
String[] pieces = n.split("[.,]+"); //special pattern to recognize comma and dot
long wholeNumPart;
long decimalPart;
try {
wholeNumPart = Long.valueOf(pieces[0]);
decimalPart = Long.valueOf(pieces[1]);
}
catch (NumberFormatException e) {
System.out.println("You should enter a number!");
return null;
}
Real in = new Real(wholeNumPart, decimalPart);
sc.close();
return in;
}
The important point is that I declared the both methods as static in this way you can use the methods without creating an instance of RealApplication class.
You should use "double" primitive type to store fractional numbers not "long". Now the method that returns the number equivalent of that object:
public static double createRealNumber(Real num) {
double realNum;
long wholeNumPart = num.getWholeNumPart();
long decimalPart = num.getDecimalPart();
int numOfDigits = (int)(Math.log10(decimalPart)+1);
realNum = wholeNumPart + (decimalPart / Math.pow(10,numOfDigits));
return realNum;
}
And if we write a main method:
public class Main {
public static void main(String[] args) {
Real realObj = new Real(10,2323232);
double number = RealApplication.createRealNumber(realObj);
System.out.println("Equivalent number for the object: " + number);
Real newObj = RealApplication.createRealObject();
if (newObj != null) {
System.out.println("New object's number part: " + newObj.getWholeNumPart());
System.out.println("New object's decimal part: " + newObj.getDecimalPart());
}
else{
return;
}
}
}
Because of the regex pattern we used, the inputs separated with "." and "," are allowed like 10.23 10,23 .

How can I fix these errors? java program

I have been working on a program.
I keep getting these errors:
StationInformation.java:65: error: non-static variable this cannot be referenced from a static context
Station mile_end = new Station();
^
StationInformation.java:66: error: non-static variable this cannot be referenced from a static context
Station oxford_circus = new Station();
^
StationInformation.java:67: error: non-static variable this cannot be referenced from a static context
Station kings_cross = new Station();
^
StationInformation.java:68: error: non-static variable this cannot be referenced from a static context
Station stepney_green = new Station();
^
4 errors
I want to fix the program.
I have made Station class as static and returning a list from create_messages().
//this program tells the user whether a station is a step free access station or not and how far is it from the platform
import java.util.Scanner; // imports the scanner function to input data from the user
import java.util.ArrayList;
import java.util.List;
class StationInformation {
public static void main(String[] args) // main method where methods are sequenced
{
int numberOfStations = inputint("how many stations do you want to know about?");
String station;
for (int i = 1; i <= numberOfStations; i++) {
station = inputstring("what station do you want to know about?");
search_station(station);
}
System.exit(0);
}
// A method to input integers
public static int inputint(String message) {
Scanner scanner = new Scanner(System.in);
int answer;
System.out.println(message);
answer = Integer.parseInt(scanner.nextLine());
return answer;
} // END inputInt
public static String inputstring(String message) {
Scanner scanner = new Scanner(System.in);
String answer;
System.out.println(message);
answer = scanner.nextLine();
return answer;
}
public static String create_message(Station station) {
String message;
if (station.step_free_access == true) {
message = (station.name + "does have step free access. " + "it is " + station.distance_from_platform
+ "m away from the entrance");
} else {
message = (station.name + "does not have step free access. " + "it is " + station.distance_from_platform
+ "m away from the entrance");
}
return message;
}
public static List<String> create_messages() {
Station mile_end = new StationInformation.Station();
Station oxford_circus = new Station();
Station kings_cross = new Station();
Station stepney_green = new Station();
mile_end.distance_from_platform = 50;
mile_end.name = "Mile End ";
mile_end.step_free_access = false;
String message1 = create_message(mile_end);
oxford_circus.distance_from_platform = 200;
oxford_circus.name = " Oxford Circus ";
oxford_circus.step_free_access = true;
String message2 = create_message(oxford_circus);
kings_cross.distance_from_platform = 700;
kings_cross.name = " kings cross ";
kings_cross.step_free_access = true;
String message3 = create_message(kings_cross);
stepney_green.distance_from_platform = 300;
stepney_green.name = " Stepney Green ";
stepney_green.step_free_access = false;
String message4 = create_message(stepney_green);
List<String> list = new ArrayList<>();
list.add(message1);
list.add(message2);
list.add(message3);
list.add(message4);
return list;
}
public static void search_station(String station) {
List<String> list = create_messages();
String mileEndMessage = list.get(0);
String oxfordCircusMessage = list.get(1);
String kingsCrossMessage = list.get(2);
String stepneyGreenMessage = list.get(3);
if (station.equals("Mile End")) {
System.out.println(mileEndMessage);
} else if (station.equals("kings cross")) {
System.out.println(kingsCrossMessage);
} else if (station.equals("oxford circus")) {
System.out.println(oxfordCircusMessage);
} else if (station.equals("stepney green")) {
System.out.println(stepneyGreenMessage);
} else {
System.out.println(station + " is not a London underground station ");
}
}
static class Station // a record to store information about stations
{
int distance_from_platform;
String name;
boolean step_free_access;
}
}
Edit: This answer might seem outdated since the OP decided to edit the question, removing his code in the process.
There are 2 errors in your code:
Your inner class Station is not static, meaning you cannot instantiate it in a static context. This is producing the error messages you see.
You are thinking that Java is pass-by-reference, and are trying to override the value the variable(s) are pointing to (which you cannot do in Java).
You can fix your mistakes by making your Station-class static (static class Station), and by making the stations you use class-variables, and using their fields to create a String.
You could also implement a getInfo()-method for the Station-class that prepares its info on its own. With this, you can just call System.out.println(STATION_YOU_WANT.getInfo()).
I have taken a bit of my time to write a commented solution to the question.
The most confusing part of it is probably the use of varargs (String... in the code below). They basically allow you to pass any number of arguments to a method, which will inherently be converted to an array by Java.
import java.util.HashMap;
import java.util.Locale;
import java.util.Scanner;
public class StationInformation {
private static class Station {
private String name;
private int distanceToPlatform;
private boolean stepFree;
private String[] alternateNames;
Station(String name, int distanceToPlatform, boolean stepFree, String...alternateNames) {
this.name = name;
this.distanceToPlatform = distanceToPlatform;
this.stepFree = stepFree;
this.alternateNames = alternateNames; // 'String...' makes that parameter optional, resulting in 'null' if no value is passed
}
String getInfo() {
return name + " does" + (stepFree ? " " : " not ")
+ "have step free access.\nIt is " + distanceToPlatform + "m from entrance to platform.";
}
}
private static HashMap<String, Station> stations = new HashMap<String, Station>();
public static void main(String[] args) {
createStations();
// The Program
Scanner scanner = new Scanner(System.in);
// Keep requesting input until receiving a valid number
int num;
for (;;) { // 'for (;;) ...' is effectively the same as 'while (true) ...'
System.out.print("How many stations do you need to know about? ");
String input = scanner.nextLine();
try {
num = Integer.parseInt(input);
break;
} catch (Exception exc) {
// Do nothing
}
System.out.println("Please enter a correct number.");
}
for (int i = 0; i < num; ++i) {
System.out.print("\nWhat station do you need to know about? ");
String input = scanner.nextLine();
// If available, show Station-information
if (stations.containsKey(input.toLowerCase(Locale.ROOT))) {
System.out.println(stations.get(input.toLowerCase(Locale.ROOT)).getInfo());
} else {
System.out.println("\"" + input + "\" is not a London Underground Station.");
}
}
scanner.close(); // Close Scanner; Here actually not needed because program will be closed right after, freeing its resources anyway
}
private static void createStations() {
// Add new Stations here to automatically add them to the HashMap
Station[] stations = new Station[] {
new Station("Stepney Green", 100, false),
new Station("King's Cross", 700, true, "Kings Cross"),
new Station("Oxford Circus", 200, true)
};
for (Station station : stations) {
StationInformation.stations.put(station.name.toLowerCase(Locale.ROOT), station);
// Alternative names will be mapped to the same Station
if (station.alternateNames == null) continue;
for (String altName : station.alternateNames)
StationInformation.stations.put(altName.toLowerCase(Locale.ROOT), station);
}
}
}

Profanity Filter: I just need some help on how to make it recognize _only_ the values in an array

/*
Profanity Filter:
- Cat
- Dog
- LLama
- Has to differ cases, like cAt
- Has to differ words that contain the words to be filtered, "Cataclysm", for example. Hello, World of Warcraft.
*/
import java.util.Scanner;
public class ProfanityFilter
{
public static void main (String[] args)
{
Scanner kb = new Scanner(System.in);
String userInput, toLowerCase;
boolean flag = false;
int i;
String[] list = new String[12];
list[0] = "cat";
list[1] = " cat";
list[2] = "cat ";
list[3] = " cat ";
list[4] = "dog";
list[5] = " dog";
list[6] = "dog ";
list[7] = " dog ";
list[8] = "llama";
list[9] = " llama";
list[10] = "llama ";
list[11] = " llama ";
System.out.println("Enter a string:");
userInput = kb.nextLine();
toLowerCase = userInput.toLowerCase();
for (i = 0; i < list.length; i++)
{
if(toLowerCase.contains(list[i]) | toLowerCase.equals(list[i]))
{
flag = true;
}
}
if (flag)
{
System.out.println("Something you said is forbidden.");
}
else
{
System.out.println("Nothing was found");
}
}
}
I'm just having trouble finding the proper exception to what I need. I know I'm pretty close, but I'm also tired after trying many many hours to solve this problem and coming out empty of a solution that will return true for the instances I need (the ones in the array). Can you point me out to what I'm doing wrong in here or to a proper solution without regular expressions?
I've already tried to put a break; after I turn the boolean flag to true but it didn't work, it keeps iterating and thus the output keeps being false.
Thanks!
Here is a potential solution:
public class Class {
private static final String[] profaneWords = {
"cat",
"dog",
"llama"
};
public static void main(String... args) {
System.out.println(isProfane("this is some user input."));
System.out.println(isProfane("this is some user input containing the dirty word 'Cat'."));
System.out.println(isProfane(" cat "));
System.out.println(isProfane("Cat"));
}
private static boolean isProfane(final String input) {
for (final String profanity : profaneWords) {
if (input.toLowerCase().contains(profanity)) {
return true;
}
}
return false;
}
}
Here is a streaming java8 version:
import java.util.Arrays;
public class Class {
private static final String[] profaneWords = {
"cat",
"dog",
"llama"
};
private static boolean isProfane(final String input) {
return Arrays.stream(profaneWords)
.anyMatch(input.toLowerCase()::contains);
}
}

Why is my class variable rewriting itself after an unrelated method runs?

So I'm writing a basic MasterMind game that is... mostly functional. However, its exhibiting odd behavior and I'm unsure why.
The idea is that what defines a Code and its behavior is one file, the gameplay is another, and the Main just creates a new game and starts playing. When I initialize the game, the computer creates a new random string of 4 (the "secret code"), as expected; but then once I get input for the User guess, it seems to rewrite the secret code into whatever I've input. Further, my methods for evaluating matches don't work at all, but considering that the secret code keeps changing means that it's not being set to begin with, and I'm unsure why.
All three classes below. Why is my class variable in Game not setting properly and accessible to the other methods?
Main.java
class Main {
public static void main(String[] args) {
Game newGame = new Game();
newGame.play();
}
}
Code.java
import java.util.Random;
import java.util.HashMap;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Set;
import java.lang.Math;
import java.lang.StringBuilder;
class Code {
private static HashMap<String,String> PEGS;
private static ArrayList<String> pegStrings;
protected static String secretCodeString;
public static void main(String[] args) {
}
public Code(String input){
this.secretCodeString = input;
}
public Code(){
randomize();
}
//literally just creates the peghash
public static void setPegs(){
PEGS = new HashMap<String,String>();
PEGS.put("C","c");
PEGS.put("Y","y");
PEGS.put("R","r");
PEGS.put("P","p");
PEGS.put("O","o");
PEGS.put("G","g");
}
//turns the pegs ito something randomize can use
public static ArrayList<String> makePegArray(){
setPegs();
pegStrings = new ArrayList<String>();
Collection<String> pegValues = PEGS.values();
Object[] pegObjects = pegValues.toArray();
for (int i = 0; i < pegObjects.length; i++){
pegStrings.add(pegObjects[i].toString());
}
return pegStrings;
}
// sets Class Variable secretCode to a four letter combination
public static Code randomize(){
secretCodeString = new String();
Random rand = new Random();
int randIndex = rand.nextInt(makePegArray().size());
for (int i = 0; i < 4; i++){
randIndex = rand.nextInt(makePegArray().size());
secretCodeString = secretCodeString.concat(makePegArray().get(randIndex));
}
Code secretCode = parse(secretCodeString);
return secretCode;
}
public static Code parse(String input) {
setPegs();
makePegArray();
String[] letters = input.split("");
StringBuilder sb = new StringBuilder();
for (String letter : letters) {
if (pegStrings.contains(letter)) {
sb.append(letter);
} else {
System.out.println(letter);
throw new RuntimeException();
}
}
String pegListString = sb.toString();
Code parsedCode = new Code(pegListString);
//System.out.println(parsedCode);
return parsedCode;
}
public int countExactMatches(Code guess){
String guessString = guess.secretCodeString;
int exactMatches = 0;
String[] guessArray = guessString.split("");
String[] winningCodeArray = (this.secretCodeString).split("");
for(int i = 0; i < 4; i++){
if(guessArray[i] == winningCodeArray[i]){
exactMatches++;
}
}
return exactMatches;
}
public int countNearMatches(Code guess) {
String guessString= guess.secretCodeString;
HashMap<String,Integer> guessCount = new HashMap<String,Integer>();
HashMap<String,Integer> secretCodeCount = new HashMap<String,Integer>();
Set<String> codeKeys = guessCount.keySet();
int matches = 0;
int keys = guessCount.keySet().size();
String[] keyArray = new String[keys];
for(int i = 0; i < guessString.length(); i++) {
//removes character from string
String codeCharacter = String.valueOf(guessString.charAt(i));
String guessShort = guessString.replace(codeCharacter,"");
//counts instances of said character
int count = guessString.length() - guessShort.length();
guessCount.put(codeCharacter, count);
}
for(int i = 0; i < secretCodeString.length(); i++) {
//removes character from string
String winningString = this.secretCodeString;
String winningCodeCharacter = String.valueOf(winningString.charAt(i));
String winningCodeShort = guessString.replace(winningCodeCharacter,"");
//counts instances of said character
int count = winningString.length() - winningCodeShort.length();
secretCodeCount.put(winningCodeCharacter, count);
}
for (int i = 0; i < keys; i++) {
codeKeys.toArray(keyArray);
String keyString = keyArray[i];
if (secretCodeCount.containsKey(keyString)) {
matches += Math.min(secretCodeCount.get(keyString), guessCount.get(keyString));
}
}
int nearMatches = matches - countExactMatches(guess);
return nearMatches;
}
}
Game.java
import java.util.Scanner;
class Game {
protected static Code winningCode;
public static void main(String[] args){
}
public Game(){
winningCode = new Code();
}
protected static Code getGuess() {
Scanner userInput = new Scanner(System.in);
int count = 0;
int maxTries = 5;
while(true){
try {
String codeToParse = userInput.next();
Code guess = Code.parse(codeToParse);
return guess;
} catch(RuntimeException notACode) {
System.out.println("That's not a valid peg. You have " + (maxTries - count) + " tries left.");
if (++count == maxTries) throw notACode;
}
}
}
protected static void displayMatches(Code guess){
int nearMatches = winningCode.countNearMatches(guess);
int exactMatches = winningCode.countExactMatches(guess);
System.out.println("You have " + exactMatches + " exact matches and " + nearMatches + " near matches.");
}
protected static void play(){
int turnCount = 0;
int maxTurns = 10;
System.out.println("Greetings. Pick your code of four from Y,O,G,P,C,R.");
while(true){
Code guess = getGuess();
displayMatches(guess);
if (guess == winningCode) {
System.out.print("You win!!");
break;
} else if (++turnCount == maxTurns) {
System.out.print("You lose!!");
break;
}
}
}
}
On every guess, you call Code.parse, Code.parse creates a new Code (new Code(pegListString);) and that constructor sets the secretCodeString and because that's static, all instances of Code share the same variable. You need to avoid mutable static members.
Another tip is to either have a method return a value, or mutate state (of either its input, or its own instance, this), but avoid doing both.
"Why is my class variable rewriting itself after an unrelated method runs?"
Because, actually, it is not unrelated. The "mess" that you have created by declaring variables and methods as static has lead to unwanted coupling between different parts of your code.
It is difficult to say what the correct solution is here because your code has gotten so confused by the rewrites that it is hard to discern the original "design intent".
My advice would be to start again. You now should have a clearer idea of what functionality is required. What you need to do is to redo the object design so that each class has a clear purpose. (The Main and Game classes make sense, but Code seems to be a mashup of functionality and state that has no coherent purpose.)

Java Scanner issues, Notecard class

I am trying to make a program that is basically virtual notecards. Each notecard has a string for a question and an answer as well as a count for now many times it has been asked. I am using a scanner in many instances and I think i am using it incorrectly, and am not quite sure why. The program will let me answer the first 2 questions, tell me they are incorrect no matter what, and skip letting me answer the last one. Here is the notecard class:
public class Notecard {
public String ans;
public String q;
public int count;
public Notecard(String q, String ans) {
this.q = q;
this.ans = ans;
this.count = 0;
}
public Boolean answer(String effort) {
if (this.q.toUpperCase().equals(effort.toUpperCase())) {
System.out.println("Correct!");
return true;
} else {
System.out.println("Incorrect! Correct answer:" + this.ans);
count++;
return false;
}
}
public void clearCount() {
this.count = 0;
}
public String getQ() {
return this.q;
}
}
and here is my other file:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class CreateNotecard {
int trys;
public static void main(String[] args) {
System.out.println("Get ready to be quizzed \n\n");
ArrayList<Notecard> notecards = makeCards();
quiz(notecards);
}
static ArrayList<Notecard> makeCards() {
ArrayList<Notecard> notecards = new ArrayList<Notecard>();
try {
BufferedReader in = new BufferedReader(new FileReader(
"notecards.txt"));
String str;
str = in.readLine();
while ((str = in.readLine()) != null) {
String[] argg = str.split(",");
notecards.add(new Notecard(argg[0], argg[1]));
}
in.close();
} catch (IOException e) {
System.out.println("File Read Error");
}
return notecards;
}
static void quiz(ArrayList<Notecard> notecards) {
ArrayList<Notecard> backupList = notecards;
Scanner sc = new Scanner(System.in);
long seed = System.nanoTime();
Collections.shuffle(notecards, new Random(seed));
int total = notecards.size();
int correct = 0;
for (Notecard x : notecards) {
System.out.println(x.getQ());
String effort = sc.next();
Boolean nailedIt = x.answer(effort);
if (nailedIt) {
correct++;
}
}
System.out.println("Total Notecards: " + total + "\nTotal Correct: "
+ correct);
System.out.println("Accuracy: " + (correct / total));
System.out.println("Do you want to repeat? Put \"y\" or \"n\"");
String choice1 = sc.nextLine();
if (choice1.toUpperCase().equals("Y")) {
System.out.println("Use only cards missed or all? Type \"missed\" or \"all\"");
String choice2 = sc.nextLine();
if (choice2.toUpperCase().equals("MISSED")) {
quiz(notecards);
} else {
quiz(backupList);
}
} else {
return;
}
}
}
I have a text file which I am using for this program, it contains
19-9,10
square root of 4,2
capitol of Missouri,Jefferson City
Blastoise's 1st evolution,squirtle
and my output is
Get ready to be quizzed
square root of 4
2
Incorrect! Correct answer:2
capitol of Missouri
Jefferson City
Incorrect! Correct answer:Jefferson City
Blastoise's 1st evolution
Incorrect! Correct answer:squirtle
Total Notecards: 3
Total Correct: 0
Accuracy: 0
Do you want to repeat? Put "y" or "n"
You are comparing the wrong things:
public Boolean answer(String effort) {
if (this.q.toUpperCase().equals(effort.toUpperCase())) {
Should be
if (this.ans.toUpperCase().equals(effort.toUpperCase())) {
The problem is that the Scanner class is looking for a delimiter to create tokens with, which is by default whitespace. Since you enter "2", the Scanner.next() finds no delimiters, so no token.
For example, if you enter "Jefferson City", the Scanner found one delimiter, so two tokens. sc.next in that case would be "Jefferson" only (no "City", that's the next token).
Solution? Read the line from stdin and using sc.nextLine()

Categories

Resources