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");
}
Related
If someone presses e, I want my game to stop at any time in the game.
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int points = 0;
int multiply;
System.out.println("press e to exit the game at any time! ");
System.out.println("please enter a number");
int yourNumber = input.nextInt();
for (multiply = 0; multiply<= 10; multiply++){
int yourAnswer = yourNumber * multiply;
System.out.println(yourNumber + " x " + multiply + " = ? ");
int theAnswer = input.nextInt();
for (int tries = 1; tries<= 4; tries++){
if (theAnswer == yourAnswer){
points = points + 5;
System.out.println("you have " + points + " points");
break;
}
else{
System.out.println("Your answer : " + theAnswer + " is wrong, please try again. Attempts : " + tries + " out of 4");
theAnswer = input.nextInt();
points--;
if (tries == 4){
System.out.println("sorry maximum attempts!!! moving to the next question");
tries++;
break;
}
}
}
}
}
}
Instead of just "int theAnswer = input.nextInt();" write this:
String nextIn = input.next();
int theAnswer = 0;
if (nextIn.equal("e")) {
System.out.println("Exiting the game...")
break;
}
else {
theAnswer = Integer.parseInt(nextIn);
}
I obviously haven't accounted for exceptions, but you can if you want.
So altogether it looks like this:
public class Game{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int points = 0;
int multiply;
System.out.println("press e to exit the game at any time!");
System.out.println("please enter a number");
int yourNumber = input.nextInt();
for (multiply = 0; multiply<= 10; multiply++){
int yourAnswer = yourNumber * multiply;
System.out.println(yourNumber + " x " + multiply + " = ? ");
//new part:
String nextIn = input.next();
int theAnswer = 0;
if (nextIn.equals("e")) {
System.out.println("Exiting the game...")
break;
} else {
theAnswer = Integer.parseInt(nextIn);
}
for (int tries = 1; tries<= 4; tries++){
if (theAnswer == yourAnswer){
points = points + 5;
System.out.println("you have " + points + " points");
break;
}
else{
System.out.println("Your answer : " + theAnswer + " is wrong, please try again. Attempts : " + tries + " out of 4");
theAnswer = input.nextInt();
points--;
if (tries == 4){
System.out.println("sorry maximum attempts!!! moving to the next question");
tries++;
break;
}
}
}
}
}
}
I can't figure this out
My variables aren't returning to print in the output message I have no idea where I am going wrong and my teacher tells me to go through the code line by line and check for logic and syntax errors. Any help would be appreciated.
package selfhelpstore;
import javax.swing.JOptionPane;
public class SelfHelpStore {
private static String getStringInput(String prompt) {
String input = JOptionPane.showInputDialog(prompt);
String nullFlag = "n";
int i = 1;
while (i<=2)
if (input == null) {
System.exit(0);
}else if (input.isEmpty()) {
i++;
nullFlag = "y";
prompt = JOptionPane.showInputDialog("Re-enter: ");
} else {
i=4;
nullFlag = "n";
}
if (!input.isEmpty()) {
nullFlag = "n";
}
if (nullFlag.equals("y")) {
JOptionPane.showMessageDialog(null, "Null or blank - exiting...");
System.exit(0);
}
return prompt;
}
public static void main(String[] args) {
String openingMsg, nameInputMsg, customerName, nameOutputMsg,
returnInputMsg, customerReturn, returnOutputMsg,
greetingOutputMsg, outputMsg,coverInputMsg, coverMsg ;
openingMsg = "*** Welcome to Self Help Book Store Online Ordering System ***\n"
+ " It's a great day to read a book!";
JOptionPane.showMessageDialog(null, openingMsg);
nameInputMsg = getStringInput("Please enter your name: ");
customerName = nameInputMsg;
returnInputMsg = getStringInput("Are you a returning customer (yes or no)? ");
customerReturn = returnInputMsg;
coverInputMsg = getStringInput("would you like this book in hard cover or paper back?");
coverMsg = coverInputMsg;
nameOutputMsg = "Welcome " + customerName + ".\n\n";
returnOutputMsg = "Your return customer status is " + customerReturn + ".\n";
greetingOutputMsg = "Thank you for visiting our Self Help Book Store!" + "\n"
+ "Your " + coverMsg + " should be mailed in less than two business days.\n";
outputMsg = nameOutputMsg + returnOutputMsg + greetingOutputMsg;
JOptionPane.showMessageDialog(null, outputMsg);
System.exit(0);
}
}
Your getStringInput method is returning the variable prompt, when you want it to return input.
private static String getStringInput(String prompt) {
String input = JOptionPane.showInputDialog(prompt);
String nullFlag = "n";
int i = 1;
while(i <= 2)
if(input == null)
{
System.exit(0);
} else if(input.isEmpty())
{
i++;
nullFlag = "y";
prompt = JOptionPane.showInputDialog("Re-enter: ");
} else {
i = 4;
nullFlag = "n";
}
if(!input.isEmpty()) {
nullFlag = "n";
}
if(nullFlag.equals("y")) {
JOptionPane.showMessageDialog(null, "Null or blank - exiting...");
System.exit(0);
}
return input; // Change this line
}
**this is what I have done so far. This program need me to display student info. There is no error when I run the program but the grade just isn't displayed. **
import java.io.*;
import java.math.MathContext;
class StudInfo {
public static DataInputStream d = new DataInputStream(System.in);
public static String matricNo[] = new String[100];
public static String name[] = new String[100];
public static int courseWorkMark []= new int[100];
public static int finalExamMark[] = new int [100];
public static String grade[] = new String[100];
public static double mark1;
public static double mark2;
public static int x = 1;
public static String sgrade;
public static int scourseWorkMark;
public static int sfinalExamMark;
//MENU
public static void main(String[] args)throws IOException {
menu();
}
public static void menu()throws IOException {
System.out.println("<<<-- MAIN MENU -->>>");
System.out.println("");
System.out.println("[1] Add\n[2] Edit\n[3] Delete\n[4] Search\n[5] View\n[6] Exit");
System.out.println("");
System.out.print("Select a menu: ");
int m = Integer.parseInt(d.readLine());
switch(m) {
case 1: //ADD DATA
addData();
break;
case 2: //EDIT DATA
editData();
break;
case 3: //DELETE DATA
DeleteData();
break;
case 4: //SEARCH DATA
SearchData();
break;
case 5: //VIEW DATA
viewData();
break;
case 6: //EXIT SYSTEM
break;
default:
break;
}
}
//DELETE
public static void DeleteData()throws IOException {
boolean result = false;
int index = 0;
spacing();
System.out.print("<<<-- DELETE RECORDS -->>>\n\n");
System.out.print("Search Student Matric Number: ");
String smatricNo = d.readLine();
for(int i=1;i<matricNo.length;i++) {
if(matricNo[i] !=null) {
if(smatricNo.equalsIgnoreCase(matricNo[i])) {
result = true;
index = i;
}
}
}
if(result == true) {
System.out.print("Matric: "+matricNo[index].toUpperCase()+ " ");
System.out.print("Name: "+name[index].toUpperCase()+ " ");
System.out.print("Course Work: "+courseWorkMark[index]+ " ");
System.out.print("Final Exam: "+finalExamMark[index]+ " ");
System.out.print("Grade: "+grade[index].toUpperCase()+ " ");
System.out.println("");
System.out.print("Are you sure to save this record?[y]-y/[n]-no: ");
String Ques = d.readLine();
if(Ques.equalsIgnoreCase("y")) {
matricNo[index] = null;
name[index] = null;
courseWorkMark[index] = 0;
finalExamMark[index] = 0;
grade[index] = null;
for(int j=index+1;j<matricNo.length;j++)
{
matricNo[j-1] = matricNo[j];
name[j-1] = name[j];
courseWorkMark[j-1] = courseWorkMark[j];
finalExamMark[j-1] = finalExamMark[j];
grade[j-1] = grade[j];
}
System.out.println("Record succesfully deleted!");
System.out.println("\n\n<Press Enter>");
String Ques1 = d.readLine();
spacing();
menu();
} else{
spacing();
menu();
}
} else{
System.out.print("Matric Number not found!");
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}
}
//SEARCH
public static void SearchData()throws IOException {
boolean result = false;
int index=0;
spacing();
System.out.print("<<<-- SEARCH DATA -->>>\n\n");
System.out.print("Search Student Matric Number: ");
String smatricNo = d.readLine();
for(int i=1;i<matricNo.length;i++) {
if(matricNo[i] !=null) {
if(smatricNo.equalsIgnoreCase(matricNo[i])) {
result = true;
index = i;
}
}
}
if(result==true) {
System.out.print("Matric: " + matricNo[index].toUpperCase() + " ");
System.out.print("Name: " + name[index].toUpperCase() + " ");
System.out.print("Course Work: " + courseWorkMark[index] + " ");
System.out.print("Final Exam: " + finalExamMark[index] + " ");
System.out.print("Grade: " + grade[index].toUpperCase() + " ");
System.out.println("");
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}else {
System.out.print("Matric Number not found!");
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}
}
//ADD
public static void addData()throws IOException {
spacing();
System.out.print("<<<-- ADD DATA -->>>\n\n");
System.out.print("Student Matric Number: ");
String smatricNo = d.readLine();
System.out.print("Student Name: ");
String sname = d.readLine();
System.out.print("Course Work: ");
scourseWorkMark = Integer.parseInt(d.readLine());
System.out.print("Final Exam: ");
sfinalExamMark = Integer.parseInt(d.readLine());
Calculate();
System.out.print("Grade: " + sgrade);
String sgrade = d.readLine();
System.out.print("Are you sure to save this record?[y]-y/[n]-no: ");
String Ques = d.readLine();
if(Ques.equalsIgnoreCase("y")) {
matricNo[x] = smatricNo;
name[x] = sname;
courseWorkMark[x] = scourseWorkMark;
finalExamMark[x] = sfinalExamMark;
grade[x] = sgrade;
x++;
spacing();
menu();
}else if(Ques.equalsIgnoreCase("n")) {
spacing();
menu();
}
}
public static void spacing() {
System.out.print("\n\n\n");
}
//VIEW
public static void viewData()throws IOException {
boolean center = false;
spacing();
System.out.print("<<<-- VIEW DATA -->>>\n\n");
for(int i=1;i<matricNo.length;i++) {
if(matricNo[i] != null) {
System.out.print("Matric Number: " + matricNo[i].toUpperCase()+ " ");
System.out.print("Name: " + name[i].toUpperCase()+ " ");
System.out.print("Course Work: " + courseWorkMark[i]+ " ");
System.out.print("Final Exam: " + finalExamMark[i]+ " ");
System.out.print("Grade: " + grade[i].toUpperCase()+ " ");
System.out.println("");
center=true;
}
}
if(center == false) {
System.out.print("\nEMPTY DATABASE. NO RECORDS FOUND!");
}
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}
//EDIT
public static void editData()throws IOException {
boolean result = false;
int index=0;
spacing();
System.out.print("<<<-- EDIT DATA -->>>\n\n");
System.out.print("Search Matric Number: ");
String smatricNo = d.readLine();
for(int i=1;i<matricNo.length;i++) {
if(matricNo[i] !=null) {
if(smatricNo.equalsIgnoreCase(matricNo[i])) {
result = true;
index = i;
}
}
}
if(result == true) {
System.out.print(matricNo[index] + " " +name[index]+ " " +courseWorkMark[index]+ " " +finalExamMark[index]+ " " +grade[index]+ " \n\n");
System.out.print("Student Matric Number: ");
String smatricNoedit = d.readLine();
System.out.print("Student Name: ");
String snameedit = d.readLine();
System.out.print("Course Work: ");
scourseWorkMark = Integer.parseInt(d.readLine());
System.out.print("Final Exam: ");
sfinalExamMark = Integer.parseInt(d.readLine());
Calculate();
System.out.print("Grade: " + sgrade);
String sgrade = d.readLine();
System.out.print("Are you sure to update this record?[y]-y/[n]-no: ");
String Ques = d.readLine();
if(Ques.equalsIgnoreCase("y")) {
matricNo[index] = smatricNoedit;
name[index] = snameedit;
courseWorkMark[index] = scourseWorkMark;
finalExamMark[index] = sfinalExamMark;
grade[index] = sgrade;
spacing();
menu();
}
else if(Ques.equalsIgnoreCase("n"))
{
spacing();
menu();
}
}else {
System.out.print("Matric Number not found!");
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}
}
//CALCULATION PART
public static String Calculate()
{
double mark1 = scourseWorkMark * 60 / 100;
double mark2 = sfinalExamMark * 40 / 100;
double totalMark = mark1 + mark2;
if (totalMark >= 90)
{
sgrade = "A+";
}
else if (totalMark >= 80)
{
sgrade = "A";
}
else if (totalMark >= 70)
{
sgrade = "A-";
}
else if (totalMark >= 65)
{
sgrade = "B+";
}
else if (totalMark >= 60)
{
sgrade = "B";
}
else if (totalMark >= 55)
{
sgrade = "C+";
}
else if (totalMark >= 50)
{
sgrade = "C";
}
else if (totalMark >= 45)
{
sgrade = "D";
}
else if (totalMark >= 40)
{
sgrade = "E";
}
else
{
sgrade = "F";
}
return;
}
}
Why can't the grade be displayed?
In the public static String Calculate() function, you need to return return sgrade; and currently, you are not returning any object, but the method calls for the return of a string.
Also, remove String sgrade = d.readLine(); from line 199 (in the addData function). This is causing problems, because you are defining a new variable with the same name as a class variable, and not specifying which one to use on the next few lines.
When I fix this, here is the output:
<<<-- MAIN MENU -->>>
[1] Add [2] Edit [3] Delete [4] Search [5] View [6] Exit
Select a menu: 1
<<<-- ADD DATA -->>>
Student Matric Number: 1
Student Name: Jake Chasan
Course Work: 100
Final Exam: 100 Grade: A+
<<<-- VIEW DATA -->>>
Matric Number: 1 Name: JAKE Course Work: 100
Final Exam: 100 Grade: A+
Below is my code, and there are no errors in the actual code, but it won't run and I am not sure how to fix it. I have been working on this assignment for hours and keep receiving the same error in the output box over and over.
import java.util.Scanner;
public class whatTheGerbils
{
public static void main(String[] args)
{
whatTheGerbils toRun = new whatTheGerbils();
toRun.gerbLab();
}
Gerbil[] gerbilArray;
Food[] foodArray;
int numGerbils;
int foodnum;
public whatTheGerbils() {}
public void gerbLab()
{
boolean gerbLab = true;
while(gerbLab)
{
foodnum = 0;
numGerbils = 0;
String nameOfFood = "";
String colorOfFood;
int maxAmount = 0;
String ID;
String name;
String onebite;
String oneescape;
boolean bite = true;
boolean escape = true;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many types of food do the gerbils eat?");
int foodnum = Integer.parseInt(keyboard.nextLine());
foodArray = new Food[foodnum];
for (int i = 0; i < foodnum; i++)
{
System.out.println("The name of food item " + (i+1) + ":"); //this is different
nameOfFood = keyboard.nextLine();
System.out.println("The color of food item " + (i+1) + ":");
colorOfFood = keyboard.nextLine();
System.out.println("Maximum amount consumed per gerbil:");
maxAmount = keyboard.nextInt();
keyboard.nextLine();
foodArray[i] = new Food(nameOfFood, colorOfFood, maxAmount);
}
System.out.println("How many gerbils are in the lab?");
int numGerbils = Integer.parseInt(keyboard.nextLine()); // this is different
gerbilArray = new Gerbil[numGerbils];
for (int i = 0; i < numGerbils; i++)
{
System.out.println("Gerbil " + (i+1) + "'s lab ID:");
ID = keyboard.nextLine();
System.out.println("What name did the undergrads give to "
+ ID + "?");
name = keyboard.nextLine();
Food[] gerbsBetterThanMice = new Food[foodnum];
int foodType = 0;
for(int k = 0; k < foodnum; k++)
{
boolean unsound = true;
while(unsound)
{
System.out.println("How much " + foodArray[k].getnameOfFood() + "does" + name + " eat?");
foodType = keyboard.nextInt();
keyboard.nextLine();
if(foodType <= foodArray[k].getamtOfFood())
{
unsound = false;
}
else
{
System.out.println("try again");
}
}
gerbsBetterThanMice[k] = new Food(foodArray[k].getnameOfFood(), foodArray[k].getcolorOfFood(), foodType);
}
boolean runIt = true;
while (runIt)
{
System.out.println("Does " + ID + "bite? (Type in True or False)");
onebite = keyboard.nextLine();
if(onebite.equalsIgnoreCase("True"))
{
bite = true;
runIt = false;
}
else if (onebite.equalsIgnoreCase("False"))
{
bite = false;
runIt = false;
}
else {
System.out.println("try again");
}
}
runIt = true;
while(runIt)
{
System.out.println("Does " + ID + "try to escape? (Type in True or False)");
oneescape = keyboard.nextLine();
if(oneescape.equalsIgnoreCase("True"))
{
escape = true;
runIt = false;
}
else if(oneescape.equalsIgnoreCase("False"))
{
escape = false;
runIt = false;
}
else
{
System.out.println("try again");
}
}
gerbilArray[i] = new Gerbil(ID, name, bite, escape, gerbsBetterThanMice);
}
for(int i = 0; i < numGerbils; i++)
{
for(int k = 0; k < numGerbils; k++)
{
if(gerbilArray[i].getID().compareTo(gerbilArray[k].getID()) >
0)
{
Gerbil tar = gerbilArray[i];
gerbilArray[i] = gerbilArray[k];
gerbilArray[k] = tar;
}
}
}
boolean stop = false;
String prompt = "";
while(!stop)
{
System.out.println("Which function would you like to carry out: average, search, restart, or quit?");
prompt = keyboard.nextLine();
if (prompt.equalsIgnoreCase("average"))
{
System.out.println(averageFood());
}
else if (prompt.equalsIgnoreCase("search"))
{
String searchForID = "";
System.out.println("What lab ID do you want to search for?");
searchForID = keyboard.nextLine();
Gerbil findGerbil = findThatRat(searchForID);
if(findGerbil != null)
{
int integer1 = 0;
int integer2 = 0;
for (int i = 0; i < numGerbils; i++)
{
integer1 = integer1 + foodArray[i].getamtOfFood();
integer2 = integer2 + findGerbil.getGerbFood()[i].getamtOfFood();
}
System.out.println("Gerbil name: " +
findGerbil.getName() + " (" + findGerbil.getBite() + ", " +
findGerbil.getEscape() + ") " +
Integer.toString(integer2) + "/" + Integer.toString(integer1));
}
else
{
System.out.println("error");
}
}
else if (prompt.equalsIgnoreCase("restart"))
{
stop = true;
break;
}
else if(prompt.equalsIgnoreCase("quit"))
{
System.out.println("program is going to quit");
gerbLab = false;
stop = true;
keyboard.close();
}
else
{
System.out.println("error, you did not type average, search, restart or quit");
}
}
}
}
public String averageFood()
{
String averageStuff = "";
double avg = 0;
double num1 = 0;
double num2 = 0;
for (int i = 0; i < numGerbils; i++)
{
averageStuff = averageStuff + gerbilArray[i].getID();
averageStuff = averageStuff + " (";
averageStuff = averageStuff + gerbilArray[i].getName();
averageStuff = averageStuff + ") ";
for (int k = 0; k < foodnum; k++)
{
num1 = num1 + foodArray[k].getamtOfFood();
num2 = num2 + gerbilArray[i].getGerbFood()[k].getamtOfFood();
}
avg = 100*(num2/num1);
avg = Math.round(avg);
averageStuff = averageStuff + Double.toString(avg);
averageStuff = averageStuff + "%\n";
}
return averageStuff;
}
public Gerbil findThatRat (String ID)
{
for(int i = 0; i < numGerbils; i++)
{
if(ID.contentEquals(gerbilArray[i].getID()))
{
return gerbilArray[i];
}
}
return null;
}
}
Whenever a Java program runs, it starts with a method called main. You are getting the error because you don't have such a method. If you write such a method, then what it needs to do is this.
Create an object of the whatTheGerbils class.
Run the gerbLab() method for the object that was created.
The simplest way to do this would be to add the following code inside the whatTheGerbils class.
public static void main(String[] args){
whatTheGerbils toRun = new whatTheGerbils();
toRun.gerbLab();
}
You need a main method in your code for it to run, add in something like this
public static void main(String [] args){
gerLab();
}
afer program outputs a winner, i ask if user wants to play again or exit but for some reason scanner doesn't read this input(continue or not). I even put prompt for continuation outside the while loop but still no luck:
"|XXX|
| O |
| O|
Player X is a winner!
Do you want to play again? Enter Y for yes or N for no!
BUILD SUCCESSFUL (total time: 26 seconds)
"
This is code:
public class TicTacToeRunner
{
public static void main(String[] args)
{
int row;
int column;
Scanner in = new Scanner(System.in);
TicTacToe game = new TicTacToe();
String player = "X";
boolean done = false;
int moveCounter = 0;
String answer;
int noMovement = -2;
int toQuit = -1;
int movesToCheckWins = 5;
int movesToCheckTies = 7;
while (!done)
{
do
{
row = column = noMovement;
System.out.print("\n" + game);
System.out.print("Please make a move " + (moveCounter + 1) + "(" + player + ")\nRow for " + player.toUpperCase() + " (or -1 to exit): ");
if (in.hasNextInt()) //check if input is an integer
{
row = in.nextInt();
}
if (row == toQuit) //if entered -1 quit the game
{
done = true;
System.out.println("Player " +player.toUpperCase() + " ended the game !");
System.exit(0); //game termination
}
else
{
System.out.print("Column for " + player.toUpperCase() + ": ");
if(in.hasNextInt()) //check if input is an integer
{
column = in.nextInt();
}
}
}while(!game.checkForValidMove(row, column)); //end of do-while loop if checkForValidMove is false
moveCounter++;
game.set(row, column, player);
if (moveCounter >= movesToCheckWins) //check wins after 5 moves
{
if (game.checkForWin(row, column, player)) //if a winner
{
done = true;
System.out.println("\n" + game);
System.out.println("Player " + player.toUpperCase() + " is a winner!");
}
}
if (moveCounter >= movesToCheckTies) //Check for ties after 7 moves
{
if (game.checkForEarlyTie()) //check for early tie
{
done = true;
System.out.println("\n" + game);
System.out.println("Tie Game after " + moveCounter + " moves!");
}
}
// Switching players
if (player.equals("X"))
{
player = "O";
}
else
{
player = "X";
}
}
System.out.println("Do you want to play again? Enter Y for yes or N for no!");
answer = in.nextLine();
answer = answer.toLowerCase(); //change input to lowercase for bullet proofing
if(answer.equals("y"))
{
done = false;
player = "X";
moveCounter = 0;
game.resetTheGame();
}
else
{
System.exit(0); //program termination
}
}
}
using a do while loop. your work is easy..
import java.util.Scanner;
public class TicTacToeRunner {
public static void main(String[] args) {
int row;
int column;
Scanner in = new Scanner(System.in);
TicTacToe game = new TicTacToe();
String player = "X";
boolean done = false;
String choice = "";
int moveCounter = 0;
String answer;
int noMovement = -2;
int toQuit = -1;
int movesToCheckWins = 5;
int movesToCheckTies = 7;
do{
while (!done) {
do {
row = column = noMovement;
System.out.print("\n" + game);
System.out.print("Please make a move " + (moveCounter + 1) + "(" + player + ")\nRow for " + player.toUpperCase() + " (or -1 to exit): ");
if (in.hasNextInt()) // check if input is an integer
{
row = in.nextInt();
}
if (row == toQuit) // if entered -1 quit the game
{
done = true;
System.out.println("Player " + player.toUpperCase() + " ended the game !");
System.exit(0); // game termination
} else {
System.out.print("Column for " + player.toUpperCase() + ": ");
if (in.hasNextInt()) // check if input is an integer
{
column = in.nextInt();
}
}
} while (!game.checkForValidMove(row, column)); // end of do-while
// loop if
// checkForValidMove
// is false
moveCounter++;
game.set(row, column, player);
if (moveCounter >= movesToCheckWins) // check wins after 5 moves
{
if (game.checkForWin(row, column, player)) // if a winner
{
done = true;
System.out.println("\n" + game);
System.out.println("Player " + player.toUpperCase() + " is a winner!");
}
}
if (moveCounter >= movesToCheckTies) // Check for ties after 7 moves
{
if (game.checkForEarlyTie()) // check for early tie
{
done = true;
System.out.println("\n" + game);
System.out.println("Tie Game after " + moveCounter + " moves!");
}
}
// Switching players
if (player.equals("X")) {
player = "O";
} else {
player = "X";
}
}
System.out.println("Do you want to play again? Enter Y for yes or N for no!");
choice = in.nextLine();
}while(choice.equals("y")||choice.equals("Y"));
}
}