I am doing "Rock,Paper,Scissors" game and I want to check if the input matches with any arrays, for now I have this code and it works perfect:
String[] rockArray = {"Rock","rock","1"},
paperArray = {"Paper","paper","2"},
scissorsArray = {"Scissors","scissors","3"};
String[][] answersArray = {rockArray, paperArray, scissorsArray};
//Scanner
Scanner scan = new Scanner(System.in);
// Input
System.out.print("\nRock, Paper or Scissors? -> ");
String answer = scan.next();
// Checking if the input contains the right values
while(!Arrays.asList(answerRock).contains(answer) &&
!Arrays.asList(answerPaper).contains(answer) &&
!Arrays.asList(answerScissors).contains(answer)) {
System.out.print("Try again: ");
answer = scan.next();
}
But I want to make it simple and here is my idea but for some reason it doesn't work:
// Here is my arrays
String[] rockArray = {"Rock","rock","1"},
paperArray = {"Paper","paper","2"},
scissorsArray = {"Scissors","scissors","3"};
String[][] globalArray = {rockArray, paperArray, scissorsArray};
// Input
System.out.print("\nRock, Paper or Scissors? -> ");
String answer = scan.next();
//Validation
while(!Arrays.asList(globalArray).contains(answer) {
System.out.println("Try again: ");
answer = scan.next();
}
Thank you very much!
String[][] globalArray = {rockArray, paperArray, scissorsArray};
...
Arrays.asList(globalArray)
This call to Arrays.asList() will create list with 3 elements, the 3 array and not a list with the content of the arrays. When you then use contains to search for the element, you will always get false because answer will never be on of the arrays (how would it, it's a String not an array).
I suggest you do something like this:
List<String> allAnswers = Arrays.asList(rockArray);
allAnswers.addAll(Arrays.asList(paperArray));
allAnswers.addAll(Arrays.asList(scissorsArray));
...
while(!allAnswers.contains(answer)) {
...
This also saves you from calling Arrays.asList() over and over again which improves performance.
!Arrays.asList(globalArray).contains(answer) doesn't work because the Arrays.asList(...) method will output a List<String[]> not List<String>.
If you really want to use asList(...) you have to input an String[] allPossibleInputString
Your second code snippet does not work because you can't do something like this !Arrays.asList(globalArray).contains(answer).
One solution is to copy the contents of the three array into your global array like this:
String[] rockArray = {"Rock","rock","1"},
paperArray = {"Paper","paper","2"},
scissorsArray = {"Scissors","scissors","3"};
String[] globalArray = new String[9];
/* Copy Contents To Global Array */
System.arraycopy(rockArray, 0, globalArray, 0, 3);
System.arraycopy(paperArray, 0, globalArray, 3, 3);
System.arraycopy(scissorsArray, 0, globalArray, 6, 3);
Now you can do this:
while(!Arrays.asList(globalArray).contains(answer)) {
System.out.println("Try again: ");
answer = scan.nextLine();
}
Related
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());
}
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?
So i'm trying to read some user input which is then checked against two arrays of strings, then if the user input equals something in either of the arrays i want to put the user input into a new array, but when i go to print the new array which should contain the user input it prints that every value in the array is null
String[] VegiFruit = {"Apples", "Lettuce", "Broccoli"};
String[] Meats = {"Ground beef", "Hambuger"};
String[] Input = new String[20];
String[] InputGreen = new String[20];
String done = "done";
Scanner USER_IN = new Scanner(System.in);
Methods Use = new Methods(); //This is another class I have that just makes printing blank lines and borders look nicer
Use.border();
System.out.println("Enter Item name then follow instructions.");
Use.space();
for(int i = 0; i < 21; i++)
{
System.out.print(i+": ");
Input[i] = USER_IN.nextLine();
if(Arrays.asList(VegiFruit).contains(Input))
{
InputGreen[i] = Input[i];
System.out.println(InputGreen[i]); //Prints null for every value
}
}
So am I doing something wrong with the logic? or is it something else?
if(Arrays.asList(VegiFruit).contains(Input))
This line is totally wrong because you are comparing the object(Here Input is an parameter value of .contains method, it is an object) with a List of element, here element of the list is a String value.
So change the code like below,
if (Arrays.asList(VegiFruit).contains(Input[i])) {
InputGreen[i] = Input[i];
System.out.println(InputGreen[i]); //Now it is print the corresponding value.
}
How do i take a input from JOptionPane.showInputDialog, split it and add it to an Arraylist?
public static void main(String[] args) {
String acc = JOptionPane.showInputDialog("Enter a string:");
int num = Integer.parseInt(acc);
}
You can use Java's String.split() to separate a string based on a separatos.
For example if the words in the String are separated by a space then you can use:
yourString.split(" ");
This will return an String array. A more concrete example for what you want can be something like this
ArrayList<String> list = new ArrayList<String>();
String pop = "hello how are you doing";
for(String s: pop.split(" ")){
list.add(s);
}
The variable 'list' will contain:
["hello", "how", "are", "you", "doing" ]
EDIT: I read in another post that you wanted to parse it to integer first, you should put that kind of things in your question. If you can then it's better if you split the string with the above method and then parse each element as you add it to an Integer ArrayList (this if the elemenets are integers).
Please pay more attention to your posts. In the title you say LinkedList, in the text ArrayList. By the way will nobody figure out what you really want with that kind of information.
So you want to split something? You mean the string that you are getting there?
Then just look at this post!
How to split a string in Java
Then with the single values you simply add then to the list.
Example:
String acc = JOptionPane.showInputDialog("Enter a string:"); //enters yes-no
String[] result = acc.split("-");
myArrayList.add(result[0]); //yes
myArrayList.add(result[1]); //no
Component frame = new JFrame();
// get text
String name = JOptionPane.showInputDialog(frame, "What's your name?");
System.out.println(name);
// split text when u get a space
List<String> list = Arrays.asList(name.split("\\p{Z}+"));
System.out.println(list);
I am having trouble with my project because I can't get the beginning correct, which is to read a line of integers separated by a space from the user and place the values into an array.
System.out.println("Enter the elements separated by spaces: ");
String input = sc.next();
StringTokenizer strToken = new StringTokenizer(input);
int count = strToken.countTokens();
//Reads in the numbers to the array
System.out.println("Count: " + count);
int[] arr = new int[count];
for(int x = 0;x < count;x++){
arr[x] = Integer.parseInt((String)strToken.nextElement());
}
This is what I have, and it only seems to read the first element in the array because when count is initialized, it is set to 1 for some reason.
Can anyone help me? Would it be better to do this a different way?
There is only a tiny change necessary to make your code work. The error is in this line:
String input = sc.next();
As pointed out in my comment under the question, it only reads the next token of input. See the documentation.
If you replace it with
String input = sc.nextLine();
it will do what you want it to do, because nextLine() consumes the whole line of input.
String integers = "54 65 74";
List<Integer> list = new ArrayList<Integer>();
for (String s : integers.split("\\s"))
{
list.add(Integer.parseInt(s));
}
list.toArray();
This would be a easier way to do the same -
System.out.println("Enter the elements seperated by spaces: ");
String input = sc.nextLine();
String[] split = input.split("\\s+");
int[] desiredOP = new int[split.length];
int i=0;
for (String string : split) {
desiredOP[i++] = Integer.parseInt(string);
}
There are alternate ways to achieve the same. but when i tried your code, it seems to work properly.
StringTokenizer strToken = new StringTokenizer("a b c");
int count = strToken.countTokens();
System.out.println(count);
It prints count as 3. default demiliter is " "
I dont know how are you getting your input field. May be it is not returning the complete input in string format.
I think you are using java.util.Scanner for reading your input
java doc from scanner.
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. The resulting tokens may then be
converted into values of different types using the various next
methods.
Hence the input is returning just one Integer and leaving the rest unattended
Read this. Scanner#next(), You should use Scanner#nextLine() instead
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
.
.
.
StringTokenizer st = new StringTokenizer(br.readLine());
int K = Integer.parseInt(st.nextToken());
int N= Integer.parseInt(st.nextToken());