I have designed the battleship game to only have one ship hidden and now I have to implement another ship into the game. I am new to Java and was wondering if anybody could offer me a simple way to go about this. Do I need to create another method or just adjust the display river method?
public static void displayRiver(int[] river, boolean showShip) {
System.out.println();
System.out.print("|");
for (int val : river) {
switch (val) {
case -1: // No Ship
System.out.print("x");
break;
case 0: // Unknown
System.out.print(" ");
break;
case 1: // Ship Found
System.out.print(showShip ? "Y" : " ");
break;
}//switch
System.out.print("|");
}//for
System.out.println();
System.out.println();
}//displayRiver
// main method
public static void main(String[] arg) {
int riverLength = promptForInt("Please, enter the river lenght");
int [] shipArray = new int[riverLength];
int randomBattleshipLocation = new Random().nextInt(riverLength);
shipArray[randomBattleshipLocation] = 1;
boolean showShip = false ;
int userGuess;
do
{
displayRiver (shipArray, false);
userGuess = promptForInt(String.format("Guess, enter a location from 1 to " + riverLength));
userGuess = userGuess -1;
if(shipArray[userGuess] == 1)
{
System.out.println("Boom! ");
showShip = true;
displayRiver(shipArray, true);
}
else if(shipArray[userGuess] == -1)
{
System.out.println("Location was already hit, try again! ");
}
else if(shipArray[userGuess] == 0)
{
System.out.println("Splash...");
shipArray[userGuess] = -1 ;
}
} while(!showShip);
System.exit(0);
}
}
Your logic seems to be that an 1 in the array indicates a ship, and your ships apparently are never more than one in width.
You currently use the following to create one ship
int randomBattleshipLocation = new Random().nextInt(riverLength);
shipArray[randomBattleshipLocation] = 1;
So you could turn that into a method that creates a battleship, then call that as many times as you want for multiple ships. Just make sure that you don't assign a ship on top of another ship, or make another logical error (like trying to put 5 ships into a river of size 4, and it will loop forever trying to find space for ships).
Pseudo-code and not-so-pseudo-code:
for(int i = 0;i < shipsToAdd; i++) {
addShip(shipArray);
}
// Use a shared class-level Random object, don't do new Random().nextInt();
private static Random rnd = new Random();
private static addShip(int[] array) {
// Here you should loop to check if the array is already full of ships
// otherwise it's a design flaw that will result in an infinite loop with bad input
// loop until we find a shipless array index
int index = rnd.nextInt(array);
while(array[index] == 1)
index = rnd.nextInt(array);
array[index] = 1;
}
Related
I need to write a code that "Display the complete set of unique values input after the user enters each new value." Such as:
The·complete·set·of·unique·values·entered·is:↵
Unique·Value·1:·is·100↵
Unique·Value·2:·is·10↵
Unique·Value·3:·is·20↵
I have attached my code below, and have the code completed, however, it seems to come across errors on my very last line to produce the last "this is the first time (user input) has been entered" & the unique value portion results of Unique Value # is (user input that's unique and stored in array). There seems to be an error in the very last System.out.println("Unique...) line.
Any help would be greatly appreciated.
import java.util.Scanner;
import java.util.ArrayList;
public class DisplayUniqueValueInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// creating an ArrayList from user input
ArrayList<Integer> userInputs = new ArrayList<Integer>(5);
// prompt user and store input
int count = 0;
while (true) {
int a = 0;
while(true) {
System.out.print("Enter an integer between 10 and 100:");
a = Integer.parseInt(sc.nextLine());
if (a < 10 || a > 100)
System.out.println("Invalid input\n");
else
break;
}
count++;
if (count == 5)
break;
boolean ifExists = false;
for(int i = 0; i<userInputs.size(); i++) {
if (userInputs.get(i) == a) {
ifExists = true;
break;
}
}
if (!ifExists){
System.out.printf("This is the first time %d has been entered\n", a);
userInputs.add(a);
}
} // end while statement
// output unique values
System.out.println("\nThe complete set of unique values entered is:\n");
for(int i = 0; i < 5; i++) {
System.out.println("Unique Value" + userInputs[i] + "is:" + " ");
}
} // end main method
} // end of class
A little off-topic but if you must store unique elements, you normally go for a Set. That being said, in the portion of the code where you collect the user input, you are asking for 5 numbers but storing 4 e.g.:
int count = 0;
while (true) {
int a = 0;
while(true) {
System.out.print("Enter an integer between 10 and 100:");
a = Integer.parseInt(sc.nextLine());
if (a < 10 || a > 100)
System.out.println("Invalid input\n");
else
break;
}
// count++;
// if (count == 5) if you break here, the code below won't be reached
// break; thus you will never store the last user input
// Lists have a method contains that does exactly what you are trying to do
// Consider using ifExists = userInput.contains(a)
boolean ifExists = false;
for(int i = 0; i<userInputs.size(); i++) {
if (userInputs.get(i) == a) {
ifExists = true;
break;
}
}
if (!ifExists){
System.out.printf("This is the first time %d has been entered\n", a);
userInputs.add(a);
}
// consider breaking here after you have collected the last user input
// alternatively, use a do{ ... } while(); loop
count++;
if (count == 5)
break;
} // end while statement
You are not printing the iteration variable i e.g.:
// output unique values
System.out.println("\nThe complete set of unique values entered is:\n");
for(int i = 0; i < userInputs.size(); i++) {
System.out.println("Unique Value " + (i + 1) + ": is " + userInputs.get(i));
}
Also as mentioned in another answer, in your for-loop the variable i must go up to < userInputs.size() since if you try to go up to 5, it will break if the user entered duplicate values.
For the last loop, you should do this instead, because your array is to store unique numbers, right? So if there is less than 5 unique number, your program will break, and why don't use Set instead?
// output unique values
System.out.println("\nThe complete set of unique values entered is:\n");
for(int i = 0; i < userInputs.size(); i++) {
System.out.println("Unique Value" + userInputs.get(i) + "is:" + " ");
}
Your error is because in the last for loop you try to access your list with userInputs[i] instead of userInputs.get(i)
If you want to accept and print only unique value, Perhaps use Set instead of ArrayList. Example:-
public static void main(String args[]){
Set<Integer> numbers = new HashSet<>();
for(String input : args){
Integer num = Integer.parseInt(input);
if(!(numbers.add(num))){
throw new IllegalArgumentException("Number already have");
}
System.out.println("Unique number =" + num);
}
}
A Set is a collection that contains no duplicate elements. Refer to its javadoc for details.
** Sample above just for brevity, you may retrofit your program with Set type.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
import java.util.Scanner;
import java.util.ArrayList;
public class hangman {
public static void ttt(String inputWord) {
int wordLength = inputWord.length();
String blanks = "";
for (int i = 0; i < wordLength; i++) {
blanks = blanks.concat("_ ");
}
// System.out.print(wordLength);
System.out.println(blanks);
int points = 0;
int counter = 0;
ArrayList<String> usedChars = new ArrayList<String>();
while (points < wordLength) {
Scanner reader = new Scanner(System.in);
System.out.println("Guess: ");
String guess = reader.next();
// int checker = 0;
// for(int k = 0; k < usedChars.size(); k++) {
// if(usedChars.get(k) != guess) {
// checker = checker + 1;
// }
// else {}
// }
// if(checker == usedChars.size()) {
for (int i = 0; i < wordLength; i++) {
if (guess == inputWord.substring(i, i + 1)) {
points = points + 1;
usedChars.add(guess);
System.out.println("hit"); // this is me trying to see if
// this part is working
} else {
}
}
System.out.println("Used letters: " + usedChars);
// }
// else {
// System.out.print("Sorry, that letter has already been used");
// }
counter = counter + 1;
if (counter == 5) {
points = wordLength;
}
}
System.out.println("Game over");
}
public static void main(String[] args) {
ttt("to");
}
}
Don't worry about the commented out code, that's just me going over the top trying to prevent duplicate guesses, but it's more important that I get the rest of the code to work first.
Anyway, the only part of my code that seems to be working is the counter part. You can try it yourself, but it seems like all it does it take 5 guesses (5 lives, kind of random) and print game over.
edit: in hindsight i need to revisit that counter part, because it should only increase for incorrect guesses
The first thing I noticed was that my array isn't working correctly. It's not .add()'ing like I ask it to add my guesses. (Source: https://beginnersbook.com/2013/12/java-arraylist-add-method-example/)
Then, the more serious problem of the code not even being able to record correct guesses :/
I'm starting to code in my school's java class and decided to try this on my own for fun, any help would be greatly appreciated! :P
change the following boolean expression
guess == inputWord.substring(i, i + 1)
to
guess.equals(inputWord.substring(i, i + 1))
because guess is a String object. using '==' operator will only compare the reference, not the value.
also you might want to use
String guess = reader.nextLine();
instead of
String guess = reader.next();
In the interest of learning I decided to write up a coin flipping program. The coin is an enum and i have the program return that enum value. I also have the user input from a menu style but this was helped by following along in a Barnes and Nobles book I purchased a while back.
I think I have come to a weird cross road. i was wanting to basically return the enum value and such but remove the 'menu' aspect and replace it with the ability for the user to input how many flips they would like to do and also repeat the program if they want to (so instead of pressing 1 to flip each time they can input say 20000 and it would flip that many times i also think doing this would help with a fairness check as a true test of fairness would return almost even amounts of heads and tails if it were to flip that many times then pressing 0 for no flips would end the program) and i want to prompt the user and ask if they would like to repeat.
here is the program I have written:
import java.util.*;
public class CoinTossing
{
private enum Coin { HEADS, TAILS };
private static final Random randomNumbers = new Random();
private static final int HEAD = 1;
private static final int TAIL = 2;
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
int choice;
int toss = 0;
int tosses = 0;
int frontflip = 0;
int backflip = 0;
Coin gameStatus;
System.out.println("Welcome to the Coin Toss Program.\n");
System.out.println("Choose from the menu what you want to do.");
System.out.print("1. Toss the coin\n2. Quit program\n");
choice = input.nextInt();
while ( choice != 0 )
{
if ( choice == 1 )
{
int CoinTossed = Flip();
switch ( CoinTossed )
{
//added tosses to switch statement to make the counter work perfect.
case HEAD:
gameStatus = Coin.HEADS;
tosses++; // add amount of tosses
break;
default: // changed case TAIL to default. Easy and works.
gameStatus = Coin.TAILS;
tosses++; // add amount of tosses
break;
}
if ( gameStatus == Coin.HEADS )
{
frontflip++; //Add amount of heads
}
else // gameStatus == TAILS
backflip++; //Add amount of tails
}
// A try to make an real exit out of a program
if ( choice == 2 )
{
EndProgram( frontflip, backflip, tosses );
}
System.out.println("\nChoose from the menu what you want to do.");
System.out.print("1. Toss the coin\n2. Quit program\n");
choice = input.nextInt();
}
}
//Toss the coin to determine 1 or 2.
public static int Flip()
{
int toss;
toss = 1 + randomNumbers.nextInt( 2 );
if ( toss == 1 )
{
System.out.println("You toss the coin and it lands on head!");
}
else
{
System.out.println("You toss the coin and it lands on tail!");
}
return toss;
}
public static void EndProgram( int frontflip, int backflip, int tosses )
{
System.out.printf("You have tossed %d times.\n", tosses);
System.out.printf("Of all those tosses, %d landed on heads, and %d on tails.\n", frontflip, backflip);
System.exit(0);
}
}
I think I need a do / while loop so that I can have the user answer the yes or no question of do you want to play again? and inside the loop I have a switch statement that also says if the user inputs 0 for the number of flips the program ends?
I thought I could add this snippet to get input:
System.out.println("How many flips do you want?");
System.out.println("(0 will exit the program)");
number = input.nextInt();
I was thinking of creating a new variable and have the user set the number of tosses. Then compound the while loop check like so
while(choice != 0 && numTosses !=0)
and then decrease the count and I'll have to check that count and once it reaches 0 print results as far as how many heads and how many tails then prompt the user if they would like to play the game again but I am having trouble getting the right. honestly I don't even know why I'm trying to do this if but for the knowledge aspect so if you don't wanna help a broski out I understand. I feel like I am on the right track.
You can use 2 loops:
public class CoinFlip {
private enum Coin {
HEADS,
TAILS
};
public static void main(String[] arguments) {
new CoinFlip();
}
CoinFlip() {
Scanner input = new Scanner(System.in);
int heads = 0, tails = 0;
while (true) {
System.out.println("How many flips do you want?");
System.out.println("(0 will exit the program)");
int number = input.nextInt();
if (number == 0)
break; // or System.exit
for (int i = 0; i < number; i++) {
Coin flipResult = flip();
switch (flipResult) {
case HEADS:
heads++;
break;
case TAILS:
tails++;
break;
}
}
System.out.println("Heads: " + heads);
System.out.println("Tails: " + tails);
}
}
private Coin flip() {
return Coin.values()[(int) (Math.random() * Coin.values().length)];
}
}
The while loop continues to ask the user to play again and again, if they put 0 your break it or exit it. In that loop, a for loop will iterate over the flips.
I am writing a code for Hang Man game in Java.But I cannot write a proper code or find a way to calculate users' score and printing it at the users' end command with 0:stop.Here are the score calculation rules;
Score is computed as number of letters of the word minus number of letters currently displayed.
Here “table “ score is 5-4=1 as when the user make a guess there are 4 letters already displayed.
If the user guess is not correct score is 0
If the man’s figure is completed before a guess, the score is 0
Each play of the game bu the same user is a session, the same word cannot be held by computer.
If “table” is held as a “things” it can bot be held by computer again n the same session.
When the user press 0 in the main mene, the session ends.
Toptal number of plays, how many times correctly guessed , and total score of the user is displaid to the screen.
Also,i have a problem to prevent duplicate in random selected words array
import java.util.Random;
import java.util.Scanner;
public class CEVIK_CAGATAY{
public static char[] star;
public static void main (String args[])
{
char game[];
int category;
int correct=0;
Scanner input = new Scanner(System.in);
Random r = new Random();
int totalplay=0;
int totalscore=0;
String man[] = new String[7];
man[2] = " --\n o |\n/ |\n |\n_____\n";
man[3] = " --\n o |\n/| |\n |\n_____\n";
man[4] = " --\n o |\n/|\\|\n |\n_____\n";
man[5] = " --\n o |\n/|\\|\n/ |\n_____\n";
man[6] = " --\n o |\n/|\\|\n/ \\|\n_____\n";
String arr[]={"serhat","cagatay","begum","emre","berk","ali","veli","istanbul",
"ankara","mersin","izmir","antalya","new york","samsun","kedi","kopek",
"kus","ayi","bocek","karinca","manda","masa","pencil","bag","clock","televison","book","glass"};
int arr1 []={6,7 };
System.out.println("0 To Stop,1 to Continue");
category=input.nextInt();
while(category!=0){
System.out.println("0 To STop,1 to Continue");
String word = arr[r.nextInt(arr.length)];
for(int i=0; i<arr.length;i++) {
if(arr[i]==word){
int letterlength=arr1[i];
}
//letterlength-existedlength=guessremain;
}
int count = word.length();
char[] CharArr=word.toCharArray();
char[] star = word.toCharArray();
for(int i=0;i<star.length;i++)
{
star[i] = '*';
System.out.print(star[i]);
}
for (int i=1; i<=5; i++)
{
System.out.printf ("\nGuess a Letter:");
char letter= input.next().charAt(0);
for (int j=0;j<CharArr.length; j++)
{
if(letter == star[j])
{
System.out.println("this word already exist");
}
else
{
if(letter==CharArr[j])
{
star[j]=letter;
i--;
System.out.printf("CORRECT GUESS!\n");
correct++;
}
}
}
System.out.print(star);
switch(i+0)
{
case 1: System.err.printf("Strike 1\n");
System.out.println(man[2]);
break;
case 2: System.err.printf("Strike 2\n");
System.out.println(man[3]);
break;
case 3: System.err.printf("Strike 3\n");
System.out.println(man[4]);
break;
case 4: System.err.printf("Strike 4\n");
System.out.println(man[5]);
break;
case 5: System.err.printf("Strike5\n");
System.err.printf("You're out!!! The word is Not_Matched\n");
System.out.println(man[6]);
break;
}
System.out.printf("\n");
if((new String(word)).equals(new String(star)))
{
System.err.printf("Winner Winner\n");
break;
}
}
totalplay++;
totalscore+=correct;
System.out.println("CONTINUE 1,STOP 0");
category=input.nextInt();
if(category==0) {
System.out.println(totalplay);
System.out.println(totalscore);
}
}
}
}
Get rid of the following for loop. It serves no purpose except to throw an Array Index Out of Bounds error. Your program runs without it. Be sure to practice best practices for language as well (such as camelCase for naming variables). It makes your code easier for humans to understand.
for(int i=0; i<arr.length;i++) {
if(arr[i]==word){
int letterlength=arr1[i];
}
//letterlength-existedlength=guessremain;
}
Can't figure out why my code will only return a Int when I need a String and help would be great. code below . I tried declaring variable as String with no luck.
I want to return 3 random strings: cherry, grape, bell or x
import java.util.Scanner;
import java.util.Random;
public class slot {
public static void main(String[] args)
{
String answer = "y";
int cherry;
int grape;
int bell;
int x;
Random generator = new Random(); // random generator
Scanner scan = new Scanner (System.in); // scanner class
System.out.println("Would you like to play the slot machine?(y/n): ");
answer = scan.nextLine();
while(answer.equalsIgnoreCase("y"))
{
cherry = generator.nextInt(5); // generates a random number
grape = generator.nextInt(5);
bell = generator.nextInt(5);
System.out.println("The three numbers of the slot machine are: " + cherry +grape +bell);
if(cherry == grape && grape == bell)
{
System.out.println("JACKPOT! All three of the same");
}
if(cherry == grape || cherry == bell || grape == bell )
{
System.out.println("Close, you got two of the same!!");
}
else
{
System.out.println("Not a winner");
}
System.out.print("Try again?(y/n): ");
answer = scan.nextLine();
System.out.println();
}
System.out.println("Bye!!");
}
}
I would formulate it like this:
// The different results each "wheel" / "column" on the slot machine.
String[] results = { "cherry", "bell", "grape", "x" };
// Create a random result for each wheel.
String wheel1 = results[generator.nextInt(results.length)];
String wheel2 = results[generator.nextInt(results.length)];
String wheel3 = results[generator.nextInt(results.length)];
and then continue with your if statements. (But do else if for the second and third statement).
if (wheel1 == wheel2 && wheel2 == wheel3) {
// jackpot
} else if (wheel1 == wheel2 || wheel2 == wheel3 || wheel1 == wheel3) {
// two equal
} else {
// all three different.
}
If you want to go deeper into the language, I recommend you to look into enums.
(Note that comparing strings using == is in 9 cases out of 10 a bad idea. Here however, we don't need to bother with comparing string content but can get away by comparing reference values.)
Declaring strings as ints does not make them integer values. What you need to do is make an array which contains the words you're using. Then generate a random int value which is within the scope of the array.
Then you'll pick the word from the array which is in the location specified by the random int you have.
EDIT: I'm sorry, I didn't read your whole question. Could you tell us what is getting printed?
your are printing the values of your ints. Try this: You generate a number and depending on this number you choose your String.
Random generator = new Random();
int a = generator.nextInt(5);
int b = generator.nextInt(5);
int c = generator.nextInt(5);
String roll1 = null;
switch(b){
case 1: roll1 = "cherry";
break;
case 2: roll1 = "grape";
break;
case 3: roll1 = "bell";
break;
default: roll1 = "xxx";
break;
}
//repeat for b and c with roll2 and roll3
System.out.println(roll1);