I am having an unusual error with trying to return a string in my code. I am very new to java so I don't sometimes understand the ins and outs of how classes and returning values/assignment of values works. Any advice would be very helpful! Thank you :)
package videogaem;
import java.util.Scanner;
public class TeamName {
public String getTeamName() {
boolean valid_name = false;
Scanner reader = new Scanner(System.in);
while (valid_name == false) {
System.out.println("Enter team name here: ");
String team_name = reader.nextLine();
int name_length = team_name.length();
if (name_length >= 3 && name_length < 10) {
System.out.println(team_name + "... Sweet as name!");
valid_name = true;
return team_name;
}
else {
System.out.println("Name must be within 2 - 10 characters! :^)");
valid_name = false;
}
}
reader.close();
return team_name; /// <<< team_name is underlined red with the error
}
public static void main(String[] args) {
TeamName team = new TeamName();
team.getTeamName();
}
}
You need to declare the variable name outside the while condition. You have declared the variable name inside the while loop, so it's scope lies inside the while loop.Make sure the scanner is closed. In if statement you simply returning the team_name you have not closed the reader. It's opened, so first close the reader and then return the team_name.
import java.util.Scanner;
public class TeamName {
public String getTeamName() {
String team_name = null;
boolean valid_name = false;
Scanner reader = new Scanner(System.in);
while (valid_name == false) {
System.out.println("Enter team name here: ");
team_name = reader.nextLine();
int name_length = team_name.length();
if (name_length >= 3 && name_length < 10) {
System.out.println(team_name + "... Sweet as name!");
valid_name = true;
}
else {
System.out.println("Name must be within 2 - 10 characters! :^)");
valid_name = false;
}
}
reader.close();
return team_name;
}
public static void main(String[] args) {
TeamName team = new TeamName();
team.getTeamName();
}
}
in the getTeamName() method declear the String team_name ..
remove from the inner scope and right just before this scope.😊
Related
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);
}
}
}
in here i want to collect everything after a substring and set it as their specfic field.
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
/**
*
*
* class StudentReader for retrieveing data from file
*
*/
public class StudentReader {
public static Student[] readFromTextFile(String fileName) {
ArrayList<Student> result = new ArrayList<Student>();
File f = new File(filename);
Scanner n = new Scanner(f);
while (n.hasNextLine()) {
String text = n.nextLine();
}
n.close();
String hold1[] = text.Split(",");
String hold2[] = new String[hold1.length];;
for(int i = 0; i < hold1.length(); ++i) {
hold2[i] = hold1.Split("=");
if (hold2[i].substring(0,3).equals("name")) {
}
}
return result.toArray(new Student[0]);
}
}
backing up the goal of this code is to first open and read a file where it has about 20 lines that look just like this
Student{name=Jill Gall,age=21,gpa=2.98}
I then need to split it as done above, twice first to get rid of comma and the equals, I then for each line need to collect the value of the name, age and double, parse them and then set them as a new student object and return that array they are going to be saved onto, what I am currently stuck on is that i cannot figure out what's the right code here for collecting everything after "name" "age" "gpa", as i dont know how to set specific substrings for different name
im using this link as a reference but I don't see what actually does it
How to implement discretionary use of Scanner
I think the bug is in following lines,
while (n.hasNextLine()) {
String text = n.nextLine();
}
Above code should throw compilation error at String hold1[] = text.Split(","); as text is local variable within while loop.
Actual it should be,
List<String> inputs = new ArrayList<String>()
Scanner n = new Scanner(f);
while (n.hasNextLine()) {
inputs.add(n.nextLine());
}
You can use above inputs list to manipulate your logic
By the look of it, at least by your ArrayList<> declaration, you have a class named Student which contains member variable instances of studentName, studentAge, and studentGPA. It might look something like this (the Getter/Setter methods are of course optional as is the overriden toString() method):
public class Student {
// Member Variables...
String studentName;
int studentAge = 0;
double studentGPA = 0.0d;
// Constructor 1:
public Student() { }
// Constructor 2: (used to fill instance member variables
// right away when a new instance of Student is created)
public Student(String name, int age, double gpa) {
this.studentName = name;
this.studentAge = age;
this.studentGPA = gpa;
}
// Getters & Setters...
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}
public double getStudentGPA() {
return studentGPA;
}
public void setStudentGPA(double studentGPA) {
this.studentGPA = studentGPA;
}
#Override
public String toString() {
return new StringBuilder("").append(studentName).append(", ")
.append(String.valueOf(studentAge)).append(", ")
.append(String.valueOf(studentGPA)).toString();
}
}
I should think the goal would be to to read in each file line from the Students text file where each file line consists of a specific student's name, the student's age, and the student's GPA score and create a Student instance for the Student on that particular file line. This is to be done until the end of file. If there are twenty students within the Students text file then, when the readFromTextFile() method has completed running there will be twenty specific instances of Student. Your StudentReader class might look something like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
*
* class StudentReader for retrieving data from file
*
*/
public class StudentReader {
private static final Scanner userInput = new Scanner(System.in);
private static Student[] studentsArray;
public static void main(String args[]) {
String underline = "=====================================================";
String dataFilePath = "StudentsFile.txt";
System.out.println("Reading in Student data from file named: " + dataFilePath);
if (args.length >= 1) {
dataFilePath = args[0].trim();
if (!new File(dataFilePath).exists()) {
System.err.println("Data File Not Found! (" + dataFilePath + ")");
return;
}
}
studentsArray = readFromTextFile(dataFilePath);
System.out.println("Displaying student data in Console Window:");
displayStudents();
System.out.println(underline);
System.out.println("Get all Student's GPA score average:");
double allGPA = getAllStudentsGPAAverage();
System.out.println("GPA score average for all Students is: --> " +
String.format("%.2f",allGPA));
System.out.println(underline);
System.out.println("Get a Student's GPA score:");
String sName = null;
while (sName == null) {
System.out.print("Enter a student's name: --> ");
sName = userInput.nextLine();
/* Validate that it is a name. Should validate in
almost any language including Hindi. From Stack-
Overflow post: https://stackoverflow.com/a/57037472/4725875 */
if (sName.matches("^[\\p{L}\\p{M}]+([\\p{L}\\p{Pd}\\p{Zs}'.]*"
+ "[\\p{L}\\p{M}])+$|^[\\p{L}\\p{M}]+$")) {
break;
}
else {
System.err.println("Invalid Name! Try again...");
System.out.println();
sName = null;
}
}
boolean haveName = isStudent(sName);
System.out.println("Do we have an instance of "+ sName +
" from data file? --> " +
(haveName ? "Yes" : "No"));
// Get Student's GPA
if (haveName) {
double sGPA = getStudentGPA(sName);
System.out.println(sName + "'s GPA score is: --> " + sGPA);
}
System.out.println(underline);
}
public static Student[] readFromTextFile(String fileName) {
List<Student> result = new ArrayList<>();
File f = new File(fileName);
try (Scanner input = new Scanner(f)) {
while (input.hasNextLine()) {
String fileLine = input.nextLine().trim();
if (fileLine.isEmpty()) {
continue;
}
String[] lineParts = fileLine.split("\\s{0,},\\s{0,}");
String studentName = "";
int studentAge = 0;
double studentGPA = 0.0d;
// Get Student Name (if it exists).
if (lineParts.length >= 1) {
studentName = lineParts[0].split("\\s{0,}\\=\\s{0,}")[1];
// Get Student Age (if it exists).
if (lineParts.length >= 2) {
String tmpStrg = lineParts[1].split("\\s{0,}\\=\\s{0,}")[1];
// Validate data.
if (tmpStrg.matches("\\d+")) {
studentAge = Integer.valueOf(tmpStrg);
}
// Get Student GPA (if it exists).
if (lineParts.length >= 3) {
tmpStrg = lineParts[2].split("\\s{0,}\\=\\s{0,}")[1];
// Validate data.
if (tmpStrg.matches("-?\\d+(\\.\\d+)?")) {
studentGPA = Double.valueOf(tmpStrg);
}
}
}
}
/* Create a new Student instance and pass the student's data
into the Student Constructor then add the Student instance
to the 'result' List. */
result.add(new Student(studentName, studentAge, studentGPA));
}
}
catch (FileNotFoundException ex) {
System.err.println(ex);
}
return result.toArray(new Student[result.size()]);
}
public static void displayStudents() {
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return;
}
for (int i = 0; i < studentsArray.length; i++) {
System.out.println(studentsArray[i].toString());
}
}
public static boolean isStudent(String studentsName) {
boolean found = false;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return found;
} else if (studentsName == null || studentsName.isEmpty()) {
System.err.println("Student name can not be Null or Null-String (\"\")!");
return found;
}
for (int i = 0; i < studentsArray.length; i++) {
if (studentsArray[i].getStudentName().equalsIgnoreCase(studentsName)) {
found = true;
break;
}
}
return found;
}
public static double getStudentGPA(String studentsName) {
double score = 0.0d;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return score;
} else if (studentsName == null || studentsName.isEmpty()) {
System.err.println("Student name can not be Null or Null-String (\"\")!");
return score;
}
boolean found = false;
for (int i = 0; i < studentsArray.length; i++) {
if (studentsArray[i].getStudentName().equalsIgnoreCase(studentsName)) {
found = true;
score = studentsArray[i].getStudentGPA();
break;
}
}
if (!found) {
System.err.println("The Student named '" + studentsName + "' could not be found!");
}
return score;
}
public static double getAllStudentsGPAAverage() {
double total = 0.0d;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return total;
}
for (int i = 0; i < studentsArray.length; i++) {
total += studentsArray[i].getStudentGPA();
}
return total / (double) studentsArray.length;
}
}
I'm having trouble understanding how to parse text documents with unknown amounts of 'students'. All my solutions are coming up strange and I'm having trouble with the Scanner. Breaking down the input, the first integer represents how many classes there are, the first string is the class name, the following are students with respective dates and variables that need to be stored along with the student, with an unknown amount of students. I want to store each student along with the class they are in.
My code is extremely messy and confusing so far:
String filename = "input.txt";
File file = new File(filename);
Scanner sc = new Scanner(file);
Student[] studArr = new Student[100];
int studCounter = 0;
boolean breaker = false;
boolean firstRun = true;
int numClasses = sc.nextInt();
System.out.println(numClasses);
while(sc.hasNextLine()){
String className = sc.nextLine();
System.out.println("Name: " + className);
String test = null;
breaker = false;
sc.nextLine();
// Breaks the while loop when a new class is found
while (breaker == false){
Student temp = null;
// Boolean to tell when the first run of the loop
if (firstRun == true){
temp.name = sc.nextLine();
}
else
temp.name = test;
System.out.println(temp.name);
temp.date = sc.nextLine();
if (temp.date.isEmpty()){
System.out.println("shit is empty yo");
}
temp.timeSpent = sc.nextInt();
temp.videosWatched = sc.nextInt();
temp.className = className;
studArr[studCounter] = temp;
studCounter++;
sc.nextLine();
test = sc.nextLine();
firstRun = false;
}
}
}
}
class Student {
public String name;
public String date;
public String className;
public int timeSpent;
public int videosWatched;
}
I don't need an exact answer, but should I be looking into a different tool then Scanner? Is there a method I can research?
Thanks for any assistance.
I came up with the following solution. Scanner is a fine tool for the job. The tricky part is that you have to sort of look ahead to see if you have a blank line or a date to know if you have a student or a class.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Parser {
private static String nextLine(Scanner sc) {
String line;
while (sc.hasNext()) {
if (!(line = sc.nextLine()).isEmpty()) {
return line;
}
}
return null;
}
public static ArrayList<Student>[] parseFile(String fileName) {
File file = new File(fileName);
try (Scanner sc = new Scanner(file)) {
int numClasses = sc.nextInt();
String className = nextLine(sc);
ArrayList<Student>[] classList = new ArrayList[numClasses];
for (int i = 0; i < numClasses; i++) {
classList[i] = new ArrayList<>();
while (true) {
String studentOrClassName = nextLine(sc);
if (studentOrClassName == null) {
break;
}
String dateOrBlankLine = sc.nextLine();
if (dateOrBlankLine.isEmpty()) {
className = studentOrClassName;
break;
}
int timeSpent = sc.nextInt();
int videosWatched = sc.nextInt();
classList[i].add(new Student(className, dateOrBlankLine, studentOrClassName, timeSpent,
videosWatched));
}
}
return classList;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new ArrayList[0];
}
public static void main(String[] args) {
for (ArrayList<Student> students : parseFile("classList.txt")) {
if (!students.isEmpty()) {
System.out.println(students.get(0).className);
}
for (Student student : students) {
System.out.println(student);
}
}
}
static class Student {
public String className;
public String date;
public String name;
public int timeSpent;
public int videosWatched;
public Student(String className, String date, String name, int timeSpent,
int videosWatched) {
this.className = className;
this.date = date;
this.name = name;
this.timeSpent = timeSpent;
this.videosWatched = videosWatched;
}
public String toString() {
return name + '\n' + date + '\n' + timeSpent + '\n' + videosWatched + '\n';
}
}
}
Ask yourself, what does a Student contain? A name, date, number and number. So you want to do the following (not actual code) (format written in Lua code, very understandable. This means this will not run in Lua :P)
if line is not empty then
if followingLine is date then
parseStudent() // also skips the lines etc
else
parseClass() // also skips lines
end
end
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()
**Hello, I have to create a hangman game in java. I cant use arrays. Most of my code is done but I have been having some problems and some tips would be welcome.
I just found something else that I could use help on. After prompting the user for a new secret word and using newHangMan.setSecretWord(newWord); my disguised word does not reset to "????" (with the same number of "?" as words in the secret word).
I'm very sorry for such a long post and the bad formatting(1st time posting here).
Can anyone help?**
This is my class file:
public class HangMan
{
private String secretWord = "bigbang", disguisedWord = "";
private int guessCount = 0, missCount = 0;
public void setSecretWord(String newWord)
{
secretWord = newWord;
guessCount = 0;
missCount = 0;
int wordLength = newWord.length();
while(wordLength > 0)
{
disguisedWord = disguisedWord + "?";
wordLength--;
}
}
public String getSecretWord()
{
return secretWord;
}
public boolean isFound()
{
return secretWord.equalsIgnoreCase(disguisedWord);
}
public String getDisguisedWord()
{
return disguisedWord;
}
public int getGuessCount()
{
return guessCount;
}
public int getMissesCount()
{
return missCount;
}
public void guessCharacter(char c)
{
// int position = secretWord.indexOf(c);
boolean got_it = false;
String updateDisguised="";
for(int i=0; i < secretWord.length();i++)
{
if(c == secretWord.charAt(i))
{
updateDisguised = updateDisguised + secretWord.charAt(i);
String checkDuplicate = updateDisguised.substring(0,i);
int duplicatePos = checkDuplicate.indexOf(c);
if(duplicatePos <0)
guessCount++;
got_it = true;
}
else
{
updateDisguised = updateDisguised + disguisedWord.charAt(i);
}
}
if(got_it == false)
{
missCount++;
guessCount++;
}
disguisedWord = updateDisguised;
}
}
This is my main method:
import java.util.Scanner;
public class HangManGame {
public static void main(String[] args)
{
boolean retry= true;
String retry_ans;
Scanner kb = new Scanner(System.in);
HangMan newHangMan = new HangMan();
String word = newHangMan.getSecretWord();
String input;
char guess;
newHangMan.setSecretWord(word);
System.out.println("Hangman game starts:");
do{
System.out.println("Guess this: " + newHangMan.getDisguisedWord());
System.out.println("Enter your guess character: [guess]");
input = kb.next();
guess = input.charAt(0);
newHangMan.guessCharacter(guess);
System.out.println(newHangMan.getDisguisedWord());
System.out.println("Number of guesses so far : " + newHangMan.getGuessCount());
System.out.println("NUmber of misses so far: " + newHangMan.getMissesCount());
if((newHangMan.getMissesCount()==7) || (newHangMan.isFound()))
{
System.out.println("The game is over");
System.out.println("Would you like to try again?");
retry_ans = kb.next();
if(retry_ans.equalsIgnoreCase("yes"))
{
retry = true;
System.out.println("Please enter a new secret word:");
String newWord = kb.next();
newHangMan.setSecretWord(newWord);
}
else
{
retry =false;
}
}
} while(retry == true);
}
}
(newHangMan.isFound()=true)
should be
newHangMan.isFound()
Do not make an bool compare to another bool.
The = is evaluate the boolean.
Replace
while(retry = true);
with
while(retry);
The former is an assignment, so it never evaluates to false although it should.
Your while condition is an assignment, rather than a comparison, which is likely the cause of your problem - you're setting the value of retry to true (retry = true) rather than checking that the value of retry currently equals true (retry == true).
Classic java starter error. while check stetement should be
While(retry == true)