Simple bulls and cows java game [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I try to create a verry simple Bulls and Cows game (https://en.wikipedia.org/wiki/Bulls_and_Cows). The game is for my school project. My knowledge is limited, so I need to make the game using only loops, IF-else constructions and other simple functions.
The written code works somewhat - generate code and understands that number is hited, but did not indicate how many cows and bulls have in the wrong assumptions.
I would be glad if someone point me in the right direction :) Thanks in advance
import java.util.Random;
import java.util.Scanner;
public class BCgame{
public static void main(String[] args){
Random r= new Random();
int number= 0;
int trynum = 0;
while(uniq(number= (r.nextInt(9000) + 1000)));
String targetStr = number +"";
boolean game = true;
Scanner input = new Scanner(System.in);
do{
System.out.println(number);
int bulls = 0;
int cows = 0;
System.out.print("Guess a number: ");
int guess;
guess = input.nextInt();
if (uniq(guess) || guess < 1000) continue;
trynum++;
String guessStr = guess + "";
for(int i= 0;i < 4;i++){
if(guessStr.charAt(i) == targetStr.charAt(i)){
bulls++;
}else if(targetStr.contains(guessStr.charAt(i)+"")){
cows++;
}
}
if(bulls == 4){
game = false;
}else{
System.out.println(cows+" Cows and "+bulls+" Bulls.");
}
}while(game);
System.out.println("You won after "+trynum+" guesses!");
}
public static boolean uniq(int num){
String checknum = num+"";
if(checknum.charAt(0) == checknum.charAt(1)) return false;
else if(checknum.charAt(1) == checknum.charAt(2)) return false;
else if(checknum.charAt(2) == checknum.charAt(3)) return false;
return true;
};
}

You've already gone a long way towards the solution using the Rosetta example (http://rosettacode.org/wiki/Bulls_and_cows#Java). Just continue to work through it.
Experimentation is key to learning a language well, so make sure you understand what each line is doing and test the results.
Also, learn how to use your debugging tools to see which lines are behaving differently to what you expect, and then try and understand why.
If you get stuck on a specific statement then post that. Otherwise, this question is too unspecific, especially when Rosetta has a working example for you.

Related

How do I fix the unreachable statement? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I tried reading about this and I can't find the real problem. I'm new to java and it's my first time that I've encountered this problem. I tried putting the counter inside main method and outside of it and it still says unreachable statement.
Here is my code:
import java.util.Random;
import java.util.Scanner;
public class Harrylist{
static Random Userinput = new Random();
static Scanner input = new Scanner(System.in);
static String cancellor;
static int counter = 0;
static int integer = 0;
public static void main(String[] args) {
System.out.println("Guessing game! please enter a total number of guesses");
int y = input.nextInt();
int[][] GuessingGame = new int[2][];
GuessingGame[0] = new int[y];
GuessingGame[1] = new int[y];
//AI inputs
for(int i = integer; i < y; i++){
GuessingGame[1][i] = Userinput.nextInt(50);
//System.out.println(GuessingGame[1][i]);
//User inputs
System.out.println("Please enter a number within the range of 50");
cancellor = input.nextLine();
GuessingGame[0][i] = input.nextInt();
for(int j = 0; j<y; j++){
if(GuessingGame[0][integer] == GuessingGame[1][j]){
System.out.println("Correct!");
break;
counter++;
}
You cannot put anything after break statement because it break your loop. counter++ will never be reached. Use this:
counter++;
break;
instead this:
break;
counter++;
the break keyword causes your code to interrupt and exit out of the loop. Therefore everything insite of the if(GuessingGame[0][integer] == GuessingGame[1][j]) condition and after the break will not be reached. To fix this you just need to make sure that the break statement is the last thing in its block of code.

Hackerrank says my output is wrong even though the output matches perfectly [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am doing an assignment on Hackerrank for Java where I had to perform some mathematical operations with scanner data. I ran the code with two samples and I got a 100% match with the expected output (see picture) but somehow Hackerrank still says there is no match. Is it possible that you print something and it looks the same but it is recognized as something different? I already tried to write the code in a different way so the result would be picked up correctly, by using System.out.println but this was to no avail.
import java.util.*;
import java.io.*;
class Solution {
public static void main(String []argh) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
String jj = "";
for (int i = 0; i < t; i++) {
int a = in.nextInt();
int b = in.nextInt();
int n = in.nextInt();
String hh = "";
for(int k=1;k<n+1;k++){
long oo = a ;
for (double o = 0; o < k; o++) {
oo = oo + b * (long) Math.pow(2, o);
}
hh = hh + " " + oo;
}
if (i > 0) {
System.out.print("\n");
}
System.out.print(hh);
}
in.close();
}
}
image of Hackerrank result
Since there's no picture included to compare your code to output and/or expected output, I can only guess, but might be that System.out.print("\n"); is not visible in html output, but is still picked up by the validation algorythm, and if lets say 5 is expected \n5 would obviously be wrong, even if the \n whitespace part is invisible

Creating a loop to check array (java)

Homework assignment Suggestions only please as I wish very much to learn this as second nature!
The goal is to create an array with a user specified question amount (array size) followed by an answer key (said array size now filled). Then to have the user input the "students" answers to check against key.
I wrote all that no worries. Works lovely. The issue I am having is in two areas:
Create a loop that asks to grade another quiz.
Have it only check/score/calculate every other answer. ie: even answers only.
I have used a do/while loop to continue checking but couldn't get a sentinel value to stick. Also depending on where I placed it, the answers kept coming up as the first check. So I am unsure as to where to place and how to write it. I even tried to use a for loop boxing in the array and student answer portion to no avail.
As regards to having it check every other one, I thought of modifying the count of "i" to something like ((i+1)*2) instead of i++ for the two for loops but I just get errors as that seems to not be proper at all.
Thank you in advance!
import java.util.Scanner;
import java.text.NumberFormat;
public class EvenQuizzes {
public static void main(String[] args) {
int quizQuest = 0, count = 0;
double percentTotal = 0.0;
Scanner scan = new Scanner(System.in);
System.out.print("How many questions are in the quiz? Or enter 0 to quit. ");
quizQuest = scan.nextInt();
int[] answers = new int[quizQuest]; // scan in question total and apply
// to array
System.out.println("Enter the answer key: ");
for (int i = 0; i < answers.length; i++) {
answers[i] = scan.nextInt();
}
for (int i = 0; i < answers.length; i++) {
System.out.println("Enter the answer to be graded : ");
int toGrade = scan.nextInt();
if (toGrade == answers[i]) {
count++;
}
}
percentTotal = ((double) count / quizQuest);
NumberFormat defaultFormat = NumberFormat.getPercentInstance();
defaultFormat.setMinimumFractionDigits(2);
System.out.println("The questions answered correctly total: " + count);
System.out.println("The percentage correct is: " + defaultFormat.format(percentTotal));
System.out.println("\nAnother quiz to be graded?");
}
}
// do ( quizQuest != 0){ //condition check to run new quiz against KEY
// for (int j = 0; (quizQuest = scan.nextInt()) != 0; j++); {
At the bottom is what I had considered for the loop portion I am having trouble with.
As you asked for hints (and not the code), here it is:
For more than one quizzes, use do-while, as follows:
do{
//do something
//scan the value of quiz quest
//do something
}while(quizquest != 0)
Now, if only answers at even positions are to be checked, do following:
for (int i =0; i <answers.length; i++)
{
System.out.println("Enter the answer to be graded : ");
int toGrade = scan.nextInt();
if(i % 2 == 0 && toGrade == answers[i]){
count++ ;
}
}
Create a loop that asks to grade another quiz: You could use a do-while loop with a boolean indicating if the user (teacher?) wants to grade another quiz:
do{
boolean continue = false;
// check if the user wants to continue
while(continue);
Have it only check/score/calculate every other answer. ie: even answers only: You can check for even answers with the modulo operator:
if(i % 2 == 0){
// even answer
}
Hope this helps!
You should have a variable, perhaps named continue, whose default value is 'Y'. At the very beginning, create a while loop that checks the condition continue==Y, and at the end when you ask "Another quiz to be graded?", read in the input to the variable continue.

StringBuilder not printing its value? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm a noob to java, so I'm sorry if this is a simple question.
I always found it interesting that you could condense a number into a single digit by adding its digits together. Thus, I decided to try to make a program to do it for me! Here's an example.
Input: 557
5 + 5 + 7 = 17
1 + 7 = 8
Answer: 8
See! This obviously would work with any number. But, my program is terminating with no output. Can anyone help me out? I'm not so used to tringBuilder, so I think that might be the issue.
import java.util.Scanner;
import java.lang.StringBuilder;
public class MagicNumberApp
{
public static void main (String [] args)
{
int number;
String numberstring;
boolean keepGoing = false;
Scanner input = new Scanner(System.in);
StringBuilder builder = new StringBuilder();
sopl("Welcome to Magic Number! \nThe idea is to add the idividual digits of a number "
+ "\nuntil it is condensed into a one digit number.\n\nInput a number...");
sop(">");
number = input.nextInt();
numberstring = Integer.toString(number);
if (numberstring.length() < 1)
keepGoing = true;
sopl("");
number = 0;
while (keepGoing)
{
for (int i = 0; i < numberstring.length(); i++)
{
number += Character.getNumericValue(numberstring.charAt(i));
builder.append("+" + numberstring.charAt(i) + " ");
}
builder.append("=" + number);
sopl(builder);
if (numberstring.length() > 1)
{
numberstring = Integer.toString(number);
number = 0;
sopl("");
}
else
{
keepGoing = false;
}
}
}
public static void sop (Object o)
{
System.out.print(o);
}
public static void sopl (Object o)
{
System.out.println(o);
}
}
Your keepGoing logic is backwards. You are setting keepGoing to true is the inputted number is less than 1 digit and you initialized it to false.
if (numberstring.length() < 1)
keepGoing = false;
All numbers have at least one digit, even 0, so there is no need for the above test before the while loop. Remove it. But you must initialize keepGoing to true.
I believe the problem lies in this line:
if (numberstring.length() < 1)
keepGoing = true;
Right now it is saying that keepGoing will only be true if numberstring has a length of 0. You can change it to something like this:
if (numberstring.length() > 1)
keepGoing = true;
Edit: I have an additional suggestion. You can add an else statement to print a message if the user input does has one digit:
else
sopl(number + " only has one digit. Try again!");
In addition to all the answers. I recommend you read your input as String and save yourself the initial conversion to string.
numberstring = input.nextLine();

Coding for the first time (Java hangman game)- going from console-based to GUI

I am completely new to programming and I have to complete some tasks in Java (I'm using Eclipse). This one is a hangman game. My code is below. I have written a console-based program that basically works (counting lives instead of drawing a hangman graphic).
I think this question will seem very simple to most people, but I would really appreciate your help.
I am trying my best to look for answers online, but as a complete novice it is hard to know where to start. I would really just like to know if I am on the right track so that I don't waste too much time.
I am supposed to (and want to!) do this myself, so ideally I would like hints on what to focus on.
The questions I have are:
I now need to create a GUI (which I have never done before):
how useful is this code that I have already worked out? Is everything completely different once I start creating the game with a GUI?
I used a StringBuffer to store the previously guessed letters. I
wanted to search this in order to display the word with all the
previously guessed letters filled in (as it stands it only prints
out the current guess with all the other letters obscured). Is that
possible?
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
StringBuffer buffer = new StringBuffer();
String secretWord;
int secretWordLength;
int position;
int livesLost = 0;
int totalLives = 10;
int lettersRemaining;
boolean guessInWord;
char guess;
StringBuffer prevGuessedLetters;
//prompt user to enter a word and set as an instance of the secretWord variable
System.out.println("Enter a word:");
secretWord = myScanner.next();
//determine the length of the word entered
secretWordLength = secretWord.length();
System.out.println(secretWordLength);
lettersRemaining = secretWordLength;
for (position = 0; position < secretWordLength; position++) {
System.out.print("*");
}
System.out.println();
//loop starts
while (lettersRemaining > 0 && livesLost < 10) {
//prompt user to guess a letter
System.out.println("Guess a letter:");
guess = myScanner.findWithinHorizon(".", 0).charAt(0);
//check if the letter guessed is in the secretWord
guessInWord = (secretWord.indexOf(guess)) != -1;
if (guessInWord == false) {
livesLost++;
System.out.print("Sorry, you have lost a life. You still have ");
System.out.print(totalLives -= livesLost);
System.out.println(" life/lives left. Keep trying.");
} else {
System.out.println("That was a good guess, well done!");
for (position = 0; position < secretWordLength; position++) {
if (secretWord.charAt(position) == guess) {
System.out.print(guess);
lettersRemaining--;
} else {
System.out.print("*");
}
}
}
System.out.println();
prevGuessedLetters = buffer.append(guess);
System.out.print("Previously guessed letters: ");
System.out.println(prevGuessedLetters);
System.out.print("Letters remaining: ");
System.out.println(lettersRemaining);
}
if (livesLost == totalLives) {
System.out.println("Sorry, you lose!");
} else {
System.out.print("Well done, you win! The word was ");
System.out.println(secretWord);
}
}
Java comes with a GUI toolkit called Swing, which you should learn to use for the purposes of your task at hand.
As far as searching for previously guessed letters, you may be better served by the Set, which is a Collection of unique elements. You could use a Set of Characters, i.e. a Set<Character>.
A crude example:
Set<Character> guesses = new HashSet<Character>();
Character guess;
// etc.
while (lettersRemaining > 0 && livesLost < 10)
{
//prompt user to guess a letter
System.out.println("Guess a letter:");
guess = myScanner.findWithinHorizon(".",0).charAt(0);
if (guesses.contains(guess)) {
System.out.println("You have already guessed this character!");
} else {
guesses.add(guess);
//check if the letter guessed is in the secretWord
guessInWord = (secretWord.indexOf(guess))!= -1;
// etc.
}
}
Actually, you can get some extra mileage out of the add method by taking advantage of the fact that it returns true if the element was not already in the set:
if (guesses.add(guess)) {
//check if the letter guessed is in the secretWord
guessInWord = (secretWord.indexOf(guess))!= -1;
// etc.
} else {
System.out.println("You have already guessed this character!");
}
Well, for your first question:
-Your code it's useful to your goal, so keep it up. Search about Swing library which it's a graphical lib for java, it will let you make a GUI without so much hard work.
About your second question:
-Right now i can't help you with it but it's not so hard so keep looking for it.
By adding a GUI, your application will be longer and more structurally complex. It might not be a good idea to have all the code in 1 main method like your current program. So you might want to re-arrange your code into several different methods (also called procedures/sub-routines in other languages). This technique is call procedural programming which is intended to make your coding life easier.
That being told, your code is not completely wasted when switching to GUI. The game logic remains the same. Nothing changes except the way the program interacts with users. This time, you receives guesses and outputs answers using Swing objects like JTextField (Swing is the default graphic library of Java. There's a lot out there but it's a good start). You'll also want to look at JPanel and JFrame (ways of telling the graphic window where exactly you want to put your stuff - so called layout).
StringBuffer is just a modifiable version of String. To perform searching/read through operations, try an array-like data structure. Here I use ArrayList which is the very basic data structure in Java:
ArrayList<String> buffer;
boolean addGuess(String inputString){
boolean isNewGuess = true;
for (String s: buffer){
if (s.equals(inputString)){
isNewGuess = false;
break;
}
}
if (isNewGuess) buffer.add(inputString);
return isNewGuess;
}
using Hang-Man Game simple logic
optional this is package name
package arr_game;
import java.util.Random;
import java.util.Scanner;
public class HangMan {
public static char[] star;
public static void main (String args[])
{
char game[];
Scanner input = new Scanner(System.in);
Random r = new Random();
String[] arr = { "pakistan", "india", "jarmany", "america", "rashia", "iran", "iraq", "japan", "sudan", "canada"};
String word = arr[r.nextInt(arr.length)];
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<=3; 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");
}
}
}
System.out.print(star);
switch(i+0)
{
case 1: System.err.printf("Strike 1\n");
break;
case 2: System.err.printf("Strike 2\n");
break;
case 3: System.err.printf("Strike 3\n");
System.err.printf("You're out!!! The word is Not_Matched\n");
break;
}
System.out.printf("\n");
if((new String(word)).equals(new String(star)))
{
System.err.printf("Winner Winner, Chicken Dinner!\n");
break;
}
}
}
}

Categories

Resources