the object value comparison to a string value does not happen - java

public class ClientServer {
public static void main (String[] args){
Object[] selectioValues = {"Server "," Client"};
String initialSection = "Server";
Object selection = JOptionPane.showInputDialog(null,"login As:","Client server", JOptionPane.QUESTION_MESSAGE,null , selectioValues , initialSection );
**if(selection.equals("Server"))**{
server srv = new server();
srv.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
srv.startRunning();
}
**else if (selection.equals("Client"))**{
String IPServer = JOptionPane.showInputDialog("enter IP:");
Client capsa;
capsa = new Client(IPServer);
capsa.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
capsa.startRunning();
}
}
}
The code in bold doesn't work. When I added breakpoints to check whether the compiler is going inside IF then it was not. Please explain me why IF condition is not running.

Your possible selection values are "Server " and " Client" but you compare to "Server" and "Client". The strings are not equal because of the leading/trailing spaces.

Related

How would you make a !!say command for a discord bot?

This is how my commands are set up:
public void onMessageReceived(MessageReceivedEvent evt) {
//Objects
User objUser = evt.getAuthor();
MessageChannel objMsgCh = evt.getChannel();
Message objMsg = evt.getMessage();
//Commands
if(objMsg.getContentRaw().equalsIgnoreCase(Ref.prefix+"say " + message))
{
StringBuilder message = new StringBuilder();
for(int i = 1; i < command.length; i++) {
if(i == command.length-1) {
message.append(command[i]);
}else {
message.append(command[i] + " ");
}
}
objMsgCh.sendMessage(message.toString()).queue();
objMsg.delete();
return;
}
}
It doesn't reply with anything and I don't understand why.
I am using JDA (Java Discord API).
Respect for your creativity but I think you are missing some basic java knowledge. Here is what I think you are aiming for:
public void onMessageReceived(MessageReceivedEvent event){
if(event.getMessage().getContentRaw().startsWith("!!say")){
event.getChannel().sendMessage(event.getMessage().getContentRaw().substring(6)).queue();
event.getMessage().delete().queue();
}
}
I think the if condition is logical. Get the Messages as String in raw format and looking for the string starting with "!!say". Then send a new Message to the channel where the message was received where the message is the raw message as the string with the first five characters (the "!!say") are cut off. So the Bot is repeating the whole message beside the command tag.
Hope this brings you forward in your mission.
I worked out how to do it.
public void onMessageReceived(MessageReceivedEvent evt) {
//Objects
User objUser = evt.getAuthor();
MessageChannel objMsgCh = evt.getChannel();
Message objMsg = evt.getMessage();
if(objMsg.getContentRaw().startsWith(Ref.prefix+"say"))
{
String words = objMsg.getContentRaw().substring(Ref.prefix.length() + 4);
String more_words = words;
objMsgCh.sendMessage(more_words).queue();
You don't really need String more_words = words;
And I do (Ref.prefix.length() + 4) so it says everything after !!say but make sure to make it create something like String prefix = "!!"; because my may not be able to it with the prefix in the if statement. The + 4 counts every just after the prefix and the space between user input.
For Example:
if(objMsg.getContentRaw().startsWith(Ref.prefix+"urban")) {
String query = objMsg.getContentRaw().substring(Ref.prefix.length() + 6);
Because "urban" has 5 characters you would put 6 to account for the space.
Hope that helps.
If you plan on using the JDA-Utilities the following code will work for creating a command.
public class sayCommand extends Command {
public sayCommand() {
this.help = "!say <message>";
this.aliases = new String[] {"!s"};
this.name = "say";
}
#Override
protected void execute(CommandEvent event) {
event.getChannel().sendMessage(event.getMessage().getContentDisplay().split("\\s+", 2)[1]).queue();
}
}
With only using one line, you could have the bot easily mimic your argument.

I have to determine from a string the starting and arrival cities

I have the following code which, by means of a keyboard input, gives me the start and arrival .. the start is determined according to the "da" proposition, while the arrival determines it according to the preposition "a" so I'm fighting now is: I want to get the start and the arrival even if I change the order of the propositions .. you know how I could proceed ..
this is the OUTPUT I get :
I want to go from ostuni to trapani
Partenza :ostuni
Arrivo :trapani
but if I wrote like this:
I want to go to ostuni by trapani
I would like to print the same start and finish correctly ..that is
Patenza :trapani
Arrivo :ostuni
Is this processing possible?
thanks a lot for the attention! Good day
package eubot.controller;
import eubot.intent.Intent;
public class EubotEngine {
public Intent getIntent(String stringInput) {
String str1 = "";
String str2 = "";
Intent dictionary = null;
for (String str3 : Intent.keyWord) {
if (stringInput.contains(str3)) {
//System.out.println("La stringa contiene : " + str3);
int indice1 = stringInput.indexOf(str3) + str3.length();
String splittable =
stringInput.substring(indice1,stringInput.length()).trim();
String splittable2[] = splittable.split(" ");
int index = 0;
for (String str : splittable2) {
str = splittable2[index +1];
str1 = str;
System.out.println("Partenza :" + str1);
break;
}
String splittable3[] = splittable.split(" ");
for(String str : splittable3) {
str = splittable3[index + 3];
str2 = str;
System.out.println("Arrivo :" + str2);
break;
}
index++;
dictionary = new Intent();
dictionary.setTesto(stringInput);
}
}
return dictionary;
}
}
package eustema.eubot.intent;
public class Intent {
public String testo;
public String getTesto() {
return testo;
}
public void setTesto(String testo) {
this.testo = testo;
}
public static String[] keyWord = { "devo andare", "voglio andare", "vorrei andare", "devo recarmi"};
public static String[] parameter = { "bari", "roma", "milano","pisa","firenze","napoli","como","torino" };
}
package eustema.eubot.main;
import java.util.Scanner;
import eustema.eubot.controller.*;
import eustema.eubot.intent.*;
public class Test {
public static void main(String[] args) {
System.out.println("<<-|-|-|-|-|-|-|-|-|<<<BENVENUTO IN EuBoT>>>|-|-|-|-|-|-|-|-|->>");
EubotEngine controller = new EubotEngine();
Scanner input = new Scanner(System.in);
String string;
while (true) {
string = input.nextLine();
Intent intent = controller.getIntent(string);
}
}
}
I know this will not be considered a good answer:)
This is non-trivial to solve by means of imperative programming. The reason is there are many forms in which one can express the same intent. Things like filler words, synonyms, inversions and in general things you did not think about could disrupt your algorithm.
Of course it depends on the level of accuracy you want to achieve. If you are happy that this will not work for all cases, you could always put in conditions like:
if (arr[index-1] == "from") setStart(arr[index]);
if (arr[index-1] == "to") setDestination(arr[index]);
Google, Amazon and Apple are battling to improve this sort of human-computer interaction, but they are using a more mathematical/statistical approach through machine learning.
So, if you're looking for state of the art:
Main search terms: context-free grammars.
Other key words: Markov models, Information extraction, vector space models, tf-idf

Java string array doesn't print correctly

I am currently working on a Java program that crawls a webpage and prints out some information from it.
There is one part that I can't figure out, and thats when I try to print out one specific String Array with some information in it, all it gives me is " ] " for that line. However, a few lines before, I also try printing out another String array in the exact same way and it prints out fine. When I test what is actually being passed to the "categories" variable, its the correct information and can be printed out there.
public class Crawler {
private Document htmlDocument;
String [] keywords, categories;
public void printData(String urlToCrawl)
{
nextURL=urlToCrawl;
crawl();
//This does what its supposed to do. (Print Statement 1)
System.out.print("Keywords: ");
for (String i :keywords) {System.out.print(i+", ");}
//This doesnt. (Print Statement 2)
System.out.print("Categories: ");
for (String b :categories) {System.out.print(b+", ");}
}
public void crawl()
{
//Gather Data
//open up JSOUP for HTTP parsing.
Connection connection = Jsoup.connect(nextURL).userAgent(USER_AGENT);
Document htmlDocument = connection.get();
this.htmlDocument=htmlDocument;
System.out.println("Recieved Webpage "+ nextURL);
int guacCounter = 0;
for(Element guac : htmlDocument.select("script"))
{
if(guacCounter==5)
{
//String concentratedGuac = guac.toString();
String[] items = guac.toString().split("\\n");
categories = processGuac(items);
break;
}
else if(guacCounter<5) {
guacCounter++;
}
}
}
public String[] processKeywords(String totalKeywords)
{
String [] separatedKeywords = totalKeywords.split(",");
//System.out.println(separatedKeywords.toString());
return separatedKeywords;
}
public String[] processGuac(String[] inputGuac)
{
int categoryIsOnLine = 6;
String categoryData = inputGuac[categoryIsOnLine-1];
categoryData = categoryData.replace(",","");
categoryData = categoryData.replace("'","");
categoryData = categoryData.replace("|",",");
categoryData = categoryData.split(":")[1];
//this prints out the list of categories in string form.(Print Statement 3)
System.out.println("Testing here: " + categoryData.toString());
String [] categoryList=categoryData.split(",");
//This prints out the list of categories in array form correctly.(Print statement 4)
System.out.println("Testing here too: " );
for(String a : categoryList) {System.out.println(a);}
return categoryList;
}
}
I cut out a lot of the irrelevant parts of my code so there might be some missing variables.
Here is what my printouts look like:
PS1:
Keywords: What makes a good friend, making friends, signs of a good friend, supporting friends, conflict management,
PS2:
]
PS3:
Testing here: wellbeing,friends-and-family,friendships
PS4:
Testing here too:
wellbeing
friends-and-family
friendships

Erase console text java

I am making a console chat program in java. Which accepts user text input and sends to server, server then broadcast this to all clients. I want to erase the text entered by user, on his console.
I would prefer platform independent solution.
import java.io.*;
class Test
{
public static void main(String args[])
{
System.out.print("you: ");
String t=getString();
System.out.println("We accepted : " + t);
}
static String getString()
{
String s;
try{
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
s = bufferRead.readLine();
//int count = 1;
//System.out.print(String.format("\033[%dA",count)); // Move up
//System.out.print("\033[2K"); // Erase line content, works on terminal but not on cmd
for(int i=0;i<s.length();i++)
System.out.print("\b"); //dont know, why it doesnt works??
}
catch(IOException e)
{e.printStackTrace(); s="Error";}
return s;
}
}
This is my interpretation of your question:
I am a client and I type a message, "Hello." Everybody else sees "Hello". However, by typing "Hello" into my console, the message is already there. I don't want to see another "Hello" appear on my screen from the announcer.
Is that the functionality you are trying to achieve? If so, I would suggest that you do not erase the message. If you've printed something to console, it might not be so easy to erase it. Rather you could just never send it in the first place.
The following is what I have generally used for messaging systems in which you don't want the sender to see his message twice:
Conveniently, you have a member object for each person connected to the server, and each member has a name. Hopefully names will be unique. Now, if you ensure that every member gets identified with a name upon connecting to your server, then when you announce the message to everyone, you just make sure that you don't announce it to the sender.
Specifically, I would modify the constructor and the run() method of the announcer class:
String message;
String senderName;
announcer( member x , String msg ) {
senderName = x.name;
message= x.name + " : " + msg ;
}
public void run() {
for ( int i=0 ; i<server.group.size() ; i++ ) {
if ( !server.group.get( i ).name.equals( senderName ) ) {
send( server.group.get( i ).sck );
}
}
}
Now, the message is sent to everyone except the sender, which achieves the equivalent result of sending it to the sender and then erasing it. I'm sorry if you will have to write more code to get everyone's name set up correctly, but I haven't heard of any implementations where duplicate messages were just "erased" from standard output.
Alternatively, if your server.group objects are the same as the member objects you pass into the announcer constructor, then this will work
String message;
member sender;
announcer( member x , String msg ) {
sender = x;
message= x.name + " : " + msg ;
}
public void run() {
for ( int i=0 ; i<server.group.size() ; i++ ) {
if ( server.group.get( i ) != sender ) {
send( server.group.get( i ).sck );
}
}
}

How to avoid using dynamic variables / a billion if statements in Java?

So, since dynamic variables aren't a thing in Java, and if statements will be horribly unwieldy, was looking for help converting this code block into a more concise one.
I looked into hashmaps, and they just didn't seem quite right, it's highly likely I was misunderstanding them though.
public String m1 = "Name1";
public String m1ip = "192.1.1.1";
public String m2 = "Name2";
public String m2ip = "192.1.1.1";
public String req;
public String reqip;
... snip some code...
if (requestedMachine == 1)
{ req = m1; reqip = m1ip;}
else if (requestedMachine == 2)
{ req = m2; reqip = m2ip;}
else if (requestedMachine == 3)
{ req = m3; reqip = m3ip;}
else if (requestedMachine == 4)
{ req = m4; reqip = m4ip;}
else if (requestedMachine == 5)
{ req = m5; reqip = m5ip;}
requestedMachine is going to be an integer, that defines which values should be assigned to req & reqip.
Thanks in advance.
Define a Machine class, containing a name and an ip field. Create an array of Machine. Access the machine located at the index requestedMachine (or requestedMachine - 1 if the number starts at 1):
Machine[] machines = new Machine[] {
new Machine("Name1", "192.1.1.1"),
new Machine("Name2", "192.1.1.1"),
...
}
...
Machine machine = machines[requestedMachine - 1];
First, create a Machine class:
class Machine {
String name;
String ip;
//Constructor, getters, setters etc omitted
}
Initialize an array of Machines:
Machine[] machines = ... //initialize them with values
Get the machine corresponding to requestedMachine:
Machine myMachine = machines[requestedMachine];
This is a great candidate for an enum:
/**
<P>{#code java EnumDeltaXmpl}</P>
**/
public class EnumDeltaXmpl {
public static final void main(String[] ingo_red) {
test(MachineAction.ONE);
test(MachineAction.TWO);
test(MachineAction.THREE);
test(MachineAction.FOUR);
}
private static final void test(MachineAction m_a) {
System.out.println("MachineAction." + m_a + ": name=" + m_a.sName + ", ip=" + m_a.sIP + "");
}
}
enum MachineAction {
ONE("Name1", "192.1.1.1"),
TWO("Name2", "292.2.2.2"),
THREE("Name3", "392.3.3.3"),
FOUR("Name4", "492.4.4.4"),
FIVE("Name5", "592.5.5.5");
public final String sName;
public final String sIP;
private MachineAction(String s_name, String s_ip) {
sName = s_name;
sIP = s_ip;
}
}
Output:
[C:\java_code\]java EnumDeltaXmpl
MachineAction.ONE: name=Name1, ip=192.1.1.1
MachineAction.TWO: name=Name2, ip=292.2.2.2
MachineAction.THREE: name=Name3, ip=392.3.3.3
MachineAction.FOUR: name=Name4, ip=492.4.4.4
Thee best choice you have is to build an array of machines with IP, Name etc..then you only need to find the machine required into the array.
public class Machine(){
private String name, ip;
public Machine(String name, String ip){
this.name=name;
// You can check a valid ip
this.ip=ip;
}}
public class Machines(){
private Machine[] machines;
private int number_of_machines;
public Machines(){
//define number_of_machines for your array and length of itself
}}
main()
Machine[] Machines = new Machine[number_of_machines];
Machine m1 = new Machine(String name, String ip);
.
.
.
Machine mn = new Machine(String name, String ip);
int number=5;
for(int i=0; i<number_of_machines; i++){
if (machines[number]<number_of_machines){
System.out.println("There is no machine with that number");
}else if (machines[number]==number_of_machines-1){
System.out.println("That is the choosen machine");
}
}
}
If your id values are not necessarily integers or if they are not a continuous sequence from 0 forward, you could also use a HashMap. Something like
HashMap<Integer, Machine> machines = new HashMap<>();
machines.put(1, machine1);
machines.put(7, machine7);
...
to get the desired value
Machine machine7 = machines.get(7);
You can replace the key with a String or whatever you like if needed. Your id values also do not need to go 0,1,2,3,4,5, ... as they need to if you are going with an array.

Categories