I have to display the current user into the gui, but it keep saying the the hashset is empty, this has been bugging me for hours. What is the easiest way to fix this? There might be a lot of un used code as i was testing things trying to make it work.
Client.java
public class Client {
Server.names();
}
Server.java
public class Server {
public static HashSet<String> names = new HashSet<String>();
public static void main(String[] args) throws Exception{
while(true){
name = in.readLine();
if(name == null){
return;
}
if(!names.contains(name)){
names.add(name);
break;
}
}
}
}
Your Q is a bit unclear, but if you want to get the HashSet, names from your Server class, you need to get the reference to it by calling Server.name, not Server.name() as it is not a method.
Now names will be empty until you populate it. To populate it you need to call code that will read user input and store it in names. In this case you can call the main method of Server (see this related Q here) but unless you really want that to be your main method of Server, I would recommend renaming the method to populateNames() or something similar.
Related
I am quite a new coder in Java, I have already used it before but without going deep into it, but now that I learned the basic I am searching for a way to be more efficient in my way of coding, so I ask how could I do lines of code to run one after another each time I use a certain word, for example, I would like my code to run several fighting commands that I premade using only the word "fight" in my code
All you need to do is set up a scanner that waits for a string input after which is process the string received through the scanner and if said string is "fight" then call the fight method.
Like this:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String command = in.next();
in.close();
ProcessCommand(command);
}
static void ProcessCommand(String command) {
if (command.equalsIgnoreCase("fight")) {
fight();
}
}
static void fight() {
// Do Stuff..
}
Hope this helps! :D
So I have written a Java program that has a function handInExam() that may not be called twice in a row, thus the program is history-sensitive. The problem that then occurs is that I need a variable canHandInExam to check whether this method has already been called and update this variable in each method, which leads to very poor maintainability. Below is a code snippet to show the problem.
public class NotAllowedException extends Exception {
public NotAllowedException(String message) {
super(message);
}
}
import java.util.Scanner;
public class Exam {
String[] exam;
String[] answers;
boolean canHandInExam;
public Exam(String[] questions) {
exam = questions;
answers = new String[exam.length];
canHandInExam = false;
}
// This method may only be called once in a row
public void handInExam throws NotAllowedException() {
if (canHandInExam) {
// Send exam to teacher
canHandInExam = false;
} else {
throw new NotAllowedException("You may not hand in this exam!");
}
}
public void otherMethod() {
// Do something
canHandInExam = true;
}
}
In this small example it is feasible to slightly adapt each method, however if you would have lots of methods you would need to adapt all of them. Since after all these methods you may again call handInExam() thus the variable canHandInExam would need to be set to true.
Is there a way to solve this problem in a way that is more maintainable? I am open to other possible programming languages that are not OO, but at this point I am unsure of what would be suitable.
I have considered using functional programming (e.g. Haskell) as those languages are not history-sensitive, however I did not know how to limit that you may only call a function once in a row. I tried searching for how to limit a function call to n times in a row both in Java and Haskell, but this ended up with only references to how to call a function n times.
If you speak about handing in an exam, than this doesn't mean that something is done with that exam, but that there is some entity to which the exam is given. So instead of storing within the exam whether it was handed in or can be handed in, something like this would be more appropriate:
//or whatever you call this
public interface Institution {
void handInExam(Exam exam) throws DuplicateExamException;
boolean isHandedIn(Exam exam);
}
Implementations of Institution store the exams that were handed in (possibly using a Set).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm running the main method by clicking a jButton in this class. First tried by using
public static void main(String[]args)
All the java swing components started to show non static variable cannot be referenced from static content errors. So I changed
public static void main(String[]args)
to
public void main(String[]args)
No errors shown for the swing components but expected result are not displaying in the jTextArea. IF i print the expected output in System.out.println, it shows correctly. What am I doing wrong here? This is how i trigger main() to run by clicking on jButton
jButton4.setText("Analyze");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try{
TestTextRazor test = new TestTextRazor();
test.main(new String[0]);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
This is my main()
public void main(String[] args) throws NetworkException, AnalysisException {
File textSRC = new File("MyText.txt");
String myTextCount = null;
BufferedReader myTextBr = null;
String check = "";
try {
String myTextCurrentLine;
myTextBr = new BufferedReader(new FileReader(textSRC));
while ((myTextCurrentLine = myTextBr.readLine()) != null) {
myTextCount = myTextCount + " " + myTextCurrentLine;
}
// Sample request, showcasing a couple of TextRazor features
String API_KEY = "7d5066bec76cb47f4eb4e557c60e9b979f9a748aacbdc5a44ef9375a";
TextRazor client = new TextRazor(API_KEY);
client.addExtractor("words");
client.addExtractor("entities");
client.addExtractor("entailments");
client.addExtractor("senses");
client.addExtractor("entity_companies");
String rules = "entity_companies(CompanyEntity) :- entity_type(CompanyEntity, 'Company').";
client.setRules(rules);
AnalyzedText response = client.analyze(myTextCount);
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
for (Sentence sentence : response.getResponse().getSentences()) {
for (Word word : sentence.getWords()) {
System.out.println("----------------");
System.out.println("Word: " + word.getLemma());
for (Entity entity : word.getEntities()) {
///System.out.println("Matched Entity: " + entity.getEntityId());
}
for (Sense sense: word.getSenses()) {
//System.out.println("Word sense: " + sense.getSynset() + " has score: " + sense.getScore());
}
}
}
// Use a custom rule to match 'Company' type entities
for (Custom custom : response.getResponse().getCustomAnnotations()) {
for (Custom.BoundVariable variable : custom.getContents()) {
if (null != variable.getEntityValue()) {
for (Entity entity : variable.getEntityValue()) {
String CompanyFound = ("Variable: " + variable.getKey() +"\n"+ "Value:" + entity.getEntityId());
System.out.println(CompanyFound);
jTextArea3.append(CompanyFound);
writer.write(CompanyFound);
writer.flush();
writer.close();
}
}
}
}
String ObjButtons[] = {"Yes","No"};
int PromptResult;
PromptResult = JOptionPane.showOptionDialog(null,"Completed Analysis!\nIs there any error in the Analysis?","Homonym Entity Extraction Application",JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE,null,ObjButtons,ObjButtons[1]);
//JOptionPane.getAlignmentX(Component.BOTTOM_ALIGNMENT);
if(PromptResult==JOptionPane.YES_OPTION)
{
System.out.println("YEs!!!!!");
jTextArea2.setEditable(true);
jTextArea3.setEditable(true);
jButton4.setEnabled(false);
jButton5.setEnabled(true);
}
else{
JOptionPane.showMessageDialog(null, "Completed Analysis!","Alert", 1);
System.out.println("No!!!!!!!!!!");
jTextArea2.setEditable(false);
jTextArea3.setEditable(false);
jButton4.setEnabled(false);
}
}catch (IOException ex) {
}
}
Please guide me.
Basically, the error is saying, you are trying to reference non-static variables from a static context.
Non-static variables (often referred to as instance variables or fields) require an instance of their parent class in order to have some kind referencing context.
Take a look at Understanding Instance and Class Members for more details.
Without much more of an example to go by, I would create a class constructor and move the contents of the main method to it.
I would then fix the main method to be static and create a new instance of the class from the main method...
The reason I would refrain from making Swing components static is it's way to easy to mix up you references and end up referencing something that isn't actually displayed on the screen...
Updated
Two things.
Make sure that the context of your main method is correct, that the UI components that you have created are not static and you are referencing them correctly.
Don't call the TestTextRazor class directly. This is just an example of how the API works. Take the time to understand it and incorporate into your own class(es) as required
Firs of all, what you need to understand is that a static method cannot access class fields or other methods that are non-static. So look at your code. The main has to be static as that is its natural signature, which must remain in tact as is. So all your class fields that you are trying to access in the main method, need to be static. Is this good practice? Absolutely not. You can browse through the Swing tutorial to pick up on good practices. I'm sure if you run through 20 examples, you'll pick up on a lot of good coding practices for Swing. Good Luck!
"I'm running the main method by clicking a jButton in this class"
One thing I noticed that you are doing complete wrong is trying to call the main method from inside your actionPerformed. The main method should never be called. The JVM using that method as an entry point for your program.
Another thing you have to understand is that a Swing program is event-driven. One button, should not run a complete program, unless it is a very small program.
I would consider creating methods for different tasks like
public String getSomethingFromFile(String filename) throws IOExceptions {
}
where you can call that method from an actionPerformed or something to append data to a text area.
Learn to use class members and initialize them in your constructor or some initialization method.
If you want everything that's going on the main method to be performed on a button click, put all that code in the actionPerformed , not in the main. A typical form of what goes inside the main is just something like this, where you just need to initialize your class to get the program running
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
JFrame frame = new JFrame();
frame.add(new MyGUIPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
where new MyGUIPanel() is an instance of your Main class
Another option is to create a method to perform all the tasks that are in the main like
public void performTextRazorTask() throws NetworkException, AnalysisException {
...
}
and just call that method from the actionPerformed
Again, I stress that you have a look at the tutorials I linked for better practices, as this site isn't really a tutorial site, I don't want to get into a tutorial type answer.
First of all you can not make main method as non static.
As per this line non static variable cannot be referenced from static content errors. make those variables as static
I want to make a simple interative shell based on the console where I can write commands like login, help, et cetera.
I first thought of using Enums, but then I didn't know how to implement them neatly without a load of if-else statements, so I decided to go with an array-approach and came up with this:
public class Parser {
private static String[] opts = new String[] {"opt0", "opt1", "opt2", "opt3" ... }
public void parse(String text) {
for(int i = 0; i < opts.length; i++) {
if(text.matches(opts[i]) {
switch(i) {
case 0:
// Do something
case 1:
// Do something-something
case 2:
// Do something else
}
return;
}
}
}
}
But I ended up seeing that this was probably the most rudimentary way of doing something like this, and that there would be problems if I wanted to change the order of the options. How could I make a simpler parser? This way it would work, but it would also have said problems. The use of the program is purely educational, not intended for any serious thing.
A simple approach is to have a HashMap with the key equal to the command text and the value is an instance of class that handle this command. Assuming that the command handler class does not take arguments (but you can easily extend this) you can just use a Runnable instance.
Example code:
Runnable helpHandler = new Runnable() {
public void run(){
// handle the command
}
}
// Define all your command handlers
HashMap<String, Runnable> commandsMap = new HashMap<>(); // Java 7 syntax
commandsMap.put("help",helpHandler);
// Add all your command handlers instances
String cmd; // read the user input
Runnable handler;
if((handler = commandsMap.get(cmd)) != null) {
handler.run();
}
You can easily extend this approach to accept argument by implementing your own interface and subclass it. It is good to use variable arguments if you know the data type e.g. void execute(String ... args)
One solution that comes to mind is actually using Design patterns. You could use the input from the user, as the discriminator for a Factory class.
This factory class will generate an object, with an "execute" method, based on the input. This is called a Command object.
Then you can simply call the method of the object returned from the factory.
No need for a switch statement. If the object is null, then you know the user entered an invalid option, and it abstracts the decision logic away from your input parser.
Hopefully this will help :)
I used the following coding to display user accounts in my domain.But in that coding it display only first 100 records.But in my domain nearly 500 users account.I don't know what problem in this coding
import java.net.URL;
import java.util.List;
import com.google.gdata.client.appsforyourdomain.UserService;
import com.google.gdata.data.appsforyourdomain.provisioning.UserEntry;
import com.google.gdata.data.appsforyourdomain.provisioning.UserFeed;
public class Readuser {
public int i3;
public String rn[]=new String[100];
public void read(){
try
{
// Create a new Apps Provisioning service
UserService myService = new UserService("My Application");
myService.setUserCredentials(admin,password);
// Get a list of all entries
URL metafeedUrl = new URL("https://www.google.com/a/feeds/"+domain+"/user/2.0/");
System.out.println("Getting user entries...\n");
UserFeed resultFeed = myService.getFeed(metafeedUrl, UserFeed.class);
List<UserEntry> entries = resultFeed.getEntries();
for(i3=0; i3<entries.size(); i3++) {
UserEntry entry = entries.get(i3);
rn[i3]= entry.getTitle().getPlainText();
System.out.println(rn[i3]);
}
System.out.println("\nTotal Entries: "+entries.size());
}
catch(Exception e) { System.out.print(e);}
}
public static void main(String args[])
{
Readuser ru=new Readuser();
ru.read();
}
}
You only allocate 100 entries.
public String rn[]=new String[100];
Hint from your code : public String rn[]=new String[100];
Do you really need to have i3 and rn as class members ? Do you really need rn ? A List seems more comfortable as an Object than a String[].
There is no need for the string array (String[]).
Arrays are fixed size; and in this case you have allocated 100 "slots" for Strings, and when You try to assign a string to position 100 ( you know, the 101:th string) it fails.
You catch an exception in the end. Print the stack trace to find out whats going on
catch(Exception e) {
e.printStackTrace();
}
Learn to read it an find out what is says... However you should not catch the exception in this method. It is better to abort whatever the program was doing. Catch it in your main method - just printing or logging it is fine, so that you can correct the programming error.
Anyway; The result you get is a List of user entries. Lists are part of the (java.util)collections framework. Collections have a lot of features; in this case you want to iterate over all entries in the list. You can do this by using the iterator() method -read the javadoc...OR you can use for-loop syntactic sugar for doing this:
for( UserEntry user : entries ) {
// user is the current UserEntry
System.out.println(user.getTitle().getPlainText());
}
The variables i3 and rn are no good... They shouldn't be class variables, and if you need "temporary" variables, define them close to where you are going to use them.
As for naming of variables, a name like "entry" is less useful than "user". Actually a class called UserEntry should probably be called just User, but I don't know about this API, so...