You give your guess and programm compare the result with random word from the list. If the the programm could find equal symbouls, there will be shown, if not you will see "#"-symbol. Now, I can't understand why "#" didn't dysplayed. Here is a full code.
Example:
apple – random word
apricot - answer of customer
ap############# (15 syllables, because of customer don't have to know
the lenght of word)
import java.util.Random;
import java.util.Scanner;
public class Main {
private static Scanner scan = new Scanner(System.in);
public static final int N = 30;
public static void main(String[] args) {
String ranWord;
Random rand = new Random();
String[] words = new String[N];
words[0] = "appricot";
words[1] = "orange";
words[2] = "cucumber";
words[3] = "potato";
words[4] = "tomato";
words[5] = "cherry";
words[6] = "banana";
words[7] = "carrot";
words[8] = "were";
words[10] = "very";
words[11] = "tasty";
words[12] = "as";
words[13] = "usual";
words[14] = "and";
words[15] = "fresh";
words[16] = "and";
words[17] = "tasty";
words[18] = "passed";
words[19] = "for";
words[20] = "cooking";
words[21] = "a";
words[22] = "chicken";
words[23] = "it";
words[24] = "isn't";
words[25] = "necessary";
words[26] = "cook";
words[27] = "chicken";
words[28] = "every";
words[29] = "day";
System.out.println("Try to guess the word, call Your variant?" + "\n");
ranWord = words[rand.nextInt(N)];
System.out.println("Computer guess the word: " + ranWord);
Computer computer = new Computer(ranWord);
String customWord = scan.nextLine();
Customer customer = new Customer(customWord);
boolean finish = true;
while (!finish) {
//customWord = scan.nextLine();
if (customer.word.equals(computer.ranWord)) {
System.out.println("Succsesful prompt!");
finish = true;
} else {
checkIsFinish(customWord, ranWord);
finish = false;
}
}
}
static void checkIsFinish(String customWord, String ranWord) {
int minLenghtWord = customWord.length() < ranWord.length() ? customWord.length() : ranWord.length();
for (int i = 0; i < minLenghtWord; i++) {
if (customWord.charAt(i) == ranWord.charAt(i)) {
System.out.print(ranWord.charAt(i));
} else {
System.out.print("#");
}
}
for (int i = 0; i < 15 - minLenghtWord; i++) {
System.out.print("#");
}
System.out.println(customWord.length());
}
}
It is a silly mistake you made. You never enter while because finish = true at the start.
Do this,
finish = true;
while (finish) {
//customWord = scan.nextLine();
if (customer.word.equals(computer.ranWord)) {
System.out.println("Succsesful prompt!");
} else {
checkIsFinish(customWord, ranWord);
}
finish = false;
}
Or,
finish = false;
while (!finish) {
//customWord = scan.nextLine();
if (customWord.equals(ranWord)) {
System.out.println("Succsesful prompt!");
} else {
checkIsFinish(customWord, ranWord);
}
finish = true;
}
Related
I am trying to use Linear Search using java to find the name in the 2d array and print the details related to it, but the code is directly going to last loop without searching
the code is
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Source {
String customerDetails[][]=new String[5][3];
Source()
{
customerDetails[0][0]="1001";
customerDetails[0][1]="Raj";
customerDetails[0][2]="Chennai";
customerDetails[1][0]="1008";
customerDetails[1][1]="Akshay";
customerDetails[1][0]="Pune";
customerDetails[2][0]="1002";
customerDetails[2][1]="Simrath";
customerDetails[2][2]="Amristar";
customerDetails[3][0]="1204";
customerDetails[3][1]="Gaurav";
customerDetails[3][2]="Delhi";
customerDetails[4][0]="1005";
customerDetails[4][1]="Ganesh";
customerDetails[4][2]="Chennai";
}
public static void main(String args[] ) throws Exception {
Source nc = new Source();
Scanner sc = new Scanner(System.in);
String key = sc.nextLine();
boolean found = false;
for(int i=0;i<5;i++){
for(int j=0;j<3;j++){
if(nc.customerDetails[i][j].equals(key)){
found = true;
System.out.println(nc.customerDetails[i][0] + '\n' + nc.customerDetails[i][1] + '\n' + nc.customerDetails[i][2]);
break;
}
}
if(!found){
System.out.println("No Record Found");
break;
}
}
}
}
i want to find Gaurav in the array and print
1204
Gaurav
Delhi
public class test
{
String customerDetails[][] = new String[5][3];
test()
{
customerDetails[0][0] = "1001";
customerDetails[0][1] = "Raj";
customerDetails[0][2] = "Chennai";
customerDetails[1][0] = "1008";
customerDetails[1][1] = "Akshay";
customerDetails[1][2] = "Pune";
customerDetails[2][0] = "1002";
customerDetails[2][1] = "Simrath";
customerDetails[2][2] = "Amristar";
customerDetails[3][0] = "1204";
customerDetails[3][1] = "Gaurav";
customerDetails[3][2] = "Delhi";
customerDetails[4][0] = "1005";
customerDetails[4][1] = "Ganesh";
customerDetails[4][2] = "Chennai";
}
public static void main(String args[]) throws Exception
{
test nc = new test();
Scanner sc = new Scanner(System.in);
String key = sc.nextLine();
boolean found = false;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
if (nc.customerDetails[i][j].equals(key))
{
found = true;
System.out.println(nc.customerDetails[i][0] + '\n' + nc.customerDetails[i][1] + '\n' + nc.customerDetails[i][2]);
break;
}
}
}
if (!found)
{
System.out.println("No Record Found");
// break;
}
}
}
This should work. if(!found) should be outside the loop to check all records.
Heading
Program for Java class, supposed to be the game Pass the Pigs, tried everything, but cant get the special case marked by //FIXME to execute. Below is the code i have written. Any advice welcome on where i went wrong. I know there is a way to make it shorter using a for-loop, but i need to get this program working properly before trying to get it looking sleek. Thank you.
package ch07labx;
import java.util.Random;
import java.util.Scanner;
public class PassThePigs {
//names of pieces
public static final String SIDER_NO_DOT = "Sider(no dot)";
public static final String SIDER_DOT = "Sider(dot)";
public static final String TROTTER = "Trotter";
public static final String RAZORBACK = "Razorback";
public static final String SNOUTER = "Snouter";
public static final String LEANING_JOWLER = "Leaning Jowler";
//score for piece landings
public static final int SIDER_NO_DOT_SCORE = 0;
public static final int SIDER_DOT_SCORE = 0;
public static final int TROTTER_SCORE = 5;
public static final int RAZORBACK_SCORE = 5;
public static final int SNOUTER_SCORE = 10;
public static final int LEANING_JOWLER_SCORE = 15;
//odds of landing
public static final int SIDER_NO_DOT_PROB = 33;
public static final int SIDER_DOT_PROB = 66;
public static final int TROTTER_PROB = 76;
public static final int RAZORBACK_PROB = 96;
public static final int SNOUTER_PROB = 99;
public static final int LEANING_JOWLER_PROB = 100;
private static Scanner scnr = new Scanner(System.in);
public static void main(String[] args) {
String pigRollOne = null;
String pigRollTwo = null;
int wholeTurnScore = 0;
String userInput = null;
do {
int rollScore = 0;
Random randGen = new Random();
int rollOne = randGen.nextInt(100) + 1;
int rollTwo = randGen.nextInt(100) + 1;
int rollOneScore = 0;
int rollTwoScore = 0;
//rollOne outcomes
if (rollOne <= SIDER_NO_DOT_PROB) {
pigRollOne = SIDER_NO_DOT;
rollOneScore = SIDER_NO_DOT_SCORE;
} else if (rollOne <= SIDER_DOT_PROB) {
pigRollOne = SIDER_DOT;
rollOneScore = SIDER_DOT_SCORE;
} else if (rollOne <= TROTTER_PROB) {
pigRollOne = TROTTER;
rollOneScore = TROTTER_SCORE;
} else if (rollOne <= RAZORBACK_PROB) {
pigRollOne = RAZORBACK;
rollOneScore = RAZORBACK_SCORE;
} else if (rollOne <= SNOUTER_PROB) {
pigRollOne = SNOUTER;
rollOneScore = SNOUTER_SCORE;
} else if (rollOne == LEANING_JOWLER_PROB) {
pigRollOne = LEANING_JOWLER;
rollOneScore = LEANING_JOWLER_SCORE;
}
//rollTwo outcomes
if (rollTwo <= SIDER_NO_DOT_PROB) {
pigRollTwo = SIDER_NO_DOT;
rollTwoScore = SIDER_NO_DOT_SCORE;
} else if (rollTwo <= SIDER_DOT_PROB) {
pigRollTwo = SIDER_DOT;
rollTwoScore = SIDER_DOT_SCORE;
} else if (rollTwo <= TROTTER_PROB) {
pigRollTwo = TROTTER;
rollTwoScore = TROTTER_SCORE;
} else if (rollTwo <= RAZORBACK_PROB) {
pigRollTwo = RAZORBACK;
rollTwoScore = RAZORBACK_SCORE;
} else if (rollTwo <= SNOUTER_PROB) {
pigRollTwo = SNOUTER;
rollTwoScore = SNOUTER_SCORE;
} else if (rollTwo == LEANING_JOWLER_PROB) {
pigRollTwo = LEANING_JOWLER;
rollTwoScore = LEANING_JOWLER_SCORE;
}
rollScore = rollOneScore + rollTwoScore;
//special cases
if ((pigRollOne.equals(SIDER_DOT) && pigRollTwo.equals(SIDER_NO_DOT)) ||
(pigRollOne.equals(SIDER_NO_DOT) && pigRollTwo.equals(SIDER_DOT))){
rollScore = 0;
wholeTurnScore = 0;
System.out.print("Rolling... " + pigRollOne +
" & " + pigRollTwo);
System.out.println();
System.out.print("this roll: " + rollScore);
System.out.println();
System.out.print("this turn: " + wholeTurnScore);
System.out.println();
System.out.println("Pig out!");
break;
}
if ((pigRollOne.equals(SIDER_DOT) && pigRollTwo.equals(SIDER_DOT)) ||
(pigRollOne.equals(SIDER_NO_DOT) && pigRollTwo.equals(SIDER_NO_DOT))){
rollScore = 1; //FIXME
}
if (pigRollOne.equals(pigRollTwo)) {
rollScore = 2 * (rollOneScore + rollTwoScore);
}
wholeTurnScore += rollScore;
//screen outputs
System.out.print("Rolling... " + pigRollOne +
" & " + pigRollTwo);
System.out.println();
System.out.print("this roll: " + rollScore);
System.out.println();
System.out.print("this turn: " + wholeTurnScore);
System.out.println();
System.out.print("Roll again (y/n)? ");
userInput = scnr.next();
if(userInput.charAt(0) == 'n'){
break;
}
}while (userInput.charAt(0) == 'y');
}
}
I am working with a fairly basic programming task in Java. We are asked to create a chat-robot, where the robot is to answer randomly from a set of given strings until the user writes "Bye!", where the robot will simply reply with "Bye!" and end the program. I've written the following code:
import java.util.Scanner;
import java.util.Random;
public class Robot {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random random = new Random();
String[] answer = new String[6];
answer[0] = "blabla1";
answer[1] = "blabla2";
answer[2] = "blabla3";
answer[3] = "blabla4";
answer[4] = "blabla5";
answer[5] = "blabla6";
boolean keepGoing = true;
System.out.println("Hello, how can I help you?");
while (keepGoing) {
String input = in.next();
int output = random.nextInt(6);
System.out.println(answer[output]);
if (input.equals("Bye!")){
keepGoing = false;
System.out.println("Bye!");
}
}
}
I have two issues with the program:
At times, seemingly at random, the program will answer with multiple strings.
When writing "Bye!", the program throws in another string before writing "Bye!". I do know that this may be resolved by adding "break;", but I'd consider this bad practice seeing as I am already using a boolean. (I'd like to keep using it.)
I have no idea as to why these errors occur.
Check the condition for exit before printing anything. That will resolve the 2nd issue
while (true) {
String input = in.next();
if (input.equals("Bye!")){
System.out.println("Bye!");
break;
}
int output = random.nextInt(6);
System.out.println(answer[output]);
}
Change your program like this
import java.util.Scanner;
import java.util.Random;
public class Robot {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random random = new Random();
String[] answer = new String[6];
answer[0] = "blabla1";
answer[1] = "blabla2";
answer[2] = "blabla3";
answer[3] = "blabla4";
answer[4] = "blabla5";
answer[5] = "blabla6";
boolean continue1 = true;
System.out.println("Hello, how can I help you?");
while (continue1) {
String input = in.next();
int output = random.nextInt(6);
if (input.equals("Bye!")){
continue1 = false;
System.out.println("Bye!");
}else
{
System.out.println(answer[output]);
}
}
}
}
Use below code snappet to solve Issue2:
while (keepGoing) {
String input = in.next();
int output = random.nextInt(6);
if(!input.equals("Bye!"))
System.out.println(answer[output]);
if (input.equals("Bye!")){
keepGoing = false;
System.out.println("Bye!");
}
}
Scanner in = new Scanner(System.in);
Random random = new Random();
String[] answer = new String[6];
answer[0] = "blabla1";
answer[1] = "blabla2";
answer[2] = "blabla3";
answer[3] = "blabla4";
answer[4] = "blabla5";
answer[5] = "blabla6";
boolean keepGoing = true;
System.out.println("Hello, how can I help you?");
while (keepGoing) {
String input = in.next();
if ("Bye!".equals(input)) {
keepGoing = false;
System.out.println("Bye!");
} else {
int output = random.nextInt(6);
System.out.println(answer[output]);
}
}
import java.util.Scanner;
import java.util.Random;
public class Robot
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Random random = new Random();
String[] answer = new String[6];
answer[0] = "blabla1";
answer[1] = "blabla2";
answer[2] = "blabla3";
answer[3] = "blabla4";
answer[4] = "blabla5";
answer[5] = "blabla6";
boolean keepGoing = true;
System.out.println("Hello, how can I help you?");
while (keepGoing)
{
String input = in.next();
int output = random.nextInt(6);
System.out.println(answer[output]);
if (input.equals("Bye!"))
{
keepGoing = false;
System.out.println("Bye!");
} //This bracket is the only thing missing in your code.
}// End of while loop
} // End of main method
}// End of class
I have a simple Java program that seems to work well until uploaded to my school's grading system, "WebCat", which I'm assuming is just running JUnit. The error it kicks back is:
Forked Java VM exited abnormally. Please note the time in the report does not reflect the >time until the VM exit.
I've researched this issue and and the main first troubleshooting step seems to be to look at the dump log. Unfortunately I cannot do that in this case. I am really at a loss on how to begin to troubleshoot this considering the lack of feedback from the grading system and the lack of compile or run-time errors.
Here is the code if anyone is familiar with this error or can at least give me some direction of where to begin troubleshooting. Much appreciated!
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.io.IOException;
class PlayerApp {
public static void showMenu()
{
System.out.println("Player App Menu");
System.out.println("P - Print Report");
System.out.println("A - Add Score");
System.out.println("D - Delete Score");
System.out.println("L - Find Lowest Score");
System.out.println("H - Find Highest Score");
System.out.println("Q - Quit");
}
public static void main(String[] args) throws IOException
{
if (args.length == 0)
{
System.out.println("File name was expected as a run argument.");
System.out.println("Program ending.");
System.exit(0);
}
String fileName = args[0];
Scanner sc = new Scanner(System.in);
String stnew = "";
boolean exit = false;
Player p = null;
double[] scoreList;
File dbFile = new File(fileName);
FileInputStream fis = new FileInputStream(fileName);
InputStreamReader inStream = new InputStreamReader(fis);
BufferedReader stdin = new BufferedReader(inStream);
String name = stdin.readLine();
stnew = stdin.readLine();
int numScore = Integer.parseInt(stnew);
scoreList = new double[numScore];
for (int i = 0; i < numScore; i++)
{
stnew = stdin.readLine();
scoreList[i] = Double.parseDouble(stnew);
}
p = new Player(name, numScore, scoreList);
stdin.close();
System.out.println("File read in and Player object created.");
showMenu();
while (exit == false)
{
System.out.print("\nEnter Code [P, A, D, L, H, or Q]:");
String choice = sc.nextLine().toLowerCase();
if (choice.equals("p"))
{
System.out.println(p.toString());
}
else if (choice.equals("a"))
{
System.out.print(" Score to add: ");
stnew = sc.nextLine();
double scoreIn = Double.parseDouble(stnew);
p.addScore(scoreIn);
}
else if (choice.equals("d"))
{
System.out.print(" Score to delete: ");
stnew = sc.nextLine();
double scoreIn = Double.parseDouble(stnew);
p.deleteScore(scoreIn);
System.out.println(" Score removed.");
}
else if (choice.equals("l"))
{
System.out.println(" Lowest score: " + p.findLowestScore());
}
else if (choice.equals("h"))
{
System.out.println(" Highest score: " + p.findHighestScore());
}
else if (choice.equals("q"))
{
exit = true;
}
}
}
}
break
import java.text.DecimalFormat;
public class Player {
//Variables
private String name;
private int numOfScores;
private double[] scores = new double[numOfScores];
//Constructor
public Player(String nameIn, int numOfScoresIn, double[] scoresIn) {
name = nameIn;
numOfScores = numOfScoresIn;
scores = scoresIn;
}
//Methods
public String getName() {
return name;
}
public double[] getScores() {
return scores;
}
public int getNumScores() {
return numOfScores;
}
public String toString() {
String res = "";
DecimalFormat twoDForm = new DecimalFormat("#,###.0#");
DecimalFormat twoEForm = new DecimalFormat("0.0");
res += " Player Name: " + name + "\n Scores: ";
for (int i = 0; i < numOfScores; i++)
{
res += twoDForm.format(scores[i]) + " ";
}
res += "\n Average Score: ";
res += twoEForm.format(this.computeAvgScore());
return res;
}
public void addScore(double scoreIn) {
double newScores[] = new double[numOfScores +1 ];
for (int i = 0; i < numOfScores; i++)
{
newScores[i] = scores[i];
}
scores = new double[numOfScores + 1];
for(int i = 0; i < numOfScores; i++)
{
scores[i] = newScores[i];
}
scores[numOfScores] = scoreIn;
numOfScores++;
}
public boolean deleteScore(double scoreIn) {
boolean found = false;
int index = 0;
for (int i = 0; i < numOfScores; i++)
{
if (scores[i] == scoreIn)
{
found = true;
index = i;
}
}
if (found == true)
{
double newScores[] = new double[numOfScores -1 ];
for (int i = 0; i < index; i++)
{
newScores[i] = scores[i];
}
for (int i = index + 1; i < numOfScores; i++)
{
newScores[i - 1] = scores[i];
}
scores = new double[numOfScores - 1];
numOfScores--;
for (int i = 0; i < numOfScores; i++)
{
scores[i] = newScores[i];
}
return true;
}
else
{
return false;
}
}
public void increaseScoresCapacity()
{
scores = new double[numOfScores + 1];
numOfScores++;
}
public double findLowestScore() {
double res = 100.0;
for (int i = 0; i < numOfScores; i++)
{
if (scores[i] < res)
{
res = scores[i];
}
}
return res;
}
public double findHighestScore() {
double res = 0.0;
for (int i = 0; i < numOfScores; i++)
{
if (scores[i] > res)
{
res = scores[i];
}
}
return res;
}
public double computeAvgScore() {
double res = 0.0;
if (numOfScores > 0) {
for (int i = 0; i < numOfScores; i++)
{
res += scores[i];
}
return res / (double)(numOfScores);
}
else {
//res = 0.0;
return res;
}
}
}
Your program is calling System.exit(0) for certain inputs. Don't do that! That's exactly what the message is telling you: that the JVM exited in the middle of the text, before the scoring code could finish up. Instead of calling exit(), just use return to return from main() early.
The library System Rules has a JUnit rule called ExpectedSystemExit. With this rule you are able to test code, that calls System.exit(...).
**Hello, I have to create a hangman game in java. I cant use arrays. Most of my code is done but I have been having some problems and some tips would be welcome.
I just found something else that I could use help on. After prompting the user for a new secret word and using newHangMan.setSecretWord(newWord); my disguised word does not reset to "????" (with the same number of "?" as words in the secret word).
I'm very sorry for such a long post and the bad formatting(1st time posting here).
Can anyone help?**
This is my class file:
public class HangMan
{
private String secretWord = "bigbang", disguisedWord = "";
private int guessCount = 0, missCount = 0;
public void setSecretWord(String newWord)
{
secretWord = newWord;
guessCount = 0;
missCount = 0;
int wordLength = newWord.length();
while(wordLength > 0)
{
disguisedWord = disguisedWord + "?";
wordLength--;
}
}
public String getSecretWord()
{
return secretWord;
}
public boolean isFound()
{
return secretWord.equalsIgnoreCase(disguisedWord);
}
public String getDisguisedWord()
{
return disguisedWord;
}
public int getGuessCount()
{
return guessCount;
}
public int getMissesCount()
{
return missCount;
}
public void guessCharacter(char c)
{
// int position = secretWord.indexOf(c);
boolean got_it = false;
String updateDisguised="";
for(int i=0; i < secretWord.length();i++)
{
if(c == secretWord.charAt(i))
{
updateDisguised = updateDisguised + secretWord.charAt(i);
String checkDuplicate = updateDisguised.substring(0,i);
int duplicatePos = checkDuplicate.indexOf(c);
if(duplicatePos <0)
guessCount++;
got_it = true;
}
else
{
updateDisguised = updateDisguised + disguisedWord.charAt(i);
}
}
if(got_it == false)
{
missCount++;
guessCount++;
}
disguisedWord = updateDisguised;
}
}
This is my main method:
import java.util.Scanner;
public class HangManGame {
public static void main(String[] args)
{
boolean retry= true;
String retry_ans;
Scanner kb = new Scanner(System.in);
HangMan newHangMan = new HangMan();
String word = newHangMan.getSecretWord();
String input;
char guess;
newHangMan.setSecretWord(word);
System.out.println("Hangman game starts:");
do{
System.out.println("Guess this: " + newHangMan.getDisguisedWord());
System.out.println("Enter your guess character: [guess]");
input = kb.next();
guess = input.charAt(0);
newHangMan.guessCharacter(guess);
System.out.println(newHangMan.getDisguisedWord());
System.out.println("Number of guesses so far : " + newHangMan.getGuessCount());
System.out.println("NUmber of misses so far: " + newHangMan.getMissesCount());
if((newHangMan.getMissesCount()==7) || (newHangMan.isFound()))
{
System.out.println("The game is over");
System.out.println("Would you like to try again?");
retry_ans = kb.next();
if(retry_ans.equalsIgnoreCase("yes"))
{
retry = true;
System.out.println("Please enter a new secret word:");
String newWord = kb.next();
newHangMan.setSecretWord(newWord);
}
else
{
retry =false;
}
}
} while(retry == true);
}
}
(newHangMan.isFound()=true)
should be
newHangMan.isFound()
Do not make an bool compare to another bool.
The = is evaluate the boolean.
Replace
while(retry = true);
with
while(retry);
The former is an assignment, so it never evaluates to false although it should.
Your while condition is an assignment, rather than a comparison, which is likely the cause of your problem - you're setting the value of retry to true (retry = true) rather than checking that the value of retry currently equals true (retry == true).
Classic java starter error. while check stetement should be
While(retry == true)