Connect 4 game exception handler for array In Java - java

I already finished my program it is a connect 4 console game the only problem is I don't know where should I place my ArrayIndexOutOfBoundsException in the code in order for it to this is what I want to put in the code
try {
int element = Input.nextInt();
System.out.println("Element in the given index is :: "+myArray[element]);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("The index you have entered is invalid");
System.out.println("Please enter an index number between 0 and 6");
}
this is the game code it is made out of 3 classes
I'll post the game Engine for the program if it is not helpful I'll post the gameboard
public class C4GameEngine {
public static void main(String[] args) throws Exception {
String Start = "+------------------------------------------------------------------------------+\n" +
"| Welcome to Connect Four console application. |\n" +
"| Each player alternately drops a 'R' or 'Y' into one of the seven columns. |\n" +
"| The objective of the game is to connect four of the same characters in |\n" +
"| a row, column or diagonal. |\n" +
"+------------------------------------------------------------------------------+ ";
System.out.println(Start);
//We will use the scanner for using input have Input as reference variable
Scanner Input = new Scanner(System.in);
//making the red player enter their name
System.out.println("Red player enter your name: ");
String red = Input.nextLine();
//calling out the player class
PlayerClass p1 = new PlayerClass(red, "R");
//yellow player to enter their name
System.out.println("Yellow player enter your name: ");
String yellow = Input.nextLine();
//calling the player class for the yellow player
PlayerClass p2 = new PlayerClass(yellow, "Y");
// creating the while loop the purpose of it is to make the player decide if they want to keep playing
while (true) {
System.out.print("Do you want to keep playing? Type Y or N: ");
if (Input.nextLine().equalsIgnoreCase("Y")) {
//making the board game pattern and calling the connect four board
String[][] board = C4Board.createPattern();
boolean loop = true;
//in order to keep track of the turns
int count = 0;
C4Board.drawPattern(board);
while (loop) {
//this will let the red have the first turn then after every other turn yellow will play
if (count % 2 == 0) C4Board.dropRedPattern(board, p1.getName()); //getting the name
else C4Board.dropYellowPattern(board, p2.getName());
count++; //keeping track of the turns
C4Board.drawPattern(board);
if (C4Board.checkWinner(board) != null) {
//using the if statment to print out the winner if it is red
//one point will be set to red and then the question will repeat
//do you want to keep playing if you say Y you'll go back to the
//new game until you go with N it'll get out of the loop and show you the stats
if (C4Board.checkWinner(board) == "R") {
System.out.println("Red won.");
p1.setGameWon();
} else if (C4Board.checkWinner(board) == "Y") {
System.out.println("Yellow won.");
p2.setGameWon();
}
loop = false;
}
}
} else if (Input.nextLine().equalsIgnoreCase("N")) {
System.out.println(p1.toString());
System.out.println("--------------------");
System.out.println(p2.toString());
System.exit(0);
}
And now the gameboard
import java.util.Scanner;
//Creating the connect four board body
public class C4Board {
//We need to first create the basic visual pattern first using 2D array
public static String[][] createPattern() {
//creating a double array named field that will hold the length of array
String[][] field = new String[7][15];
// creating a loop for each row
for (int i =0;i<field.length;i++) {
// creating a loop for each column
for (int j =0;j<field[i].length;j++) {
if (j% 2 == 0){
//the column will be either empty or have a | depending on the disk
field[i][j] ="|";
} else {
field[i][j] = " ";
}
//creating the base for the row
if (i==6) field[i][j]= "-";
}
}
return field;
public static void drawPattern(String[][] f) {
for (int i =0;i<f.length;i++) {
for (int j=0;j<f[i].length;j++) {
System.out.print(f[i][j]);
}
System.out.println();
}
}
public static void dropRedPattern(String[][] f, String Name) {
//the first move would be is to have the User to tell us
//where he wants to drop the disk which column
System.out.println("+----------------------------------+\n");
//the Name String will display the end name of the user in game stat
System.out.print(Name + " drop a red disk at column (0–6):\n ");
System.out.println("+----------------------------------+\n");
//using it for keyboard input
Scanner Input = new Scanner (System.in);
int c = 2*Input.nextInt()+1;
for (int i =5;i>=0;i--) {
if (f[i][c] == " ") {
f[i][c] = "R";
break;
}
}
}
//this is the same as for the yellow disk
public static void dropYellowPattern(String[][] f, String Name) {
System.out.println("+----------------------------------+\n");
System.out.print(Name + " drop a Yellow disk at column (0–6):\n ");
System.out.println("+----------------------------------+\n");
Scanner scan = new Scanner (System.in);
int c = 2*scan.nextInt()+1;
for (int i =5;i>=0;i--) {
if (f[i][c] == " ") {
f[i][c] = "Y";
break;
}
}
}
//for the check winner in connect four you can win in many ways
//so there is going to be a for loop checking each of those
public static String checkWinner(String[][] f) {
//checking horizontal line
for (int i =0;i<6;i++) {
//the red or yellow disk or nothing will be in odd places
//we'll start from 0 (which will be 1) and stop at 6 (which will be 7)
for (int j=0;j<7;j+=2) {
if ((f[i][j+1] != " ")
&& (f[i][j+3] != " ")
&& (f[i][j+5] != " ")
&& (f[i][j+7] != " ")
&& ((f[i][j+1] == f[i][j+3])
&& (f[i][j+3] == f[i][j+5])
&& (f[i][j+5] == f[i][j+7])))
//returning the color if the pattern is the same
return f[i][j+1];
}
}
//vertical line looping over each odd column to check for repeated boxes in the same column
for (int i=1;i<15;i+=2) {
//we are vertically checking each line of the code now by the for loop statement so it's from 0 to 2
for (int j =0;j<3;j++) {
if((f[j][i] != " ")
&& (f[j+1][i] != " ")
&& (f[j+2][i] != " ")
&& (f[j+3][i] != " ")
&& ((f[j][i] == f[j+1][i])
&& (f[j+1][i] == f[j+2][i])
&& (f[j+2][i] == f[j+3][i])))
return f[j][i];
}
}
//For the diagonal line the loop has to go over the 3 uppermost rows
//then left to right column
for (int i=0;i<3;i++) {
for (int j=1;j<9;j+=2) {
//still using the odd index for the column and incrementing by 2
if((f[i][j] != " ")
&& (f[i+1][j+2] != " ")
&& (f[i+2][j+4] != " ")
&& (f[i+3][j+6] != " ")
&& ((f[i][j] == f[i+1][j+2])
&& (f[i+1][j+2] == f[i+2][j+4])
&& (f[i+2][j+4] == f[i+3][j+6])))
return f[i][j];
}
}
//this is the same as above but instead of going left to right we will go the opposing direction
for (int i=0;i<3;i++) {
for (int j=7;j<15;j+=2) {
if((f[i][j] != " ")
&& (f[i+1][j-2] != " ")
&& (f[i+2][j-4] != " ")
&& (f[i+3][j-6] != " ")
&& ((f[i][j] == f[i+1][j-2])
&& (f[i+1][j-2] == f[i+2][j-4])
&& (f[i+2][j-4] == f[i+3][j-6])))
return f[i][j];
}
}
//the null statement will return nothing if it doesn't find any disk anywhere
return null;
}
}

Related

Rockpapergame with rounds and counter variables - java

I am creating a rock paper project which has the following requirement:
Continually plays rounds of rock, paper, scissors until one of the players wins three rounds. At that point, the program outputs the winner and the number of rounds it took them to win. If there is no winner after 10 rounds, the competition is declared a tie
Something seems to be missing which I am not quite able to understand or notice. How would I make my game stop after the rounds and declare a winner?
Note: No arrays, external libraries other than scanner, or any built-in methods of java allowed
This is my attempt:
import java.util.Scanner;
public class Rockpaper{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
String player1 = keyboard.next();
String player2 = keyboard.next();
String player = "Player1";
int round = 1;
boolean go = true;
boolean win = false;
while(go){
if (player1.equals("r") && player2.equals("p")){
win = true;
}
else if (player1.equals("p") && player2.equals("r")){
win = true;
}
else if (player1.equals("p") && player2.equals("s")){
win = true;
}
else if (player1.equals("s") && player2.equals("p")){
win = true;
}
else if (player1.equals("s") && player2.equals("r")){
win = true;
}
else if (player1.equals("r") && player2.equals("s")){
win = true;
}
else if (player1.equals("r") && player2.equals("r")){
win = false;
}
else if (player1.equals("p") && player2.equals("p")){
win = false;
}
else if (player1.equals("s") && player2.equals("s")){
win = false;
}
if (round < 5){
System.out.println(win+" after "+round+" rounds!");
go = false;
}else{
System.out.println("Tie - No winner after "+round+" rounds!");
}
if (player.equals("Player1"){
Player = "Player2";
}else{
Player = "Player1";
}
}
}
}
The problem I see is that there needs to be a separate variable that counts each of the win possibilities, for example, "win1" which would count the player1 win possibility and "win2" that would count the player2 wins. I am not quite sure about the rounds variable that would initially start counting the rounds up to 10 which is the maximum.
Sample input/output:
Currently you read the input only once, before the loop:
String player1 = keyboard.next();
String player2 = keyboard.next();
After every match, you should ask if players should continue playing. If so, then you must ask for their input again. This is, just move the "playerX" variable declaration and initialization inside the loop:
//comment/remove these
//String player1 = keyboard.next();
//String player2 = keyboard.next();
//inside the loop
while(go){
String player1 = keyboard.next();
String player2 = keyboard.next();
if (player1.equals("r") && player2.equals("p")){
/* rest of your code */
}
Also, this section:
if (round < 5){
System.out.println(win+" after "+round+" rounds!");
go = false;
}else{
System.out.println("Tie - No winner after "+round+" rounds!");
}
if (player.equals("Player1"){
Player = "Player2";
}else{
Player = "Player1";
}
}
It seems odd for two things:
round is never increased.
The else after round < 5 will be always executed, wrongly stating that there's a tie.
Reassigning Player variable for asking user input is not necessary. Instead, you could use 2 variables to store names of your players that are initialized before the game begins.
One more thing: instance of Scanner is Closeable, so each time you use it to read user input, you make sure that the instance is closed after is not needed anymore, in this case, at the end of the program.
More hints:
Reduce several if/else with the same output to a single if evaluation
You could make use of methods to ease game result.
With all this in mind, your code may look like this:
import java.util.Scanner;
public class RockPaperScizzorGame {
public static int getGameResult(String player1Move, String player2Move) {
int result = 0; //assume the game will be a tie
//player 2 wins
if (player1Move.equals("r") && player2Move.equals("p")
|| player1.equals("p") && player2.equals("s")
|| player1.equals("s") && player2.equals("r")
) {
result = 2;
}
//player 1 wins
if (player1.equals("p") && player2.equals("r")
|| player1.equals("s") && player2.equals("p")
|| player1.equals("r") && player2.equals("s")) {
result = 1;
}
//return the result: 0, 1 or 2
return result;
}
public static void main (String[] args) {
try (Scanner keyboard = new Scanner(System.in)) {
String player1Name = "Player 1";
String player2Name = "Player 2";
int round = 0;
boolean go = true;
int winsPlayer1 = 0;
int winsPlayer2 = 0;
while (go) {
System.out.println("Make your move " + player1Name + ": ");
String player1Move = keyboard.next();
System.out.println("Make your move " + player2Name + ": ");
String player2Move = keyboard.next();
int gameResult = getGameResult(player1Move, player2Move);
switch(gameResult) {
case 1:
winsPlayer1++;
break;
case 2:
winsPlayer2++;
break;
}
round++;
if (winsPlayer1 == 3) {
System.out.println(player1Name + " won after " + round + " rounds!");
go = false;
} else if (winsPlayer2 == 3) {
System.out.println(player2Name + " won after " + round + " rounds!");
go = false;
} else {
if (round == 5 && winsPlayer1 < 3 && winsPlayer2 < 3) {
System.out.println("Tie - No winner after "+round+" rounds!");
go = false;
}
}
} catch (IOException e) {
System.out.println("Issues when trying to accept user input.");
e.printStacktrace();
}
}
}
You can improve the code even more:
Use more methods to ease the code in main method.
Since your main loop depends more on a counter rather than a boolean flag, you may use a for loop rather than a while.
You may ask for user input for the name of the players.
You may create a class to encapsulate data of your players: name, currentMove, number of wins.
Problems with your code:
Not using separate variables for individual players.
Not putting input statements inside the loop as a result of which the input statements run only once.
Not changing the value of the variable, round but using its value in the condition, if (round < 5) which will always evaluate true if the value of round is not increased.
Solution
import java.util.Scanner;
public class Rockpaper {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int round = 1;
boolean go = true;
int player1Score = 0;
int player2Score = 0;
while (go && round <= 10) {
String player1 = keyboard.next();
String player2 = keyboard.next();
if (player1.equals("r") && player2.equals("p")) {
player2Score++;
} else if (player1.equals("p") && player2.equals("r")) {
player1Score++;
} else if (player1.equals("p") && player2.equals("s")) {
player2Score++;
} else if (player1.equals("s") && player2.equals("p")) {
player1Score++;
} else if (player1.equals("s") && player2.equals("r")) {
player2Score++;
} else if (player1.equals("r") && player2.equals("s")) {
player1Score++;
}
if (player1Score >= 3) {
System.out.println("Player1 wins " + " after " + round + " rounds!");
go = false;
}
if (player2Score >= 3) {
System.out.println("Player2 wins " + " after " + round + " rounds!");
go = false;
}
round++;
}
if (round > 10) {
System.out.println("Tie - No winner after " + (round - 1) + " rounds!");
}
}
}
First sample run:
p
r
r
s
s
s
r
r
p
r
Player1 wins after 5 rounds!
Second sample run:
p
p
p
r
r
r
s
s
p
p
s
s
s
s
p
p
r
p
s
p
Tie - No winner after 10 rounds!

Two problems. Not adding to next index in array and not removing from array

The problem I have encountered is as follows: I have created two array representing docking spaces for ships. The first array the ship object (shipName and size - usually Super-Container) be saved in the array and if there is no space then it will be added to a waiting list array. If the space in the first array becomes vacant then the ship from the waiting list will join the first array.
But when I go to undock (remove a ship from the first array) it only finds the ship in index 0 of the first array and not index 1, 2 etc.
Also, I can only add one ship to the waiting list and it says it is full.
Can you help? Here's my dock class, problem in undock() and waitingList():
import java.util.*;
public class Main {
static Scanner scan = new Scanner(System.in);
private static Ship[] dock1 = new Ship[10];
private static Ship[] waitingList = new Ship[10];
public static void main(String[] args) {
menu();
}
public static void menu() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Choose an option: 1-3");
System.out.println("1. Dock");
System.out.println("2. Undock");
System.out.println("3. Status");
int menu = scan.nextInt();
switch (menu) {
case 1:
System.out.println("1. Dock");
dock();
break;
case 2:
System.out.println("2. Undock");
undock();
break;
case 3:
System.out.println("3. Status");
printDock();
printWaitingList();
break;
case 4:
System.out.println("4. Exit");
System.exit(0);
default:
System.out.println("No such option");
break;
}
}
}
public static void dock() {
System.out.println("Enter ship's name: ");
String name = scan.nextLine();
System.out.println("Enter ship's size: ");
String size = scan.nextLine();
System.out.println("Enter the ships dock:");
//Check if the dock number is valid
int i = Integer.valueOf(scan.nextLine());
if (i >= 0 && i < 10 && dock1[i] == null) {
int c = 0;
int co = 0;
int sco = 0;
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] != null && dock1[j].getShipSize().equals("Cargo")) {
c++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Container")) {
co++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Super-Container")) {
sco++;
}
}
if (c < 10 && co < 5 && sco < 2) {
//Add ship to the dock
dock1[i] = new Ship(name, size);
System.out.println("Enough space you can dock");
System.out.println("Ship has been docked");
} else {
System.out.println("You cannot dock");
waitingList(name,size);
}
} else {
System.out.println("Couldn't dock");
waitingList(name, size);
}
}
public static void undock() {
System.out.println("Status of ships: ");
printDock();
System.out.println("Enter ship's name to undock: ");
String name = scan.nextLine();
//System.out.println("Enter ship's size to undock: ");
// String size = scan.nextLine();
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) {
dock1[i] = null;
System.out.println("Ship removed");
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j] = null;
break;
} else {
System.out.println("No space in dock1");
return;
}
}
} else {
System.out.println("Ship not docked here");
break;
}
}
}
public static void waitingList(String name, String size){
System.out.println("Dock 1 is full, ship will try to be added to Waiting List");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) { //CHANGE TO ALLOW MORE THAN ONE SHIP
//Add ship to the dock
waitingList[i] = new Ship(name, size);
System.out.println("Enough space added to waiting list");
break;
} else {
System.out.println("No space on waiting list, ship turned away");
return;
}
}
}
public static void printDock() {
System.out.println("Docks:");
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + dock1[i].getShipName() + " " + dock1[i].getShipSize());
}
}
}
private static void printWaitingList() {
System.out.println("Waiting List:");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + waitingList[i].getShipName() + " " + waitingList[i].getShipSize());
}
}
}
}
Your loops are only working with first element of the array, becouse when check failed (for example if (waitingList[i] == null) in waitingList) you print error, and then return, thus breaking loop. What you need to do is make boolean dockSuccessful = false, then if condition is met (there is space in dock) you set it to true and then break the loop (so you woudn't dock ship multiple times). After the loop you insert
if(!dockSuccessful) {
System.out.println("Some error message here");
}
So, if loop finds at least one empty dock, dockSuccessful would be true, and error would not be printed. But if it checked all the docks, it will not update dockSuccessful, it would still be false, and error will be printed.

single dimensional array battleship code

I am beginner in java. I was trying to emulate the single dimension array battle ship code from heads first java book. The code is not failing, but I am not able to make it work properly.
Example: [1,2,3] is the array which contains the location of the battle ship. If I guess any number except 1, it is displaying as miss. But if I guess it as 1 three times (length of battleship) in a row I am making it as kill. I am not able to figure out this issue.
Could you please help me out here. The code is posted below:
package battleship;
public class battleship {
public int[] battleship = new int[3];
public int numofhits = 0;
String result = "miss";//instance variables complete
//setter method to initialize the array which holds the battle ship location
public void setbattleshiploc(int startpos) {
int i = 0;
for(i = 0; i < battleship.length; i++) {
battleship[i] = startpos + i;
System.out.println(battleship[i]);
}
System.out.println("initialized array is: " + java.util.Arrays.toString(battleship));
}
//getter method to print the set battleship array
public int[] getbattleshiploc() {
System.out.println("Battleship array is: " + battleship);
return battleship;
}
//checking whether user guess inside the battleship array location
public String guessloc(int guessnum) {
//int i = 0;
for(int cell : battleship) {
System.out.println("Guessed number is: " + guessnum + " array element: " + battleship[cell]);
System.out.println("cell: "+ cell + " ,battleship[cell]: " + battleship[cell] );
if(cell == guessnum) {
numofhits++;
if(numofhits == 3) {
result = "kill";
return result;
}//if the hits are 3 then return kill indicating that no more battle ship is available
else {
result = "hit";
return result;
}//end inner else
}//end outer if
else {
//numofhits++;
result = "miss";
return result;
}//end the if-else
}//end for loop
return "finished";
}//end function guessloc
}//end class
package battleship;
import java.util.Scanner;
public class gamelauncher {
public Scanner[] reader;
public static void main(String[] args) {
String result = "miss";
int numofguess = 0;
//int loopnum = 0;
battleship launchgame = new battleship();//launch the game
int startpos = (int) (Math.random() * 5);//generate random number between 0-4
//int[] location = {startpos, startpos + 1, startpos + 2};//initialize three consecutive array element
launchgame.setbattleshiploc(startpos);//set the array as the battleship location using setter
//display the battleship position
System.out.println("Battle shipt positions are: " + startpos +" ," + startpos+1 + " ," + startpos+2);
System.out.println("the battle ship array is: " + launchgame.getbattleshiploc());
//int[] battleshiplocation = launchgame.getbattleshiploc();
System.out.println(java.util.Arrays.toString(launchgame.getbattleshiploc()));
while(result != "kill") {
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int guess = reader.nextInt(); //get the user input integer
//reader.close();//close the scanner
//loopnum++;
numofguess++;
if(guess < 0 || guess > 7) {
System.out.println("Maximum space available is 7 units(0-6) and battleship length is 3 units, Please provide the location accordingly");
continue;
}//close if loop and go to the loop execution if the guess is not within the limits
else {
result = launchgame.guessloc(guess);
System.out.println("response from guessing method: " + result);
//get the status(hit/miss/kill) back from guess location method
if(result == "kill") {
System.out.println("We have destroyed all the parts of battle ship and it took " + numofguess +" guesses" );
break;//get out of the loop as we have destroyed everything
}//end kill
else if(result == "hit") {
System.out.println("You have destroyed " + launchgame.numofhits+" parts of batlleship, please continue");
continue;
}
else {
System.out.println("It's a miss dumbo, try again");
continue;
}
}//end outer else statement
}//end while loop
}//end main method
}//end class
I can help you by giving you this function a bit changed. Please try to fix the rest of your code on your own. It will give you important experience.
public String guessloc(int guessnum) {
for(int i=0;i<battleship.length;++i) {
if(battleship[i] == guessnum) { //it's a hit
battleship[i] = -1; //you cant hit it again, so change it
if(++numofhits == 3) {
return "kill";
}else
return "hit";
}
}
return "miss"; //miss should be outside of the for loop
}
I believe the problem is that when you are comparing Strings u are using == instead of .equals() so your code should like like this:
if(result.equals("kill"))

Hangman stats error

My code does not show the number of wins, losses and numberOfGames I had played.
I've been trying to fix it for the last month and I'm going nowhere!
import java.util.Random;
import java.util.Scanner;
public class HangmanP2 {
public static void main(String[] args) {
Scanner Input = new Scanner(System.in);
String first, reverse = "";
String second, reverse2 = "";
Scanner in = new Scanner(System.in);
System.out.println("Welcome to Hangman!");
System.out.println("Enter your first name.");
first = in.nextLine();
System.out.println("Enter your last name to play.");
second = in.nextLine();
int length = first.length();
int length2 = second.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + first.charAt(i);
reverse = reverse.substring(0,1).toUpperCase() + reverse.substring(1).toLowerCase();
for ( int i = length2 - 1 ; i >= 0 ; i-- )
reverse2 = reverse2 + second.charAt(i);
reverse2 = reverse2.substring(0,1).toUpperCase() + reverse2.substring(1).toLowerCase();
System.out.println("Your name entered in reverse is: "+reverse+" "+reverse2);
startGame(reverse,reverse2);
}
public static void startGame(String reverse,String reverse2){
Random rnd = new Random ();
Scanner user = new Scanner (System.in);
String guess = "";
String message = "";
int count = 1;
boolean quit = false;
String fullWord = "";
int wins=0;
int loss=0;
int numberOfGames=0;
int guessC = 5;
String usedLetters ="";
String remainingLetters ="";
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int hinter = 0;
int z = rnd.nextInt(10);
int k = rnd.nextInt(2);
String words[][] = {{"earth","stars","light",
"world","about","again",
"stars","light","music",
"happy","water","amber",
"apple","piano","green",
"mouth","suger","stone",
"japan","china","after","lemon",
"grand",
"lives","twice","print"},{"smile",
"puppy","latin","vegan","phone","april",
"south","house","hangs","woman",
"power","today","india","night","candy",
"forum","birth","other","chris","irish",
"paste","queen","grace","crazy","plant",
"knife","spike","darth","vader","eagle",
"egypt","range","fists","fight","glory",
"March","smart","magic","codes","rolls",
"match","honor","glass","board","teams",
"bully","zebra","under","mango","brain",
"dirty","eight","zeros","train","cycle",
"break","necks","terms","slide","large"},{"stake","guess","wrong","anime","stick","outer","input"},{ "thing","write","white","black"}};
//Prints info of the game and topic that as been selected
System.out.println("Welcome to Hangman"+" "+reverse+" "+reverse2);
//This prints the '-' and spaces for the first run of the game only
for(int index = 0; index < words[z][k].length();index++)
{
Character variableInt = words[z][k].charAt(index);
if(variableInt != ' ')
{
message += "-";
}
else
{
message += " ";
}
}
//Nothing will change, this prints information to the user about his current status in-game.
System.out.println("Secret word: \t\t" + message);
System.out.println("Letters Remaining: " + letters);
System.out.println("Letters Used: ");
System.out.println("Guesses Remaining: " + guessC);
//The loop that will continuously run the game, until the user fails or does not want to play again.
do{
//The following variable's make sure there is not stacking from previous data when the loop runs again.
remainingLetters = "";
count = 0;
//Ask the user for a letter to guess
System.out.println("\nEnter a letter to guess the word): ");
guess = user.nextLine();
//The following for-loop converts ASCII table [A-Z] to actually characters and if the player used a letter it will not show up or add to the string each run of the do-loop.
for(int x = 65; x < 91;x++){
Character current = new Character ((char)x);
String current2 = current.toString();
if(!usedLetters.contains(current2)){
remainingLetters += current;
}
}
//Converts the user's first character to a string which is converted into another character and again converted into a String (Seem's useless) but i used it this way cause i was getting an error.
Character convert = new Character (guess.charAt(0));
Character conv = new Character (convert);
String converted = convert.toString();
//The letters the player uses will be added to a string, if it has not already been added and only if it is a letter.
if(!usedLetters.contains(converted) && conv.isLetter(convert)){
usedLetters+=guess.charAt(0);
}
//Inside this for-loop it turns our word into a String and the user's first character into a string.
for(int index = 0; index < words[z][k].length();index++){
//This is a helper
count++;
//Conversion of variables
Character current2 = new Character ( words[z][k].charAt(index));
String current = current2.toString();
Character current3 = new Character (guess.charAt(0));
String current4 = current3.toString();
String current5 = current4.toUpperCase();
String current6 = words[z][k].toUpperCase();
//If the players gets a letter correct, do the following.
if(current4.equalsIgnoreCase(current))
{
//Add's on to the previous string from where the player got it correct and change it to the correct letter instead of a '-'.
message = message.substring(0,index) + guess + message.substring(index + 1);
}
//If the player gets it wrong and the helper variable is equal to 1 (so that it does not follow the loop of the for-loop and it is not one of the special characters in the game('!' or '?').
if(!current6.contains(current5) && count == 1 && guess.charAt(0) != '?' && guess.charAt(0) != '!'){
guessC--;
}
}
//Prints information to the user of their current topic
//The secret word the player has to guess
System.out.println("Secret word: \t\t" + message.toUpperCase());
//The letters in the alphabet that have not been used yet
System.out.print("\nLetters remaining: ");
System.out.print(remainingLetters.toUpperCase() + "\n\n");
//This will print a message to the user, telling them information on using a hint or the hint itself.
//Letters the user has used since the game session has been running
System.out.print("\nLetters Used: ");
System.out.print(usedLetters.toUpperCase() + "\n");
//The amount of guesses the player has left
System.out.println("\nGuesses Remaining: " +guessC );
//If the player enters a '?' it will do the following.
if(guess.charAt(0) == '?'){
if(hinter <2){
//Displays what is in the array and information about the delay, while losing guesses.
hinter++;
System.out.print("\nHint will appear after next guess! \n");
guessC -=2;
}
}
//If the user guesses the word correct
if(message.equalsIgnoreCase(words[z][k])){
System.out.println("YOU ARE CORRECT! " + words[z][k] + " is correct!");
wins++;
quit = true;
}
//If the user ask to guess the entire word it is stored in a separate variable and make quit equal to true.
if(guess.charAt(0) == '!')
{
System.out.print("\nEnter the secret word: ");
fullWord = user.nextLine();
//if the user guesses the word correct then it will tell the user they are correct and make quit equal to true.
if(fullWord.equalsIgnoreCase(words[z][k])){
System.out.println("YOU ARE CORRECT! " + words[z][k] + " is correct!");
wins++;
quit = true;
}
//If the user does not get it right it will tell the user they are wrong and make quit equal to true.
else{
System.out.println("YOU ARE INCORRECT! the word is: " + words[z][k] + " ");
loss++;
quit = true;
}
}
//If the guesses counter equal 0 then it will tell them that they have lost and make quit equal to true.
if(guessC == 0){
System.out.println("GAME OVER! The secret word was [ " + words[z][k] + " ]!");
loss++;
quit = true;
}
//This is what happens when quit eventually becomes true, the user is asked if they would like to play again.
if(quit == true){
System.out.println("\nWould you like to play again (Y or quit)? ");
System.out.println("\nOr type [stats] to check your work");
guess = user.nextLine();
//If they do want to play again, they will need to enter Y and if they do it will give them another word to guess and resets there information so that there will be no overlap.
if(guess.equalsIgnoreCase("Y")){
quit = false;
z = rnd.nextInt(10);
k = rnd.nextInt(2);
guess = " ";
guessC = 6;
message = "";
usedLetters = "";
hinter = 0;
for(int index = 0; index < words[z][k].length();index++)
{
Character variableInt = words[z][k].charAt(index);
if(variableInt != ' ')
{
message += "-";
}
else
{
message += " ";
}
}
System.out.println("Secret word: \t\t" + message);
System.out.println("Letters Remaining: " + letters);
System.out.println("Letters Used: ");
System.out.println("Guesses Remaining: " + guessC);
}
if(guess.equals("stats")){
printGameStats(wins,loss,numberOfGames);
}
else{
//If the user enters 'N' then they will be told the following and the scanner will be closed.
System.out.println("THANK YOU FOR PLAYING HAVE A GOOD DAY!");
user.close();
}
}
//end of the while loop which will only stop if quit equals true.
}while(quit != true );
}
private static void printGameStats(int wins,int loss,int numberOfGames) {
// Line
System.out.print("+");
printDashes(37);
System.out.println("+");
// Print titles
System.out.printf("| %6s | %6s | %12s |\n",
"WINS", "LOSSES", "GAMES PLAYED");
// Line
System.out.print("|");
printDashes(10);
System.out.print("+");
printDashes(10);
System.out.print("+");
printDashes(10);
System.out.print("+");
printDashes(16);
System.out.print("+");
printDashes(18);
System.out.println("|");
// Print values
System.out.printf("| %6d | %6d | %12d |\n",
wins, loss, numberOfGames);
// Line
System.out.print("+");
printDashes(37);
System.out.println("+");
}
private static void printDashes(int numberOfDashes) {
for (int i = 0; i < numberOfDashes; i++) {
System.out.print("-");
}
}
}

How to manually shuffle letters in a String

I am Writing a game/java program that needs to take a word from a .txt file, then jumble the letters up and ask the user to guess what word it is. I am having two problems:
First is that I receive this error message when I run it:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Proj4.main(Proj4.java:20)
The second problem I am having is jumbling the word. I cannot figure out how to do that without using the shuffle command (which I cannot use).
Here is my code:
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Proj4 {
public static void main(String[] args) throws IOException {
Scanner inFile = new Scanner(new File ("words.txt"));
int counter = 0;
while (inFile.hasNext()) {
inFile.nextLine();
counter++;
}
String[] word = new String[counter];
for (int j = 0; j < counter; j++) {
word[j] = inFile.nextLine();
}
int lengthList = Integer.parseInt(word[0]);
Scanner s = new Scanner(System.in);
Random randomNumber = new Random();
int i = randomNumber.nextInt(lengthList); //picks a word at random. assigns to "word"
String currentWord = word[i];//picks a word at random. assigns to "currentWord"
int turnScore = 10, finalScore = 0;
char input;
String guess ="a";
do { //do loop for whole program looping
turnScore = 10;
do { //do loop for guessing correct
do{
System.out.println("Current Puzzle: " + currentWord);
System.out.println("Current points for this word: " + turnScore);
System.out.println("Enter (g)uess, (n)ew word, (h)int, or (q)uit: ");
input = s.nextLine().charAt(0); //assigns input to first letter entered by user
Character.toLowerCase(input); //puts input to lower case
if(input != 'g' && input != 'G' && input != 'h' &&
input != 'H' && input != 'n' && input != 'N' &&
input != 'Q' && input != 'q'){
System.out.println("Invalid Entry. Please input g, n, q or h only! \n ");
}
} while (input != 'g' && input != 'G' && input != 'h' && input != 'H' &&
input != 'n' && input != 'N' && input != 'Q' && input != 'q'); //end do while loop (ask for input)
if (input == 'g') {
System.out.println("Enter Your guess: ");
guess = s.nextLine();
System.out.println("your guess is: " + guess + "\n\nThe word is: " + currentWord);
if (guess.equalsIgnoreCase(currentWord)) {
System.out.println("You Guessed Correct");
System.out.println("Your Score for this word is: " +turnScore );
finalScore = finalScore + turnScore;
}//end if guess = currentWord
else
{
if (turnScore <= 0)
{
turnScore = 0;
}//end if turn score >=0
else
{
turnScore -= 1;
}//end else turn score minus 1.
System.out.println("Nope, Sorry \n\n");
}//end else guess not = to currentWord.
}//end if user input = G.
else if (input == 'n')
{
i = randomNumber.nextInt();
currentWord = word[i];
turnScore = 10;
}//end new word if
else if (input =='h')
{
turnScore = turnScore/2;
Random ranNum = new Random();
int randomLetter = ranNum.nextInt(5);
char hint = currentWord.charAt(randomLetter);
System.out.println("the Letter at spot " + (randomLetter +1) + " is " + hint);
}//end of if input = h
else if (input == 'q')
{
finalScore = finalScore + turnScore;
System.out.println("Goodbye!");
System.out.println("Final Score: " + finalScore);
System.exit(0);
}//end else if for input = Q.
}while (!guess.equalsIgnoreCase(currentWord));
}while (input != 'q');
System.out.println("Your Final Score is: " + finalScore);
System.out.println("Goodbye!");
inFile.close();
}//End main
}//end class
Your exception is caused by these lines of code:
int counter = 0;
while (inFile.hasNext()) {
inFile.nextLine();
counter++;
}
//inFile no longer has next, will break when the for loop is entered
String[] word = new String[counter];
for (int j = 0; j < counter; j++) {
word[j] = inFile.nextLine();
}
The easy way to fix this is to redeclare the inFile and read from beginning again.
The best way to fix this is to use a dynamically sized ArrayList:
int counter = 0;
ArrayList<String> word = new ArrayList<String>();
while (inFile.hasNext()) {
word.add(inFile.nextLine());
counter++;
}
This also makes your randomizing much more easy since you can do something sneaky with it.
Here's the documentation on ArrayList.
The key, not the solution, to your second question lies add(int index, E element)
There is a way to shuffle on the fly as you read. You should figure that out, and if you get stuck, then come back.

Categories