This is a method from my code and it's throwing me an 'unreachable statement' error when I attempt to compile it.
public static boolean whoareyou(String player)
{
boolean playerwhat;
if (player.equalsIgnoreCase("Player 1"))
{
return true;
}
else
{
return false;
}
return playerwhat;
}
The exact error is:
java:82: error: unreachable statement
return playerwhat;
^
I then attempt to use this boolean I return in the following code:
public static int questions(int diceroll, int[] scorep1)
{
String wanttocont = " ";
boolean playerwhat;
for (int i = 0; i <= 6; i++)
{
while (!wanttocont.equalsIgnoreCase("No"))
{
wanttocont = input("Do you wish to continue?");
// boolean playerwhat; wasn't sure to declare here or outside loop
if (diceroll == 1)
{
String textinput = input("What's 9+10?");
int ans1 = Integer.parseInt(textinput);
output("That's certainly an interesting answer.");
if (ans1 == 19)
{
if (playerwhat = true)
{
output("Fantastic answer player 1, that's correct!");
diceroll = dicethrow(diceroll);
scorep1[0] = scorep1[0] + diceroll;
output("Move forward " + diceroll + " squares. You are on square " + scorep1[0]);
}
else if (playerwhat = false)
{
output("Fantastic answer player 2, that's correct!");
diceroll = dicethrow(diceroll);
scorep1[1] = scorep1[1] + diceroll;
output("Move forward " + diceroll + " squares. You are on square " + scorep1[1]);
}
} // END if diceroll is 1
} // END while wanttocont
} // END for loop
} // END questions
I'm not sure if the above code is relevant to the question but I just wanted to show what I'm attempting to do with the boolean that is throwing me the error. Thank you.
return playerwhat; can never be reached, since either the if or else clause will return true or false. Therefore you should remove this statement. The playerwhat variable is not required.
BTW, your method can be replaced with a one liner method :
public static boolean whoareyou(String player)
{
return player.equalsIgnoreCase("Player 1");
}
I would rename this method to something more descriptive, such as isFirstPlayer.
EDIT :
You never call whoareyou is your questions method. You should call it :
Replace
if (playerwhat = true) // this is assigning true to that variable, not comparing it to true
with
if (whoareyou(whateverStringContainsTheCurrentPlayer)) {
..
} else {
...
}
Just update your code this way
public static boolean whoareyou(String player)
{
boolean playerwhat;
if (player.equalsIgnoreCase("Player 1"))
{
playerwhat = true;
}
else
{
playerwhat = false;
}
return playerwhat;
}
Try this:
public static boolean whoareyou(String player)
{
return player.equalsIgnoreCase("Player 1");
}
You have the issue, because:
return player what;
is never reached. You exit the your function either through the "if"- or through the "else"-part.
Related
I've been learning Java for about a week now and had a question about base cases in recursion in this palindrome code I'm writing.
Essentially when the input is any string that has the same first and last letter, the program prints that it is a palindrome (when it's not). The third if statement is the base case that's supposed to take care of stuff like this but it doesn't seem to be working and I can't tell why.
public static boolean isPalindrome (String inputted_string, int first_letter, int last_letter) {
boolean palindrome=false;
if (first_letter == last_letter) {
palindrome=true;
System.out.println(palindrome + "1"); //these are just here to help me find out which if statement is executing
return palindrome;
}
else if (first_letter > last_letter) {
palindrome=true;
System.out.println(palindrome + "2");
return palindrome;
}
else if (inputted_string.charAt(first_letter) != inputted_string.charAt(last_letter)) {
palindrome=false;
System.out.println(palindrome + "3");
return palindrome;
}
else if (inputted_string.charAt(first_letter) == inputted_string.charAt(last_letter)) {
palindrome=true;
System.out.println(palindrome + "4");
isPalindrome(inputted_string, first_letter+1, last_letter-1);
}
return palindrome;
}
You need to return the result of the last isPalindrome, now you always return true.
public static boolean isPalindrome (String inputted_string, int first_letter, int last_letter) {
if (first_letter >= last_letter) {
return true; //Checked all
} else if (inputted_string.charAt(first_letter) == inputted_string.charAt(last_letter)) {
return isPalindrome(inputted_string, first_letter+1, last_letter-1); // Maybe palindrome, check more
}
return false; // Nope, not palindrome
}
I am reading "Head First Java" book and I came across the problem in chapter 5 with the battleship game (with simple version). I knew that the book's code doesn't work and I tried my self fixing it, but it still didn't work.
So tried to google it and I found some post on this website but I still have a problem. The game isn't working properly as it should.
If a player enters any random number, the output is always "hit"...
This is the last version of the code:
DotCom class:
public class DotCom {
private ArrayList<String> locationCells = new ArrayList<>();
public void setlocationCells(int[] loc) {
if (loc != null)
for (int val : loc)
locationCells.add(String.valueOf(val));
}
public String checkYourself(String userInput) {
String result = "miss";
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
}
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = "hit";
}
System.out.println(result);
return result;
}
}
DotComGame class:
public class DotComGame {
public static void main(String[] args) {
int guessingTimes = 0;
DotCom dot = new DotCom();
GameHelperrr helper = new GameHelperrr();
int randomNum = (int) (Math.random() * 5);
int[] locations = { randomNum, randomNum + 1, randomNum + 2 };
dot.setlocationCells(locations);
boolean isAlive = true;
while (isAlive == true) {
String guess = helper.getUserInput("Enter a number");
String result = dot.checkYourself(guess);
guessingTimes++;
if (result.equals("kill")) {
isAlive = false;
System.out.println("You took " + guessingTimes + " guesses");
}
}
}
}
I would really appreciate to get a detailed and understandable answer, because I'm stuck and I couldn't move on with the book for a few days now.
int index = locationCells.indexOf(userInput);
This method will return -1 if the element doesn't exist in the collection.
So if you miss, it won't hit this condition:
if (index >= 0) {
locationCells.remove(index);
}
There are still elements in this collection because you didn't remove anything...
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = "hit";
}
So on a miss, the result still shows "hit."
Try this instead:
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = index == -1 ? "miss" : "hit";
}
If you haven't killed the opponents ships, then you either miss all ships or you hit a single ship.
I would guess the checkYourself-Method must be like this:
public String checkYourself(String userInput) {
String result = "miss";
int index = locationCells.indexOf(userInput);
if(index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "kill";
}else {
result = "hit";
}
}
System.out.println(result);
return result;
}
In it's current form the ArrayList is never empty because you insert 3 Values but only remove 1 if the user-input is in the list so .isEmpty() is never TRUE.
i got two different kind of errors in my code.
one is when someone enters a number that's higher than 8 or lower than 0.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 22
at boter_kaas_en_eiren.Board.placeAttempt(Board.java:37)
at boter_kaas_en_eiren.Game.play(Game.java:28)
at boter_kaas_en_eiren.MainClass.main(MainClass.java:12)
the other error is when a player wins and i want to close the scanner so nobody can play anymore.
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Unknown Source)
at java.util.Scanner.findWithinHorizon(Unknown Source)
at java.util.Scanner.nextLine(Unknown Source)
at boter_kaas_en_eiren.Game.play(Game.java:23)
at boter_kaas_en_eiren.MainClass.main(MainClass.java:12)
if somebody could help me i would appriciate it.
game class
package boter_kaas_en_eiren;
import java.util.Scanner;
public class Game {
private Board board;
private boolean gameFinished;
public Game() {
board = new Board();
gameFinished = false;
}
public void play() {
Scanner scan = new Scanner(System.in);
int x = 0;
String nextSymbol = "x";
board.ShowBoard();
while (gameFinished == false) {
String input = scan.nextLine();
int position = Integer.parseInt(input);
boolean highorlow = board.tohighorlow(position);
boolean succes = board.placeAttempt(position, nextSymbol);
if (highorlow) {
if (succes) {
if (nextSymbol.equals("x")) {
nextSymbol = "o";
} else {
nextSymbol = "x";
}
}
}
board.ShowBoard();
if (board.checkWinner("x") == true) {
System.out.println("x wins");
scan.close();
}
if (board.checkWinner("o") == true) {
System.out.println("x wins");
scan.close();
}
}
}
}
main class
package boter_kaas_en_eiren;
public class MainClass {
public static void main(String[] args) {
Game game = new Game();
game.play();
}
}
board class
package boter_kaas_en_eiren;
import java.util.Scanner;
public class Board {
private String[] board;
public Board() {
board = new String[9];
for (int i = 0; i < board.length; i++) {
board[i] = " ";
}
}
public void ShowBoard() {
System.out.println(board[0] + "|" + board[1] + "|" + board[2]);
System.out.println(board[3] + "|" + board[4] + "|" + board[5]);
System.out.println(board[6] + "|" + board[7] + "|" + board[8]);
System.out.println("");
}
public boolean tohighorlow(int position) {
if (position <= 8 && position >= 0) {
return true;
} else {
System.out.println("Invalid!!");
return false;
}
}
public boolean placeAttempt(int position, String symbol) {
if (board[position].equals(" ")) {
board[position] = symbol;
return true;
} else {
System.out.println("invalid!");
return false;
}
}
public boolean checkWinner(String symbol) {
if (board[0].equals(symbol) && board[1].equals(symbol) && board[2].equals(symbol)) {
return true;
} else if (board[3].equals(symbol) && board[4].equals(symbol) && board[5].equals(symbol)) {
return true;
} else if (board[6].equals(symbol) && board[7].equals(symbol) && board[8].equals(symbol)) {
return true;
} else if (board[0].equals(symbol) && board[3].equals(symbol) && board[6].equals(symbol)) {
return true;
} else if (board[1].equals(symbol) && board[4].equals(symbol) && board[7].equals(symbol)) {
return true;
} else if (board[2].equals(symbol) && board[5].equals(symbol) && board[8].equals(symbol)) {
return true;
} else if (board[0].equals(symbol) && board[4].equals(symbol) && board[8].equals(symbol)) {
return true;
} else if (board[2].equals(symbol) && board[4].equals(symbol) && board[6].equals(symbol)) {
return true;
} else {
return false;
}
}
}
If you would thoroughly check the source code lines given in the exceptions, you could probably find the issues yourself. But let's go through it together this time:
ArrayIndexOutOfBoundsException
This means you are trying to access an array element that is simply not there.
In your Game class, you have these two lines:
boolean highorlow = board.tohighorlow(position);
boolean succes = board.placeAttempt(position, nextSymbol);
Looking at tohighorlow(), we find this line:
if (position <= 8 && position >= 0) {
return true;
}
However, this will return true if the number is in the range [0..8]. In other words, the method returns true when your number is neither too high nor too low. Easiest fix is to change the condition like this:
if (position > 8 || position < 0)
Now numbers greater than 8 or lower than 0 will yield true, which seems to be what the method is supposed to do. Alternatively, you could swap the bodies of the if and else.
Regardless of that, you are ignoring the result of this method when you call placeAttempt() in your Game class. That's not good, because looking at placeAttempt() we find this line:
if (board[position].equals(" ")) { /* ... */
This is where your exception originates. You are accessing the board array without checking the position value. Or rather, you did check the position value but did not respect the result of that check here. Hence, if position is -2 or 12, for example, you will run into trouble as those elements do not exist (are out of bounds).
IllegalStateException: Scanner closed
Let's simplify the play() method of your Game class for a second:
public void play() {
Scanner scan = new Scanner(System.in);
/* ... */
while (gameFinished == false) {
String input = scan.nextLine();
/* ... */
boolean highorlow = board.tohighorlow(position);
boolean succes = board.placeAttempt(position, nextSymbol);
/* ... */
if (board.checkWinner("x") == true) {
System.out.println("x wins");
scan.close();
}
if (board.checkWinner("o") == true) {
System.out.println("x wins");
scan.close();
}
}
}
The first thing you do is to create the Scanner. Now, under certain circumstances (the two if at the end), you close the scanner. However, you do that within a loop. After you close the scanner, the loops starts over with its first line:
String input = scan.nextLine();
But you can't get the next line of a closed scanner.
Additional notes
I noticed that you are quite inconsistent in your style. For example, see these three method names: ShowBoard, placeAttempt and tohighorlow. You use different capitalization for each. I strongly suggest to stick to the recommended naming convention, which means camelCase with lower first letter: showBoard, placeAttempt and tooHighOrLow (also notice to vs too).
Hope this helps.
Your array board has the size 9. So if someone enters a number not between 0 and 8 you get an Exception.
You pass the input from the user directly to your function:
board.placeAttempt(position, nextSymbol);
There you do:
if (board[position].equals(" ")) {
So you try to access an invalid position of the array
I am trying to get my bet system to detect if the input numbers are duplicates. When you run the program, press 2 on the "for box" bet and follow instructions from there. The issue lies in the winlose duplicate and also for the non duplicate. I don't know how I am supposed to fix the issue.
Error stacktrace :
at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:966)
at java.util.LinkedList$ListItr.next(LinkedList.java:888)
at numbersgame.Test.winLoseBetDuplicate(NumbersGame.java:190)
at numbersgame.Test.checkDuplicate(NumbersGame.java:167)
at numbersgame.Test.WinLoseBox(NumbersGame.java:134)
at numbersgame.Test.getValues(NumbersGame.java:117)
at numbersgame.NumbersGame.main(NumbersGame.java:24)
C:\Users\cymmm1\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 6 seconds)
Code :
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package numbersgame;
import java.lang.reflect.Array;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JOptionPane;
/**
*
* #author cymmm1
*/
public class NumbersGame {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Test numbers = new Test();
numbers.getValues();
boolean win = numbers.win; //this checks if you won, either as a duplicate or not.
if (win) {
System.out.println("You won");
switch (numbers.bet_Type) {
case 1:
System.out.println("You waged " + numbers.bet_Amount
+ "dollars and you will get "
+ numbers.bet_Amount * 600 + " back.");
break;
case 2:
if (numbers.dupwin) {
System.out.println("You waged " + numbers.bet_Amount
+ "dollars and you will get "
+ numbers.bet_Amount * 200 + " back.");
} else {
System.out.println("You waged " + numbers.bet_Amount
+ "dollars and you will get "
+ numbers.bet_Amount * 100 + " back.");
}
break;
}
} else {
System.out.println("Sorry, you lost $" + numbers.bet_Amount + " dollars");
}
System.exit(0);
}
}
class Test {
public int bet_Type;
public int bet_Amount;
public int player_Number;
public int winning_Number;
private JOptionPane panel;
public boolean win;
public List<Integer> digits = new LinkedList<>();
List<Integer> digits2 = new LinkedList<>();
public void getValues() {
panel = new JOptionPane();
this.bet_Type = (Integer.parseInt(panel.showInputDialog("What is the bet type. 1 for straight, 2 for box")));
this.bet_Amount = (Integer.parseInt(panel.showInputDialog("How much is the bet")));
boolean bad = true;
while (bad) {
this.player_Number = (Integer.parseInt(panel.showInputDialog("What is the player's Number. 3 numbers must be inputted")));
int playerNumCopy = this.player_Number;
while (playerNumCopy > 0) {
digits.add(0, playerNumCopy % 10);
playerNumCopy = playerNumCopy / 10;
}
int lengthOfNum = digits.size();
if (lengthOfNum != 3) {
bad = true;
} else {
bad = false;
}
}
bad = true;
while (bad) {
this.winning_Number = (Integer.parseInt(panel.showInputDialog("What is the winning Number")));
int winningnumbercopy = this.winning_Number;
while (winningnumbercopy > 0) {
digits2.add(0, winningnumbercopy % 10);
winningnumbercopy = winningnumbercopy / 10;
}
int lengthOfNum = digits2.size();
if (lengthOfNum != 3) {
bad = true;
} else {
bad = false;
}
}
//========END OF CHECK FOR PROPER NUMBERS=================================
//Now to check for type of bet and se the method appropriate
if (this.bet_Type == 1) {
win = WinLoseStraight();
} else {
win = WinLoseBox();
}
}
private boolean WinLoseStraight() {
if (this.player_Number == this.winning_Number) {
return true;
} else {
return false;
}
// this goes back to getValues
}
private boolean WinLoseBox() {
//this checks for duplicates. if it isnt a duplicate then check for a box non-dup
boolean duplicatewin = checkDuplicate();
if (duplicatewin) { //you either won with a duplicate number or nonduplicate. check Duplicate does to things at once
return true;
} else {
return false;
}
}
public boolean duplicate;
public boolean dupwin;
//this checks for duplicated numbers
public boolean checkDuplicate() {
duplicate = false;
int[] array = new int[digits.size()];
int i = 0;
for (int numbers : digits) {
array[i] = numbers;
System.out.println(array[i]);
i++;
}
for (int j = 0; j < array.length; j++) {
for (int k = j + 1; k < array.length; k++) {
if (array[k] == array[j]) {
duplicate = true;
System.out.println(array[k] + " equals " + array[j]);
break; //if duplicated found, it will exit out of the for loop
}
}
if (duplicate) {
System.out.println("we found duplicate.");
dupwin = winLoseBetDuplicate(); //if it has duplicated numbers, it will check if your numbers match up
break;
} else {
dupwin = winLostBetNonDuplicate();
}
}
return dupwin; //this will return if you have won the prize with a duplicated number. goes back to getValues
}
private boolean winLoseBetDuplicate() {
/*how this method works is we make a linked list.
use a advanced for loop and when we encounter
a hit, we remove the number from it.
if there is still a number in the linkedlist of
player number it is a lose. we still have digits as a linked list. */
//
boolean won = false;
boolean match;
for (int digitsnumbers : digits) {
System.out.println("Checking the number: " + digitsnumbers);
for (int digits2numbers : digits2) {
if (digitsnumbers == digits2numbers) {
digits.remove(digits.indexOf(digitsnumbers));
digits2.remove(digits2.indexOf(digits2numbers));
System.out.println("we found a duplicated numer match. Removing from choosing. ");
System.out.println(digits);
System.out.println(digits2);
match = true;
} else {
match = false;
}
}
}
if (digits.size() > 0) {
won = false;
} else {
won = true;
}
return won;
}
private boolean winLostBetNonDuplicate() {
boolean won;
for (int digitsnumbers : digits) {
for (int digits2numbers : digits2) {
if (digitsnumbers == digits2numbers) {
digits2.remove(digits.indexOf(digits2numbers));
digits.remove(digits.indexOf(digitsnumbers));
break;
}
}
}
if (digits.size() > 0) {
won = false;
} else {
won = true;
}
return won;
}
}
I'm having a problem calling a method and then trapping its return.
I need it to update the result so the next time round the loop it will see it and return a different message.
public class Patient {
private char patientStatus;
public boolean admit() {
if (patientStatus != 'S')
return false;
else
patientStatus = 'A';
return true;
}
This section is in the main() method
do {
Patient temp = null;
System.out.print("Enter selection: ");
menuSelect = sc.nextLine();
// validation
if (menuSelect.length() != 1) {
System.out.println("You must enter a single character");
} else {
menuAnswer = menuSelect.charAt(0);
switch (menuAnswer) {
case 'A':
case 'a':
// patient number
System.out.print("Enter patient number: ");
patNumber = sc.nextLine();
// search for patient number
for (int i = 0; i < pat.length && temp == null; i++) {
if (pat[i].getPatientNo().equals(patNumber)) {
temp = pat[i];
}
}
if (temp == null) {
System.out.println("Patient not found");
} else {
System.out.println("Patient " + patNumber + " Found");
boolean patStatus = temp.admit();
if (patStatus == false) {
System.out.println("Admitted");
} else if (patStatus == true) {
System.out.println("Already admitted");
}
}
}
}
} while (menuAnswer != 'x' && menuAnswer != 'X');
System.out.println("Exiting menu");
I don't know how to update the patStatus so the next time in the menu if you select 'A' and the same patient number it returns "Already admitted".
Let me know if there's enough code to understand what's happening.
Your Patient has the atribute for patientStatus but its value is never saved. Your admit() method needs to set the value for it.
Currently, your code only returns the value but does not save it.
Try this:
public class Patient {
private char patientStatus;
/** "Getter" method for patientStatus
*/
public char getPatientStatus(){
return patientStatus;
}
/** "Admits" the new patient, changing its patientStatus
* #return "true" if patient is admitted; "false" if patient was already admitted.
*/
public boolean admit() {
if (patientStatus != 'A')
patientStatus = 'A'; //set the value to Admitted
return true;
else
return false;
}
}
Then, in your loop, test the value for the admit() call:
if (temp == null) {
System.out.println("Patient not found");
} else {
System.out.println("Patient " + patNumber + " Found");
boolean admitted = temp.admit(); // try to admit the patient
if (admitted) {
System.out.println("Admitted");
} else { //You don't need another if here
System.out.println("Already admitted");
}
}
Since admitted is of type boolean, you don't need to use the == operator, as the if statement uses a boolean value as argument.
You don't need a second if statement after the else either, since boolean can only have two values, if it is not true, then it can only be false
/* You have to re-factor the code on these lines.
Maintain Patients class which holds admitted patients.*/
public class Patients{
private ConcurrentHashMap<Integer, Patient> allPatients = new ConcurrentHashMap();
private HashSet<Integer) admittedPatients = new HashSet();
public Patients(){
}
public void add(Patient p){
allPatients.put(p.getPatientId(),p);
}
public Patient removePatient(int patientId){
dischargePatients.remove(patientId);
return allPatients.remove(patientId);
}
public Patient getPatient(int patientId){
return allPatients.get(patientId);
}
public void admitPatient(int patientId){
admittedPatients.add(patientId);
}
public boolean dischargePatient(int patientId){
return admittedPatients.remove(patientId);
}
public boolean isAdmittedPatient(int patientId){
return admittedPatients.contains(patentId);
}
}
From `Patient.java` class, you can admit & discharge patient.
If getPatient() is null implies patient is not present in list.
Once he is present, isAdmittedPatient returns whether
he is admitted or not.