Stuck on making an if statement for my game - java

Trying to make an if statement for a game where I give the user a scrambled word and they have to input a word made up of those scrambled letters. I have hardcoded three answers they can use. I'm stuck on trying to make an IF else statement to tell the user if they got the answer correct or to try again.
import java.util.*;
public class Scramble {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String[] wordbank = new String [10];
int answer;
wordbank[0] = "GALEE";
wordbank[1] = "OLWBE";
wordbank[2] = "RHCIA";
wordbank[3] = "RWSIT";
wordbank[4] = "NTARI";
wordbank[5] = "ETLBA";
wordbank[6] = "TIRSH";
wordbank[7] = "TLUFE";
wordbank[8] = "MIGEIN";
wordbank[9] = "RAEHT";
String[] GALEE = {"Eagle", "Gale", "Leg"};
String[] OLWBE = {"Elbow", "Below", "Lobe"};
String[] RHCIA = {"Chair", "Hair", "Air"};
String[] RWSIT = {"Wrist", "Wit", "It"};
String[] NTARI = {"Train", "Rant", "Art"};
String[] ETBLA = {"Table", "Late", "Bet"};
String[] TIRSH = {"Shirt", "Sir", "Sh"};
String[] TLUFE = {"Flute", "Felt", "let"};
String[] MIGEIN = {"Gemini", "Mini", "Gem"};
String[] RAEHT = {"Heart", "Hate", "Ear"};
System.out.println("Create a five letter word out of " + wordbank[0] + ".");
answer = s.nextInt();
if (answer) {
}

As noted in the comment by Arnaud, you should probably use next(), at least check that the value of answer is really the user input.
Once this is out of the way, you will want to check that answer is one of the three acceptable solutions.
You can use this in java 8:
boolean resultOk = Arrays.asList(GALEE).contains(answer);
if (resultOK) {
// do something
}
This will check that answer belongs to your GALEE array (so it has to be equal to either eagle, gale or leg.

You can simply iterate through GALEE to see if what they have entered is equal to one of the words in GALEE.
This is what your code should look like:
String answer = scanner.nextLine();
boolean matches = false;
for(String combination: GALEE){
if(answer.equals(combination)){
matches = true;
break
}
}
if(matches){
System.out.println("You got it correct!");
} else{
System.out.println("You got it wrong!");
}
I'd also like to note that you asked them to
Create a five letter word
but some of the words in GALEE are less than 5 letters long.

Assuming that the user types the word, you need to read it with next() instead of nextInt().
The if statement reads a boolean, that boolean in this case should come from a comparison (for example, equals as a simple solution).
if(answer.equals("Eagle")){
//do something
}
See How do I compare strings in Java? for more info
Or, for a better solution you should try to check in only one step if the answer given by the user matches some element of the array
if(Arrays.asList(GALEE).contains(answer)){
//do something
}
For this you can check How do I determine whether an array contains a particular value in Java?

Related

How to limit the number of words when reading a line from standard input?

I am new to Stackoverflow and this is my first time asking a question. I have searched my problem thoroughly, however, could not find an appropriate answer. I am sorry if this has been asked. Thank you in advance.
The question is from Hyperskill.com as follows:
Write a program that reads five words from the standard input and outputs each word in a new line.
First, you need to print all the words from the first line, then from the second (from the left to right).
Sample Input 1:
This Java course
is adaptive
Sample Output 1:
This
Java
course
is
adaptive
My trial to solve it
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
/* I have not initialized the "userInput" String.
* I know that String is immutable in Java and
* if I initialize it to an empty String ""
* and read a String from user.
* It will not overwrite to the "userInput" String.
* But create another String object to give it the value of the user input,
* and references the new String object to "userInput".
* I didn't want to waste memory like that.
*/
String userInput;
String[] userInputSplitFirstLine = new String[3];
String[] userInputSplitSecondLine = new String[2];
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine();
userInputSplitFirstLine = userInput.split("\\s+");
userInput = scan.nextLine();
userInputSplitSecondLine = userInput.split("\\s+");
for(String firstLineSplitted: userInputSplitFirstLine) {
System.out.println(firstLineSplitted);
}
for(String secondLineSplitted: userInputSplitSecondLine) {
System.out.println(secondLineSplitted);
}
scan.close();
}
}
If you try the sample input above, the output will match the sample output above. However, if you write more than 3 words to the first line and/or more than 2 words to the second line, the userInputSplitFirstLine array of size 3 will store more than 3 words. Same goes with the userInputSplitSecondLine array also. My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively? My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
Also the answer to this question suggested by Hyperskill.com is as follows:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String wordOne = scanner.next();
String wordTwo = scanner.next();
String wordThree = scanner.next();
String wordFour = scanner.next();
String wordFive = scanner.next();
System.out.println(wordOne);
System.out.println(wordTwo);
System.out.println(wordThree);
System.out.println(wordFour);
System.out.println(wordFive);
}
}
You can use next method of scanner object to read string and then it can be printed easily on new line.
while(true){
if(scanner.hasNext()){
System.out.println(scanner.next());
}
else{
break;
}
}
I think this should do the work. Don't hesitate to ask, if you have some questions.
import java.util.Scanner;
class App {
public static void main(String[] args) {
final StringBuffer line = new StringBuffer();
final StringBuffer words = new StringBuffer();
try (final Scanner sc = new Scanner(System.in)) {
while (sc.hasNextLine()) {
final String currentLine = sc.nextLine();
line.append(currentLine).append(System.lineSeparator());
for (final String word : currentLine.split("\\s+")) {
words.append(word).append(System.lineSeparator());
}
}
} finally {
System.out.println(line.toString());
System.out.println();
System.out.println(words.toString());
}
}
}
My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively?
The array here:
String[] userInputSplitFirstLine = new String[3];
is not the same one as the one you got from split:
userInputSplitFirstLine = userInput.split("\\s+");
When you do the above assignment, the old array that was in there is basically "overwritten", and now userInputSplitFirstLine refers to this new array that has a length independent of what the old array had. split always return a new array.
My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
It really depends on what you mean by "restrict". If you just want to check if there are exactly three words, and if not, exit the program, you can do this:
userInputSplitFirstLine = userInput.split("\\s+");
if (userInputSplitFirstLine.length != 3) {
System.out.println("Please enter exactly 3 words!");
return;
}
You can do something similar with the second line.
If you want the user to be unable to type more than 3 words, then that's impossible, because this is a command line app.
By the way, the code in the suggested solution works because next() returns the next "word" (or what we generally think of as a word, anyway) by default.
hope this will help you!
public class pratice1 {
public static void main (String[]args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String input1 = sc.nextLine();
char[]a =input.toCharArray();
char[]a1 = input1.toCharArray();
System.out.println(input +""+ input1);
int a2=0;
if(input!=null) {
for(int i=0;i<input.length();i++) {
if(a[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a[i]);
a2=0;
}
}
else System.out.print(a[i]);
}System.out.println("");
for(int i=0;i<input1.length();i++) {
if(a1[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a1[i]);
a2=0;
}
}
else System.out.print(a1[i]);
}
}
}
}
To solve the problem:
Write a program that reads five words from the standard input and
outputs each word in a new line.
This was my solution:
while(scanner.hasNext()){
System.out.println(scanner.next());
}

How can i turn this chatter bot into an array that scans user input

Hey so basically I have an assignment to make a simple chatter bot, the purpose of he program is to have a user input a string with a JOptionpane and then the program will search the user input the see if anything they wrote contained a key word I specified, if so they program will display a certain message. So far iv written it using if-else statements but the teacher wants us to use Arrays (which I have no idea how they work and we are just expected to know)
import javax.swing.JOptionPane;
public class ChatterBot {
public static void main(String args[]) {
String input = "";
String maths = "";
String science = "";
String chemFact = "";
String bioFact = "";
String zooFact = "";
String algFact = "";
String yes = "Well good for you";
String no = "You learn something new everyday :)";
input = JOptionPane
.showInputDialog("Pick one of the subjects listed to learn a fun fact (english, science, maths) ");
if (input.contains("science")) {
science = JOptionPane.showInputDialog(
"What kind of science fact woukd you like to know about? (chem, Biology, Zoology)");
}
else if (input.contains("maths")) {
maths = JOptionPane.showInputDialog(
"What kind of maths fact would you like to know about? (algebra, fractions, division) ");
}
if (maths.contains("algebra")) {
algFact = JOptionPane.showInputDialog(
"\"Did you know a mathematician who specializes in algebra is called an algebraist? (yes or no)\"");
}
if (algFact.contains("yes")) {
System.out.println(yes);
} else if (algFact.contains("no")) {
System.out.println(no);
}
if (science.contains("chem")) {
chemFact = JOptionPane.showInputDialog(
"Did you know If you pour a handful of salt into a full glass of water the water level will actually go down rather than overflowing the glass? (yes or no)");
}
if (chemFact.contains("yes")) {
System.out.println(yes);
} else if (chemFact.contains("no")) {
System.out.println(no);
}
else if (science.contains("biology")) {
bioFact = JOptionPane.showInputDialog("Did you know The brain itself cannot feel pain? (yes or no)");
}
if (bioFact.contains("yes")) {
System.out.println("Well good for you");
} else if (bioFact.contains("no")) {
System.out.println("You learn something new everyday :)");
}
else if (science.contains("zoology")) {
zooFact = JOptionPane
.showInputDialog("Did you know butterflies have taste receptors on their feet? (yes or no)");
}
if (zooFact.contains("yes")) {
System.out.println("Well good for you");
} else if (zooFact.contains("no")) {
System.out.println("You learn something new everyday :)");
}
if (input.contains("?")) {
System.out.println("I will be asking the questions");
}
}
There are plenty of good tutorials online about java arrays. Additionally, if your class is following a text book of any sort, then it should also have arrays covered as well. https://www.tutorialspoint.com/java/java_arrays.html
Just from a quick google.
In general an array is a data structure that holds objects in a list like function.
Generically speaking
type[] var = new type[size];
or
type[] var = {foo0, foo1, foo2...};
Real Examples
int[] intergerArray = new int[10];
String[] stringArray = {"Hello", "World"};
Indexes Generically
var = array variable
index = position of object - 1 (computers start at 0)
var[index] will return the value stored in position index from the var array
Index Examples
Make the array:
String[] stringArray = {"This", "is", "my", "first", "array"};
Access the first value:
stringArray[0];
Store the value in a variable:
String firstWord = stringArray[0];
You can even iterate through the entire array all at once:
for (int i = 0; i < stringArray.length; i++){
System.out.print(stringArray[i]);
}
Outputs:
This is my first array
For your code
I'd recommend putting your possible inputs in an array (or even in a couple of arrays)
String[] subjects = {"English", "Science", "Maths"};
You can then accept an input from the user and loop through your array to see if it matches one of your supported inputs. Also, generally you want to include a 'default' case for invalid input.
Possible Implementation
import javax.swing.JOptionPane;
public class ChatterBot{
public static void main(String[] args){
String[] subjects = {"English", "Maths", "Science"};
String userInput = JOptionPane
.showInputDialog("Pick one of the subjects listed to learn a fun fact (english, science, maths) ");
if (userInput.contains(subjects[0]){
// english facts
} else if (userInput.contains(subjects[1]){
// science facts
} else if (userInput.contains(subjects[2])){
// maths facts
}
}
}

Why is method not working as I thought it would?

I am attempting to create a hangman game. I have everything working as I want so far with the exception of one method. This method is called processGuess and takes a String letter and two String arrays as parameters. The first array is an array called spaceArray and contains Underscores that match the length of the word being guessed (example: hello produces [ _ , _ , _ , _ , _ ]). The second array is called wordArray and contains the word the user is trying to guess.
The way I envision my method working is as follows:
Create an array that stores all guessed letters (guessArray)
Create a counter that keeps track of the number of guesses (guessCounter)
Use a for loop to iterate through each letter of the word and compare it with the letter the user guessed.
a. If the letter is in the word, add the letter to the correct index of the spaceArray
Compare spaceArray to wordArray
a. If equal, print something saying they won in x number of guesses
b. If not equal.
Print spaceArray
Call the method that asks user to guess the next letter
Call this method so that the new guessed letter is processed.
The problem is that when I recall this method, it does not contain the new letter but still contains the old letter. I am unsure of what I am doing wrong. This is the first time that I have tried using methods within a method.
Here is my method:
public static void main(String[] args) throws FileNotFoundException {
Scanner file = new Scanner(
new File("C:/FilesForJava/ScrabbleDictionary.txt"));
instructions();
String[] dictionary = createDictonaryArray(file);
String[] randomWord = getRandomWord(dictionary);
String[] underscoreArray = showSpaces(randomWord);
String letter = getGuesses();
processGuess(letter, underscoreArray, randomWord);
}
public static void instructions() {
System.out.println("Let's play hangman!");
System.out.println();
}
public static String[] createDictonaryArray(Scanner inputFile)
throws FileNotFoundException {
int wordCount = 0;
while(inputFile.hasNext()) {
String word = inputFile.next();
wordCount++;
}
String[] scrabbleDictionary = new String[wordCount];
Scanner file = new Scanner(
new File("C:/FilesForJava/ScrabbleDictionary.txt"));
while(file.hasNext()) {
for(int i = 0; i < wordCount; i++) {
scrabbleDictionary[i] = file.next();
}
}
file.close();
return scrabbleDictionary;
}
public static String[] getRandomWord(String[] dict) {
String word = dict[(int)(Math.random() * dict.length)];
String[] wordArray = new String[word.length()];
for(int i = 0; i < wordArray.length; i++) {
wordArray[i] = word.trim().substring(0, 1);
word = word.trim().substring(1);
}
return wordArray;
}
public static String[] showSpaces(String[] word) {
String[] spaceArray = new String[word.length];
for(int i = 0; i < word.length; i++) {
spaceArray[i] = "_";
}
System.out.println(Arrays.toString(spaceArray));
System.out.println();
return spaceArray;
}
public static String getGuesses() {
Scanner guess = new Scanner(System.in);
System.out.println("Guess a letter: ");
String letter = guess.next();
System.out.println();
//guess.close();
return letter;
}
public static void processGuess(String letter, String[] spaceArray,
String[] wordArray) {
int guessCounter = 0;
String[] guessArray = new String[spaceArray.length];
for(int i = 0; i < spaceArray.length; i++) {
guessCounter++;
guessArray[i] = letter;
String indexLetter = wordArray[i];
if(indexLetter.equalsIgnoreCase(letter)) {
spaceArray[i] = letter;
}
}
if(spaceArray.equals(wordArray)) {
System.out.println("Yes! You won in " + guessCounter + "guesses!");
}else {
System.out.println(Arrays.toString(spaceArray));
getGuesses();
processGuess(letter, spaceArray, wordArray);
}
}
You need to pass the new guess into your processGuess method. Try something like this:
else {
System.out.println(Arrays.toString(spaceArray));
String newLetter = getGuesses();
processGuess(newLetter, spaceArray, wordArray);
}
I think this method is trying to do too much. It's strange for it to read new input and call itself recursively -- I would have expected its caller to use a loop to solicit guesses from the player and call this method (which would not recurse) instead. The method might indicate by a return value whether the user had won.
Additionally, the code seems overly complex. For instance, what's the point of guessArray, which you instantiate and initialize but never use for anything?
Furthermore, it's strange that you use arrays of Strings instead of arrays of chars, since all your Strings seem to contain a single character each. (That might actually be appropriate if you are looking to accommodate surrogate pairs, but such a consideration seems a little out of character for the level of the task.)
In any event, the reason the recursive calls to your method see only the first letter guessed is that that's what you pass to them. The getGuesses() method does nothing to modify the local letter variable (nor can it do), and the method itself just passes along whatever was passed to it.
Well, it looks like you might have a couple of problems.
First, recursion is a very poor choice for this method, I think what you're looking for is a while loop where the condition changes when the strings are equal. Using recursion here needlessly increases the size of the stack as you call more and more methods, but never return from them.
Now as to your question, in the code you gave us, the variable letter never gets changed. I assume that get guesses returns a string? If thats true then you need to set letter equal to it.
I would also like to suggest that you use a char instead of a string.
public static void processGuess(String letter, String[] spaceArray,
String[] wordArray) {
while(true) {
int guessCounter = 0;
String[] guessArray = new String[spaceArray.length];
for (int i = 0; i < spaceArray.length; i++) {
guessCounter++;
guessArray[i] = letter;
String indexLetter = wordArray[i];
if (indexLetter.equalsIgnoreCase(letter)) {
spaceArray[i] = letter;
}
}
if (spaceArray.equals(wordArray)) {
System.out.println("Yes! You won in " + guessCounter + "guesses!");
break;
} else {
System.out.println(Arrays.toString(spaceArray));
letter = getGuesses();
}
}
}
You've written the method as a recursive method (probably not the best way to do it). The issue is that when a recursive method declares a local variable, each invocation of the recursive method has its own copy of the local variables.
Thus you call processGuess, which creates a guessArray. Then processGuess calls itself again, which has its own guessArray, and after this happens a few times, you'll have a stack that looks something like:
+--------------------------------------------------------+
+ processGuess#1 +
+ local variables: guessCounter#1, guessArray#1, i#1 +
+--------------------------------------------------------+ --> calls:
+ processGuess#2 +
+ local variables: guessCounter#2, guessArray#2, i#2 +
+--------------------------------------------------------+ --> which calls:
+ processGuess#3 +
+ local variables: guessCounter#3, guessArray#3, i#3 +
+--------------------------------------------------------+ --> which calls:
+ processGuess#4 +
+ local variables: guessCounter#4, guessArray#4, i#4 +
+--------------------------------------------------------+
When processGuess#4 modifies guessArray, it changes guessArray#4. But that has no effect on guessArray#3, guessArray#2, or guessArray#1. All of these are separate local variables, and they are references that refer to four different objects. Thus, when processGuess#4, processGuess#3, and processGuess#2 all return, the changes they've made to their own guessArray's are lost, and processGuess#1 will see only the changes that it, itself, has made to its own guessArray.
As I said, I wouldn't use recursion for this particular problem. But it's definitely a problem in other cases where recursion is the right way to do things. The solutions are: (1) declare the variable or object outside the recursive method, as an instance field in the object--then they will all be accessing the same variable; or (2) add a parameter to the recursive method so that the recursive invocations can share a reference to the same object.
[Note: The #1, #2 numbers I added are just to help explain things; they aren't part of any language syntax or anything like that.]

java lexicographically sort three words

I'm new to the Java programming language and want to create a program that reads in three words using scanner class and lexicoggraphically order the three words doing this in the main method for example user enters Tom Harry Dick, answer should be Dick Harry and Tom.. I tried to use an if statement to compare the strings using java compareTo() but if statement wont return anything for me since the main method is void.
public class SortWords {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String firstWord;
String secondWord;
String thirdWord;
System.out.println("Enter three words seperated by white space");
firstWord = userInput.next();
System.out.println(firstWord);
secondWord = userInput.next();
System.out.println(secondWord);
thirdWord = userInput.next();
System.out.println(thirdWord);
}
}
Then try to read as an array elements then sort that array
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
String[] strings = new String[3];
for (int i = 0; i < strings .length; i++)
{
System.out.println("Please enter name");
strings [i] = input.next();
}
}
Arrays.sort(strings);
"I tried to use an if statement to compare the strings using java compareTo() but if statement wont return anything for me since the main method is void."
This is incorrect.
First, we do not say an if statement 'returns anything', we say that it chooses to either execute its statement block or not (the one enclosed by { }) based on whether its condition (enclosed by ( )) evaluates to true or false. (Similar idea when else and else if are thrown in)
Second, this is not effected by the return type of the method it's in, since it has nothing to do with return.
You should use print and println statements to print out the results of your comparisons of the three strings, since this is the main method and there is no higher method to return to.

Check for value in array

I need to check the array to see if the user input is already present, and display a message as to whether it is or isn't there. The first part is working, but I tried to create a method for the word check, and I'm not sure if I'm on the right path or not, cheers.
import java.util.Scanner;
public class InputLoop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
int num = array.length, i = 0;
System.out.println("Enter a word");
for (i = 0; i < num; i++) {
while (scan.hasNextInt()) // while non-integers are present...
{
scan.next(); // ...read and discard input, then prompt again
System.out.println("Bad input. Enter a word");
}
array[i] = scan.next();
WordCheck();
}
}
public void WordCheck(String[] i) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter another word");
if (scan.next().equals(array[i])) {
System.out.println("The word has been found");
} else {
System.out.println("The word has not been found");
}
}
}
Right. You've clearly gone down a bad thought process, so let's just clear the slate and have a re-think.
Step one: You want to take some user input
Step two: Compare it with all previous user inputs to see if it's present.
If it is present, return a message indicating that value has been inputted.
otherwise ignore the input and continue execution
Repeat step one.
The solution
So, let's review what you've got, and how you need to change it.
public static void main(String[] args)
If I were you, I would avoid calling methods directly from here. If you do, every method will need to be static, which is a pointless adjustment in scope for the functionality of your class. Create a new instance of your class, inside the main method, and move this code to the class' constructor. This will remove the need to make every single method static.
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
Okay, so you've created a scanner object that takes input from the System.in stream. That's a reasonable thing to do when taking input from the keyboard. You've also created an array to contain each item. If you only want the user to be able to type in 10 values, then this is fine. Personally, I would use an ArrayList, because it means you can take in as many user inputs as the user desires.
Secondly, you want a function to compare the input, with all other inputs. What you have at the moment clearly isn't working, so let's have another go at it.
You will need some input, userInput, and a collection to compare it against, allInputs.
allInputs needs to be accessible from any point in the program, so it's probably wise to make it into a field, rather than a local variable.
Then, because you're comparing userInput against all values, you're going to need a foreach loop:
for(String s : allInputs)
{
if(s.equals(userInput))
{
// Output message code.
}
}
Now the trick is fitting this inside a loop that works with this program. That is up to you.
One simple solution is to use a Set:
Set<String> words = new HashSet<String>();
Add words with the add() method and check if a word is already added with contains(word) method.
EDIT
If you must use Arrays you can keep the array sorted and do a binary search:
Arrays.sort(words);
boolean isAlreadyAdded = Arrays.binarySearch(words, newWord) >= 0;
You're going to have to loop through the entire array and check if scan.next() equals any of them - if so return true - as such:
String toCheck = scan.next();
for (String string : i) { //For each String (string) in i
if (toCheck.equals(i)) {
System.out.println("The word has been found");
return;
}
}
System.out.println("The word has not been found");
This supposes you call WordCheck(), passing the array to it - this method also has to be static for you to call it from the main() method.
You can use the arraylist.contains("name") method to check if there is a duplicate user entry.

Categories