I'm making a maze game that uses a 2D array to represent the game board. I currently have the console outputting "P" wherever the player's current position is. However, I would like to change every element in the array that the player has "visited" and display that to show their path. How would I do this? Do I need to make a second, duplicate array so I can make changes to that?
Here's my code:
import java.util.Scanner;
public class MazeGame {
private static char[][] maze = {
{'1','1','1','0','1','1','0','0','0','1','1','1','1'},
{'1','0','1','1','1','0','1','1','1','1','0','0','1'},
{'0','0','0','0','1','0','1','0','1','0','1','0','0'},
{'1','1','1','1','1','1','1','0','1','0','1','1','1'},
{'1','0','0','0','0','0','1','1','1','1','0','0','1'},
{'1','1','1','1','1','1','1','0','1','1','1','1','1'},
{'1','0','1','0','0','0','0','1','0','0','0','0','1'},
{'1','1','1','1','1','1','1','1','1','1','1','1','1'}
};
private static int playerRow = 0, playerCol = 0;
private static int moves = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
printMaze();
System.out.println("Welcome to the maze! Your goal is to make it from your starting position, the top left corner of the maze, to the end position, the bottom right corner of the maze. 1s represent spaces that you can move to, 0s represent walls that you can not move to, and Ps represent places that you have already been. To begin, enter an input: \n1-- 'U' for up\n2-- 'D' for down\n3-- 'L' for left\n4-- 'R' for right\n5-- 'Q' for quit\nHave fun playing the maze game and best of luck to you :)");
while (true) {
System.out.print("\nEnter a move (U/D/L/R/Q): ");
String move = input.nextLine();
if (move.charAt(0) == 'Q' || move.charAt(0) == 'q') {
System.out.println("Thanks for playing and have a wonderful day!");
System.exit(0);
}
if (move.length() == 1) {
if (move.charAt(0) == 'U' || move.charAt(0) == 'u') {
if (playerRow > 0 && maze[playerRow - 1][playerCol] != '0') {
playerRow--;
moves++;
} else {
System.out.println("Invalid move.");
}
} else if (move.charAt(0) == 'D' || move.charAt(0) == 'd') {
if (playerRow < maze.length - 1 && maze[playerRow + 1][playerCol] != '0') {
playerRow++;
moves++;
} else {
System.out.println("Invalid move. Please enter a valid move from the list below: \n1-- 'U' for up\n2-- 'D' for down\n3-- 'L' for left\n4-- 'R' for right\n5-- 'Q' for quit");
}
} else if (move.charAt(0) == 'L' || move.charAt(0) == 'l') {
if (playerCol > 0 && maze[playerRow][playerCol - 1] != '0') {
playerCol--;
moves++;
} else {
System.out.println("Invalid move.");
}
} else if (move.charAt(0) == 'R' || move.charAt(0) == 'r') {
if (playerCol < maze[0].length - 1 && maze[playerRow][playerCol + 1] != '0') {
playerCol++;
moves++;
} else {
System.out.println("Invalid move.");
}
} else {
System.out.println("Invalid move.");
}
} else {
System.out.println("Invalid move.");
}
printMaze();
if (playerRow == maze.length - 1 && playerCol == maze[0].length - 1) {
System.out.println("\nCongratulations, you have won the game in " + moves + " moves!");
break;
}
}
}
private static void printMaze() {
for (int i = 0; i < maze.length; i++) {
for (int j = 0; j < maze[0].length; j++) {
if (i == playerRow && j == playerCol) {
System.out.print("P ");
} else {
System.out.print(maze[i][j] + " ");
}
}
System.out.println();
}
}
}
In your case, you can straight away write P on location the player is before moving him to other part. As your conditions are maze[playerRow][playerCol + 1] != '0' it does not matter if there is 1 or P, it will be still accessible field.
maze[playerRow][playerCol] = 'P'
playerCol++;
moves++;
Yuo can add this line maze[playerRow][playerCol] = '*'; before you do the move up/down/left/right action.
In case the user enters an invalid move, it will not matter since the printMaze() method will overwrite the * with P for the current player coordinates, given by playerRow and playerCol.
if (move.length() == 1) {
maze[playerRow][playerCol] = '*';
I am trying to make a fraction calculator that quits when you type quit regardless of the casing. However these two errors have been coming up. Any suggestion?? Thanks a lot.
FractionCalculator.java:70: error: '(' expected
else if kb.next().equalsIgnoreCase("quit"){
^
FractionCalculator.java:70: error: ')' expected
else if kb.next().equalsIgnoreCase("quit"){
^
FractionCalculator.java:70: error: 'else' without 'if'
else if kb.next().equalsIgnoreCase("quit"){
^
import java.util.*;
public class FractionCalculator {
// useDelimiter or split method in string class
public static void main(String[] args) {
Greeting();
produceAnswer();
}
static String value1Str = "";
static String value2Str = "";
static char operator = ' ';
public static void Greeting() {
Scanner kb = new Scanner (System.in);
String userName;
System.out.print("Hello Person, What is your first name: ");
userName = kb.next();
System.out.println("Hi " +userName +", welcome to the great mystical fraction calculator.");
}
public static void produceAnswer() {
Scanner kb = new Scanner (System.in);
System.out.println("What is your input or type quit to leave?");
String input = kb.nextLine();
boolean value1Done = false;
boolean operatorDone = false;
boolean value2Done = false;
boolean correctFormat = false;
for (int i = 0; i < input.length(); i++) {
System.out.println("The input of given string is: " +input.charAt(i));
if (input.charAt(i) != ' ' && value1Done == false) {
value1Str += input.charAt(i);
}
else {
value1Done = true;
}
if (input.charAt(i) == '+' || input.charAt(i) == '-' || input.charAt(i) == '*' || input.charAt(i) == '/' && operatorDone == false && value1Done == true) {
operator = input.charAt(i);
operatorDone = true;
i=i+1;
}
if (input.charAt(i) != ' ' && value1Done == true && value2Done == false) {
value2Str += input.charAt(i);
}
else {
value2Done = false;
}
else if kb.next().equalsIgnoreCase("quit"){
System.out.println("Why are you leaving? Comeback soon bby");
break;
// quit = true;
//correctFormat = true;
}
}
System.out.println("value1Str is: " +value1Str);
System.out.println("Operator is: " +operator);
System.out.println("Value2Str is: " +value2Str);
}
}
You have errors in using if condition .
Updating your code with proper use of if , if else conditions.
import java.util.*;
public class FractionCalculator {
// useDelimiter or split method in string class
public static void main(String[] args) {
Greeting();
produceAnswer();
}
static String value1Str = "";
static String value2Str = "";
static char operator = ' ';
public static void Greeting() {
Scanner kb = new Scanner(System.in);
String userName;
System.out.print("Hello Person, What is your first name: ");
userName = kb.next();
System.out.println("Hi " + userName
+ ", welcome to the great mystical fraction calculator.");
}
public static void produceAnswer() {
Scanner kb = new Scanner(System.in);
System.out.println("What is your input or type quit to leave?");
String input = kb.nextLine();
boolean value1Done = false;
boolean operatorDone = false;
boolean value2Done = false;
boolean correctFormat = false;
for (int i = 0; i < input.length(); i++) {
System.out.println("The input of given string is: "
+ input.charAt(i));
if (input.charAt(i) != ' ' && value1Done == false) {
value1Str += input.charAt(i);
} else {
value1Done = true;
}
if (input.charAt(i) == '+' || input.charAt(i) == '-'
|| input.charAt(i) == '*' || input.charAt(i) == '/'
&& operatorDone == false && value1Done == true) {
operator = input.charAt(i);
operatorDone = true;
i = i + 1;
}
if (input.charAt(i) != ' ' && value1Done == true
&& value2Done == false) {
value2Str += input.charAt(i);
} else if (kb.next().equalsIgnoreCase("quit")) {
System.out.println("Why are you leaving? Comeback soon bby");
break;
// quit = true;
// correctFormat = true;
} else {
value2Done = false;
}
}
System.out.println("value1Str is: " + value1Str);
System.out.println("Operator is: " + operator);
System.out.println("Value2Str is: " + value2Str);
}
}
Check how to use if-then and if-then-else Statements at this link :
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
You have a malformed if statement:
if (...) { ....
}
else {
value2Done = false;
}
else // ERROR
An if statement cannot have two else clauses ... which you have here.
Indeed, the 3rd error message is saying that explicitly.
I am writing a Tic Tac Toe game and need to ask if the user wants to play again, (y/n). I have the game working, I'm just not sure how to loop it if the user hits y, and/or terminate it if the user hits n. I've tried several different things but can't seem to figure any of them out, so this is just my working code posted. Any help would be greatly appreciated!
import java.util.Scanner;
public class Assignment7 {
public static int row, col;
public static Scanner scan = new Scanner(System.in);
public static char[][] board = new char[3][3];
public static char turn = 'X';
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
/*create for-loop
* 9 empty spots, 3x3
*/
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = '_';
}
}
Play();
}
public static void Play() {
//find if game over
boolean playing = true;
PrintBoard();
while (playing) {
System.out.println("Please enter a row, then a column: ");
//make row next thing player types
row = scan.nextInt() - 1;
//same with column
col = scan.nextInt() - 1;
board[row][col] = turn;
if (GameOver(row, col)) {
playing = false;
System.out.println("Game over! Player " + turn + " wins!");
}
PrintBoard();
//switch players after entries
if (turn == 'X') {
turn = 'O';
} else {
turn = 'X';
}
}
}
public static void PrintBoard() {
for (int i = 0; i < 3; i++) {
System.out.println();
for (int j = 0; j < 3; j++) {
//get dividers on left
if (j == 0) {
System.out.print("| ");
}
// get dividers in all
System.out.print(board[i][j] + " | ");
}
}
//enter space after board
System.out.println();
}
public static boolean GameOver(int rMove, int cMove) {
// Check perpendicular victory
if (board[0][cMove] == board[1][cMove]
&& board[0][cMove] == board[2][cMove]) {
return true;
}
if (board[rMove][0] == board[rMove][1]
&& board[rMove][0] == board[rMove][2]) {
return true;
}
// Check diagonal victory
if (board[0][0] == board[1][1] && board[0][0] == board[2][2]
&& board[1][1] != '_') {
return true;
}
return false;
}
}
Simply use a do-while loop and wrap it around your "game" code...
When the Play method returns, prompt the user if they want to play another game, loop until they answer with anything other then "Y", for example
String input = null;
do {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = '_';
}
}
Play();
if (scan.hasNextLine()) {
scan.nextLine();
}
System.out.print("Do you want to play a game [Y/N]? ");
input = scan.nextLine();
} while ("y".equalsIgnoreCase(input));
I am writing a program that is supposed to calculate the Flesch index of a passage or string and tell the minimum education level required to comprehend.
What is supposed to happen is a person types in a string that the want to be calculated and the program is supposed to count the number of words and count the number of sentences as well as go through each word and calculate how many syllables there are in the word and add that to the total syllable counter. The way to calculate syllables is to count the number of adjacent vowels in a word, so "Computer" for instance has the vowels o, u, and e so 3 syllables. But, if the word ends in the letter e, subtract 1 from the total syllable count so, "Passage" has a, a, and e, but since the e is at the end, the syllable count is 2.
Here is what I got so far:
// Import scanner to get input from the user
import java.util.Scanner;
public class Flesch
{
public static void main (String [] args)
{
public static final double BASE = 206.835;
public static final double WORD_LENGTH_PENALTY = 84.6;
public static final double SENTENCE_LENGTH_PENALTY = 1.015;
Scanner input = new Scanner (System.in);
// Declare variables for syllables and words
int totalWords = 0;
int totalSyllables = 0;
// Prompt user for a passage of text
System.out.println ("Please enter some text:");
String passage = input.nextLine();
// Words
for (int i = 0; i < passage.length(); i++)
{
if (passage.charAt(i) == ' ') {
totalWords++;
}
else if (passage.charAt(i) == '.') {
totalWords++;
}
else if (passage.charAt(i) == ':') {
totalWords++;
}
else if (passage.charAt(i) == ';') {
totalWords++;
}
else if (passage.charAt(i) == '?') {
totalWords++;
}
else if (passage.charAt(i) == '!') {
totalWords++;
}
}
System.out.println ("There are " + totalWords + " words.");
char syllableList [] = {'a', 'e', 'i', 'o', 'u', 'y'};
// Syllables
for (int k = 0; k < syllableList.length; k++)
{
for (int i = 0; i < passage.length(); i++)
{
if (passage.charAt(i) == syllableList[k]) {
totalSyllables = totalSyllables + 1;
}
if (lastChar(passage) == 'E' || lastChar(passage) == 'e') {
totalSyllables = totalSyllables - 1;
} else {
break;
}
}
}
System.out.println ("There are " + totalSyllables + " syllables.");
input.close();
public static char lastChar (String aWord)
{
char aChar = aWord.charAt(aWord.length() - 2);
System.out.print (aChar);
return aChar;
}
/** Return true if the last character in the parameter word is
* a period, question mark, or exclaimation point, and false
* otherwise
**/
public static boolean sentenceEnd (String word)
{
if (lastChar(passage) == '.') {
return true;
} else if (lastChar(passage) == '?') {
return true;
} else if (lastChar(passage) == '!') {
return true;
} else {
return false;
}
}
double fleschIndex = BASE - WORD_LENGTH_PENALTY * (totalSyllables / totalWords) - SENTENCE_LENGTH_PENALTY * (totalWords / totalSentences);
if (fleschIndex > 100) {
educationLevel = "4th grader";
} else if (fleschIndex <= 100) {
educationLevel = "5th grader";
} else if (fleschIndex <= 90) {
educationLevel = "6th grader";
} else if (fleschIndex <= 80) {
educationLevel = "7th grader";
} else if (fleschIndex <= 70) {
educationLevel = "8th grader";
} else if (fleschIndex <= 60) {
educationLevel = "9th grader";
} else if (fleschIndex <= 50) {
educationLevel = "high school graduate";
} else if (fleschIndex <= 30) {
educationLevel = "college graduate";
} else if (fleschIndex < 0) {
educationLevel = "law school graduate";
}
System.out.println ("The Flesch idex is " + fleschIndex + ".");
System.out.println ("The text can be understood by a " + educationLevel + ".");
}
}
I keep getting some weird error messages telling me to put semi-colons around the boolean declarations which makes no sense to me.
It looks to me like you mixed up your methods.
The methods sentenceEnd and lastChar are inside the main-method. This is not allowed.
They have to be outside of the main-method but inside the Flesch-Class.
Wondering how to exit if total phrase is guessed and why my vowels, spaces and consonants are not counting? Most of progam runs great just cant figure out how to exit without saying "n" to question. I am returning values for counters, don't understand?
import java.util.Scanner;
public class Prog09
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
// Initializes all string variables
String sPhrase;
String answer;
// Initializes all int variables
int vowels = 0;
int consonants = 0;
int spaces = 0;
// Initializes all char variables
char cGuess = 0;
char vGuess = 0;
boolean valid = false;
// Asks user to enter if they want to play
System.out.print("Do you want to play a game? [y/n] ");
answer = stdIn.nextLine();
// Asks user to enter the phrase
System.out.print("Please enter the phrase to guess at : ");
sPhrase = stdIn.nextLine();
// Checks if user wants to play
while (answer.equalsIgnoreCase("y"))
{
char[] phrase = new char[sPhrase.length()];
char[] tmpArr = new char[sPhrase.length()];
for(int i = 0; i < sPhrase.length();i++)
{
tmpArr[i] = sPhrase.charAt(i);
phrase[i] = sPhrase.charAt(i);
}
// Runs methods and main body of program
initTemplateArray(sPhrase, tmpArr, spaces);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
while (answer.equalsIgnoreCase("y"))
{
//getConsonant(stdIn, cGuess);
cGuess = getConsonant(stdIn, cGuess);
vGuess = getVowel(stdIn, vGuess);
isVowel(vGuess, valid);
updateTemplateArray(tmpArr, sPhrase, cGuess, vGuess, consonants, vowels);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
stdIn.nextLine();
System.out.print("Do you want to try again? [y/n]: ");
answer = stdIn.next();
vGuess = 0;
cGuess = 0;
}
}
// Prints results
System.out.println("The common phrase contained: Spaces: " + spaces + " Consonants: " + consonants + " Vowels: " + vowels);
stdIn.close();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods for program
public static int initTemplateArray(String sPhrase, char [] tmpArr, int spaces)
{
for (int i = 0; i < sPhrase.length(); i++)
{
if (sPhrase.charAt(i) == ' ')
{
spaces++;
tmpArr[i] = ' ';
}
if (!(sPhrase.charAt(i) == ' '))
{
tmpArr[i] = '?';
}
}
return spaces;
}
public static void printTemplateArray(char [] tmpArr)
{
for (int i = 0; i < tmpArr.length; i++)
{
System.out.print(tmpArr[i]);
}
System.out.println();
}
public static boolean isVowel(char c, boolean valid)
{
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
return valid = true;
}
else
{
return valid = false;
}
}
public static char getConsonant(Scanner stdIn, char cGuess)
{
while(cGuess == 'a' || cGuess == 'e' || cGuess == 'i' || cGuess == 'o' || cGuess == 'u'|| cGuess == 0)
{
System.out.print("Enter a lowercase consonant guess : ");
String myGuess = stdIn.next();
cGuess = myGuess.charAt(0);
}
return cGuess;
}
public static char getVowel(Scanner stdIn, char vGuess)
{
while(!(vGuess == 'a' || vGuess == 'e' || vGuess == 'i' || vGuess == 'o' || vGuess == 'u'))
{
System.out.print("Enter a lowercase vowel guess : ");
String newGuess = stdIn.next();
vGuess = newGuess.charAt(0);
}
return vGuess;
}
public static int updateTemplateArray(char [] tmpArr, String sPhrase, char cGuess, char vGuess, int consonants, int vowels)
{
vowels = 0;
consonants = 0;
for (int i = 0; i < tmpArr.length; i++)
{
if (cGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
consonants++;
}
if (vGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
vowels++;
}
}
return consonants & vowels;
}
public static void printHeader()
{
System.out.println("");
System.out.println(" Common Phrase");
System.out.println("---------------");
}
}
Java passes Ints by value instead of by reference, this means that updateTemplateArray doesn't modify the values of main's vowels, consonants or spaces. To fix this you could:
Make these variables global by definining them outside the scope of the main method. You would have to change the name of the parameters in the updateTemplateArray method to prevent shadowing.
Break updateTemplateArray into separate functions to count each of the vowels, consonants or spaces, and have them return the count of each. You would then call something like: vowels = countVowels(sPhrase); to populate the variables.
With the current setup, it will exit whenever answer stops being equal to 'y' Changing the value of answer at any time will exit the loop.