Array Response Output - java

So I'm working on a little fun project that'll ask you a series of questions, and depending on what you respond with, give a specific output. Well, I've gotten all the way to the first output answer, but I can't figure out what to do.
Here's the source code. I can't seem to get the code input into the question correctly.
import java.util.Scanner;
public class Questionaire {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String answers[] = new String[1];
String response[] = new String[5];
System.out.println (" Good Evening, Devin. How are you today? ");
answers [0] = in.nextLine();
response [0] = "I'm good";
response [1] = "I'm okay";
response [2] = "I'm alright";
response [3] = "I'm great";
response [4] = "good";
if (answers[0].equals (response.length)) {
System.out.println (" That's awesome! What would you like to talk about?" );
}
else {
System.out.println( " Oh, well then.." );
}
}
}
OUTPUT:
Good Evening, Devin. How are you today?
I'm okay
Oh, well then..
Basically, I'm trying to get the if statement to take the whatever the user inputs into the answer[0] array, and if they respond with any of the responses in the response array, they get the first system.out, but whenever I type in any of them, I keep getting the else output. Can anyone tell me what I'm doing wrong?

You want to find the match of the user input from response array.
if (answers[0].equals (response.length)) will never evaluate to true unless the user input is 5 because you are comparing user input with response.length which value is 5. You need to loop from each element in response
or simply change
if (answers[0].equals (response.length))
to
if(Arrays.asList(response).contains(answer[0]))
you will need to add import java.util.Arrays

answers[0].equals (response.length)
This code will be false as answer[0] is string matching with response.length which is 5. if you want to check the answer with the response exist then code need to be modify as below
Boolean checkresponse=false;
for(int i=0;i<response.length;i++){
if (answers[0].equalsIgnoreCase(response[i])) {
System.out.println (" That's awesome! What would you like to talk about?" );
checkresponse=true;
break;
}
}
if(checkresponse==false)
System.out.println( " Oh, well then.." );

Related

Stuck on making an if statement for my game

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?

ArrayList with if statements

I am tasked with creating a simple Turing Test using ArrayLists. I know how to create the ArrayLists, but I'm having trouble connecting them to the if statements to respond properly to the user input. An example of this issue is below. When the user inputs Frank I want the first response, and any other input should result in the other response. However, whatever tweaks I make just make one or the other show up no matter what I input.
List<String> names = new ArrayList<>();
names.add( "Frank" );
System.out.print( "Hello, what is your name? ");
names.add(scanner.next());
if( names.contains( "Frank" )) {
System.out.printf( "Nice to meet you, Frank. My name is John.\n" );
}
else {
System.out.printf( "What an interesting name. My name is John.\n");
}
**Having another issue. For the second question I'm trying to use an else if statement. However, when I respond with the else if response, it gives me the final else response of "I would have never guessed" every time.
System.out.print("Where are you from? ");
states.add(scanner.next());
if (states.contains("Florida") || states.contains("florida")) {
System.out.println("So was I!\n");
} else {
if (states.contains("North Carolina") || states.contains("north carolina")) {
System.out.println("I hear that's a nice place to live.\n");
}
else {
System.out.println("I would have never guessed!");
}
}
Try the following:
List<String> names = new ArrayList<>();
System.out.print( "Hello, what is your name? ");
names.add(scanner.next());
if(names.contains( "Frank" )){
System.out.printf( "Nice to meet you, Frank. My name is John.\n" );
}else{
System.out.printf( "What an interesting name. My name is John.\n");
}
I removed the part where you add Frank to the array. This way the results might be a little different depending on your input. I still find it a little strange that you are using an ArrayList. It seems like just saving a simple variable could do the same thing.
With an ArrayList it is possible however that you could have previous answers affect other answers.

Int and String array in Java

public class CHECK {
public CHECK(){
String []wrkrs = {"Денис", "Саша", "Наталья", "Анатолий", "Юра", "Коля", "Катя", "Дима", "Антон","Тамара"};
int [] wrkrsPhone = {22626,22627,22628,22629,22630,22631,22632,22633,22634,22635};
String a = JOptionPane.showInputDialog(null, "Hello,friend!Do you wanna know, is that guy at work?Enter name:");
if(Arrays.asList(wrkrs).contains(a)){
JOptionPane.showMessageDialog(null, "That guy is at work!");
JOptionPane.showMessageDialog(null, "calling " + wrkrsPhone[wrkrsPhone.toString().indexOf(a)]);
}else{
JOptionPane.showMessageDialog(null, "Такого сотрудника нет!");
}
}
I have two arrays, which contain ints and strings. As you can see, I want to add the number of elements in the string array (for example, wrkrs number 3) to the int array, called wrkrs phone. How can i do it? I tried IndexOf, but it doesn't work.
The output, i want is something like:
Enter name:
Юра
That guy is at work!
Calling Юра + wrkrsPhone(Юра).
A better solution would be to have a Worker class that would contain the worker's name and their phone number.
Then you can use a HashMap<String,Worker> instead of your arrays to store the data.
This makes the search more efficient :
Map<String,Worker> workersMap = new HashMap<>();
workersMap.put ("Денис", new Worker ("Денис", 22626));
...
Worker worker = workersMap.get(a);
if (worker != null) {
call (worker.getPhone()); // or do whatever you want to do with the phone number
}
This is more efficient than Arrays.asList(wrkrs).contains(a), which performs linear search on the List.
...
List list = Arrays.asList(wrkrs);
if(list.contains(a)){
JOptionPane.showMessageDialog(null, "That guy is at work!");
JOptionPane.showMessageDialog(null, "calling " + wrkrsPhone[list.indexOf(a)]);
}
...
U better use a Map or extract a class Contact which have name and phone property but i think this is what u looking for :)

String concatenation in relation to JOptionPane

So, I haven't done any programming in a few months because I'm taking general prerequisite courses right now and I have a job, so now I'm a little rusty and I'd like to be up to par for when I take my next programming class in the Fall. Long story short, I'm trying to get back on track, so I'm making a silly practice program.
I made this program with all input and output done through the console using a Scanner, but then decided to go ahead and move over to JOptionPane as an interface. It was a pretty easy transition overall, but I'm just having a problem with the output at the very end. I'm trying to make all of the elements of an array into a nice, grammatically correct String for easy output in JOptionPane, but I can't really get my concatenation to work correctly. I realize that the output is not grammatically accurate when the amount of cats is one or two. I'll work on that after this, it's an easy fix.
Here is the code:
import javax.swing.JOptionPane;
public class JavaTestClass {
public static void main(String[] args)
{
//Get number of cats
int numOfCats = Integer.parseInt(JOptionPane.showInputDialog("How many cats do you have?"));
JOptionPane.showMessageDialog(null, "Oh, so you have " + numOfCats + " cats.\n", "Confirmation", JOptionPane.INFORMATION_MESSAGE);
//Get cat's names
String[] catNames = new String[numOfCats];
for(int i=0;i<numOfCats;i++)
{
catNames[i] = JOptionPane.showInputDialog("Enter the name of cat " + (i+1) + ": ");
}
//Output cat's names
String catNameList = null;
for(int i=0;i<numOfCats;i++)
{
if((i+1) == (numOfCats-1))
{
catNameList.concat(catNames[i] + ", and ");
}
else if ((i+1) == numOfCats)
{
catNameList.concat(catNames[i] + ".");
}
else
{
catNameList.concat(catNames[i] + ", ");
}
}
JOptionPane.showMessageDialog(null, "So your cat's names are: " + catNameList, "Names of cats", JOptionPane.INFORMATION_MESSAGE);
}
}
Sorry about the spacing. It didn't really come out the way I wanted it to on here, but I don't have all day the indent all of the lines just for the sake of the post. Anyway, it should be relatively obvious, even without my long description above what I'm trying to do. Any help would be much appreciated. Thanks in advance.
Strings are immutable. Every operation that modifies a String returns a new one.
So it should be:
catNameList = catNameList.concat(catNames[i] + ", and ");
Also don't initialize it to null.
String catNameList = "";
Reference the String concat javadoc. Concat method is returning the result of concatenation.

Trouble handling input in Java

I'm trying to read input from the terminal. For this, I'm using a BufferedReader. Here's my code.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] args;
do {
System.out.println(stateManager.currentState().toString());
System.out.print("> ");
args = reader.readLine().split(" ");
// user inputs "Hello World"
} while (args[0].equals(""));
Somewhere else in my code I have a HashTable where the Key and Values are both Strings. Here's the problem:
If I want to get a value from the HashTable where the key I'm using to look up in the HashTable is one of the args elements. These args are weird. If the user enters two arguments (the first one is a command, the second is what the user wants to look up) I can't find a match.
For example, if the HashTable contains the following values:
[ {"Hello":"World"}, {"One":"1"}, {"Two":"2"} ]
and the user enters:
get Hello
My code doesn't return "World".
So I used the debugger (using Eclipse) to see what's inside of args. I found that args[1] contains "Hello" but inside args[1] there is a field named value which has the value ['g','e','t',' ','H','e','l','l','o'].
The same goes for args[0]. It contains "get" but the field value contains ['g','e','t',' ','H','e','l','l','o']!
What the hell!!!
However, if I check my HashTable, wherever the key is "Hello", the value=['H','e','l','l','o'].
Any ideas?
Thank you very much.
EDIT:
Here's come code sample. The same is still happening.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Hashtable;
public class InputTest
{
public static void main(String[] args)
{
BufferedReader reader = new BufferedReader(new InputStreamReader( System.in));
Hashtable<String, String> EngToSpa = new Hashtable<String, String>();
// Adding some elements to the Eng-Spa dictionary
EngToSpa.put("Hello", "Hola");
EngToSpa.put("Science", "Ciencia");
EngToSpa.put("Red", "Rojo");
// Reads input. We are interested in everything after the first argument
do
{
System.out.print("> ");
try
{
args = reader.readLine().trim().split("\\s");
} catch (IOException e)
{
e.printStackTrace();
}
} while (args[0].equals("") || args.length < 2);
// ^ We don't want empty input or less than 2 args.
// Lets go get something in the dictionary
System.out.println("Testing arguments");
if (!EngToSpa.contains(args[1]))
System.out.println("Word not found!");
else
System.out.println(EngToSpa.get(args[1]));
// Now we are testing the word "Hello" directly
System.out.println("Testing 'Hello'");
if (!EngToSpa.contains("Hello"))
System.out.println("Word not found!");
else
System.out.println(EngToSpa.get("Hello"));
}
}
The same is still happening. I must be misunderstanding Hash Tables. Ideas where things are going wrong?
Don't worry about the value field - that's just saying that there's a single char array containing the text of "get Hello", and both args[0] and args[1] refer to that char array, but they'll have different offsets and counts. args[0] will have an offset of 0 and a count of 3; args[1] will have an offset of 4 and a count of 5.
I've no idea why your hash map wouldn't be working though... can you provide a short but complete example program?
I just noticed my mistake. I have to use containsKey() instead of contains().
I'd like to thank everyone for helping.
As a bonus, I also learned about what the 'value' field is. Nice!
As Jon said, you're just seeing an artifact of the internal implementation of Strings in Java. You can ignore the value field for your purposes. That has nothing to do with why things aren't working for you. You need to show us the part of the code that's not working.

Categories