Eclipse auto complete not working - java

Basically, I have a situation like this :
I want to know why the auto completion feature does't show the variable lineItems.
I am using Eclipse Kepler on Mac OS and pressing Control + Space.
EDIT :
I have looked at otter similar questions, and I believe I have the preferences set up correctly.

Because non-static variables can not be referenced from static context eclipse is much more smarter than we think just add static keyword to your list and it will show the suggestions.
Even if you write full name by your self still no use as it will give you error and from the configuration I think you will get suggestion for other functionalities.

Make an instance of TreeFormatter, or make the instance variable static.
import java.util.LinkedList;
import java.util.List;
public class TreeFormatter {
List<String> lineItems = new LinkedList<String>();
static List<String> staticlineItems = new LinkedList<String>();
public static void main(String[] args) {
// make an instance of TreeFormatter
TreeFormatter tf = new TreeFormatter();
tf.lineItems.add("foo");
// or make it static
staticlineItems.add("bar");
}
}

Related

Java string declaration IntelliJ IDEA

Trying to declare a string in Java inside the main method of a Console application.
String s = "this is some text";
I get a red underline saying, 'class' or 'interface' expected.
If I change the code to read
String s = new String("this is some text");
everything works, or at least the code compiles. Using JDK 1.8 and have recently upgraded the IDE to version 2016.2.4.
This only occurs when declaring a new String, all other type declarations and initializations work without declaring a new instance, i.e.
int i = 0;
Anyone know why the first declaration won't work?
Similar behaviour is exhibited when trying to write to the console,
System.out.println("this is some text");
The word 'text' is red underlined saying 'class' or 'interface' expected.
EDIT: entire class as requested
package Sandbox;
public class Main {
public static void main(String[] args) {
System.out.println("this fails");
}
}
however
package Sandbox;
public class Main {
public static void main(String[] args) {
System.out.println(new String("this works"));
}
}
See screenshot below of actual code in the IDE. Comments welcome.
Looks like an issue with Language Injections in IntelliJ.
https://www.jetbrains.com/help/idea/2016.2/using-language-injections.html
Disable the Language Injections. That should fix your Problem.
An similiar issue with the println method and string is described here and has been solved by unregistering println from string injections: https://intellij-support.jetbrains.com/hc/en-us/community/posts/206836685-System-out-println-hello-analyze-error

How to load Java Swing MainJFrame with classes instance and data from ANOTHER Java Class?

Hello Guys I have my swing application running but I need to create an "initialization class" where I create instances with data to populate the program when I run it
If I create an instance with data in the MainJFrame constructor it's working perfectly but I need to populate the MainJFrame that will send it through all the panels from ANOTHER CLASS
Here is my MainJFrame Code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package UserInterface;
import Business.Initialization;
import Business.Inventory;
import Business.InventoryList;
import Business.Product;
import Business.ProductCatalog;
import Business.Store;
import Business.StoreDirectory;
import UserInterface.StarMarketAdmin.MarketAdminWorkArea;
import UserInterface.StoreAdmin.LoginStoreAdmin;
import java.awt.CardLayout;
import java.util.Collections;
import javax.swing.SwingUtilities;
public class MainJFrame extends javax.swing.JFrame {
/**
* Creates new form MainJFrame
*/
private StoreDirectory storeDirectory;
private InventoryList inventoryList;
private ProductCatalog productCatalog;
private Store store;
public MainJFrame() {
initComponents();
this.storeDirectory = new StoreDirectory();
this.inventoryList = new InventoryList();
this.productCatalog = new ProductCatalog();
this.store = new Store();
}
private void btnMarketAdminActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
MarketAdminWorkArea panel = new MarketAdminWorkArea(userProcessContainer,storeDirectory,inventoryList,productCatalog,store);
userProcessContainer.add("MarketAdminWorkArea", panel);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
}
private void btnStoreAdminActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
LoginStoreAdmin panel = new LoginStoreAdmin(userProcessContainer,storeDirectory,inventoryList,productCatalog);
userProcessContainer.add("LoginStoreAdmin", panel);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
}
}
Now if I create an instance like:
Store s = storeDirectory.addStore();
s.setStoreName("Eddie's Market");
s.setStreet("Plainfield Pike");
s.setCity("Johnston");
s.setState("RI");
s.setCountry("USA");
in the MainJFrame it's working 100% but I need to create it in another class and call it in the MainJFrame to send it from there to all the other pannels.
How can I do this ?
create public functions to acces the private class from outside
not sure what you want exactly, but the options are endless
like
public void initStore(){
}
or just get it
public Store getStore(){
retturn store;
}
or even create and return it from there:
public Store storeFactory(){
// code here
return store;
}
or if you want another store and return it
public Store storeFactory(){
// code here to create a new store
return store2;
}
* NOT ADVISED but also an option: static *
you can also create a static one, even make it public, however public access is not the nicest way. Better keep it private and work with function as above to get it. In normally would not advice static usage like this... but assuming the MainFrame is the main program... in this case there might be an exception on the not to use static ....
private static Store store;
or
public static Store store;
than you can access it from everywhere by:
MainJFrame.store
* end static remark *
but maybe you just meant this:
public putStore(Store store){
this.store=store;
}
so you can create it in other class, and get it from other classes
in the other class to create it you migth even first get it (init it in the mainFrame with null:
private Store store=null;
in the other class:
Store store = mainframe.getStore();
// code to create it
or only create it if not yet created:
if (store==null){
// Only create if still null
// code to create it here
}
// and here use it, just created or not
Migth be a weird and 'know it all' like advice, but:
all of the above is basic java knowledge about public, private, static and so on.... might look in to some tutorials, to understand the basic things.
Java can be a pain in the... in case you do not understand it (memory leaks and so on...) so please be sure you know what you do.... (in case you want to use it professionaly)
In java there is a big difference in declaring it, and initialising it:
this is a declaration:
private Store store:
this is the init:
store = // something, even putting it to null is an init
and the combination of declare and init:
private Store store=null;
the last one you need before you can call it from other classes, because you actually will not get the object, but a pointer tot the object.
To have a pointer, you need tot init it, than init to null is enough.... so there is at least a pointer.
Understanding the way of pointers and how things are passed in java, will save some memory issues in bigger programs.
Inject this Store instance into the MainJFrame constructor.
The Store class will hold the data and you can access it through get methods.
Have you thought about that?

Error: Main method not found in class... why am I getting this?

Before people start flagging this question as a duplicate, know that I took the time too look at similar questions, and found that the answers to other "Error: Main method not found in class..." were not clearly applicable to my situation (according to my limited understanding of java)
I'm trying to utilize a text to speech api. Eclipse isn't complaining about the following code until I try to compile:
package com.textToSpeech;
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
public class FreeTTS {
private static final String VOICENAME_kevin = "kevin";
private String text; // string to speech
public FreeTTS(String text) {
this.text = text;
}
public void speak() {
Voice voice;
VoiceManager voiceManager = VoiceManager.getInstance();
voice = voiceManager.getVoice(VOICENAME_kevin);
voice.allocate();
voice.speak(text);
}
public static void main(String[] args) {
String text = "FreeTTS was written by the Sun Microsystems Laboratories "
+ "Speech Team and is based on CMU's Flite engine.";
FreeTTS freeTTS = new FreeTTS(text);
freeTTS.speak();
}
}
The following error shows up in the console:
Error: Main method not found in class com.textToSpeech.FreeTTS, please define the main method as:
public static void main(String[] args)
The code above obviously has a main method, so does anyone know why I am getting this error, and furthermore how I can fix it?
I think it has something to do with the name of the class. If I change the name of the class to something like t2s and then try to compile, I get this error:
Error: Could not find or load main class com.textToSpeech.t2s
Anybody have any thoughts? Any help would be really appreciated.
You may have messed up your project properties. I don't use eclipse, so I cannot say for sure, but try creating a new project and adding the same code to it without fiddling with the properties. The class name and the file name should be the same, check that. Also make sure that the source file is in the same package folder. If nothing works, just create a new project.
Cheers.

global variables between different classes java

i am on the creation of an app in android. its a calculator app. the main activity is where the user could input the equation, and the second activity is where the user can add/edit/delete variables. so i made a new class in another file named Global.java. then i extended it to application, imported everything i need, made s private string, made some public functions, edited the manifest, and initialized it right on my main activity. everything works fine while im only using a string to be passed by the functions but when i started adding what i need, an ArrayList, and made some functions so i could access the list then run it, the app closes. i think its because the arraylist is not allowed to be passed to different classes? am i right or am i just missing something?
please dont downvote my post if i didn't post something needed. i am using aide so there is no log output. code:
Global.java
...
import android.app.*;
import java.util.*;
public class Global extends Application
{
private String s;
public static ArrayList<String> sList;
public String getS() {
return s;
}
public void setS(String ss) {
s=ss;
}
public void add() {
sList.add(s);
}
}
MainActivity.java
...
String s;
...
global=(Global)getApplicationContext();
...
global.setS("jian"); //this one works
global.sList.add("jian"); // this one dont
...
Are you sure you initialized sList, like this:
sList = new ArrayList<String>();
If you didn't, you might want to change its declaration to include this initialization.
public static ArrayList<String> sList = new ArrayList<String>();
Just do
global.add("jian");
since you have an add function to take care of the addition of item to arraylist.
Also, try with this:
public void add(String ss) {
sList.add(ss);
}
You are not instantiating your arraylist.
public static ArrayList<String> sList = new Arraylist<String>();
Also you should read beginner tutorials on Java and android, using a public extension of application like this is a bad idea and you can get log outputs from different apps if Aide doesn't provide that, search play store

IllegalAccessException on using reflection

I was trying to learn reflection and I came across this IllegalAccessException. Please see the following code:
public class ReflectionTest
{
public static void main(String[] args)
{
Set<String> myStr = new HashSet<String>();
myStr.add("obj1");
Iterator itr = myStr.iterator();
Method mtd = itr.getClass().getMethod("hasNext");
System.out.println(m.invoke(it));
}
}
When I tried to run this program, I got the following:
Exception in thread "main" IllegalAccessException
I don't understand what's going on. Any ideas? Thanks in advance.
The troublesome piece of code is this:
itr.getClass().getMethod
You probably wanted hasNext on the Iterator class. What you have written is the HashMap.KeyIterator class, which according the Java language access specifiers (or at least the rough interpretation of JDK 1.0 used by reflection) is not available to your code.
Use instead:
Iterator.class.getMethod
(And if it wasn't for learning purposes, stay away from reflection.)
You cannot access it, because the Iterator is a private inner class. More explanation can be found here.
It's apparent that your currently executing method does not have access to the method named hasNext, e.g., by it being private or protected. You could try to enable access to it using method.setAccessible(true);
It might also be that you have some restrictions defined in your security manager (which, if you use e.g., linux, might have been included default from the distributions java package).
[EDIT] As it turns out, Tom Hawtin identified the correct root cause. You are indeed operating on HashMap.KeyIterator. Although the solution would be to use Iterator.class instead of itr.getClass() you could still enable access to it using setAccessible(true).
I suspect you should use getDeclaredMethod (among other issues). I don't bother to remember Reflection API details (they're for the compiler!), but in your case compare your code with that produced by dp4j:
$ javac -Averbose=true -All -cp dp4j-1.2-SNAPSHOT-jar-with-dependencies.jar ReflectionTest.java
ReflectionTest.java:6: Note:
import java.util.*;
public class ReflectionTest {
public ReflectionTest() {
super();
}
#com.dp4j.Reflect()
public static void main(String[] args) throws java.lang.ClassNotFoundException, java.lang.NoSuchFieldException, java.lang.IllegalAccessException, java.lang.NoSuchMethodException, java.lang.reflect.InvocationTargetException, java.lang.InstantiationException, java.lang.IllegalArgumentException {
final java.lang.reflect.Constructor hashSetConstructor = Class.forName("java.util.HashSet").getDeclaredConstructor();
hashSetConstructor.setAccessible(true);
Set<String> myStr = (.java.util.Set<.java.lang.String>)hashSetConstructor.newInstance();
final java.lang.reflect.Method addWithEMethod = Class.forName("java.util.Set").getDeclaredMethod("add", .java.lang.Object.class);
addWithEMethod.setAccessible(true);
addWithEMethod.invoke(myStr, new .java.lang.Object[1][]{"obj1"});
final java.lang.reflect.Method iteratorMethod = Class.forName("java.util.Set").getDeclaredMethod("iterator");
iteratorMethod.setAccessible(true);
Iterator itr = (.java.util.Iterator)iteratorMethod.invoke(myStr);
final java.lang.reflect.Method hasNextMethod = Class.forName("java.util.Iterator").getDeclaredMethod("hasNext");
hasNextMethod.setAccessible(true);
final java.lang.reflect.Method printlnWithbooleanMethod = Class.forName("java.io.PrintStream").getDeclaredMethod("println", .java.lang.Boolean.TYPE);
printlnWithbooleanMethod.setAccessible(true);
printlnWithbooleanMethod.invoke(System.out, new .java.lang.Object[1][]{hasNextMethod.invoke(itr)});
}
}
public static void main(String[] args)
^
...
$ java ReflectionTest
true
The only change you need to do is annotate your main method with #com.dp4j.Reflect:
$ vim ReflectionTest.java
import java.util.*;
public class ReflectionTest
{
#com.dp4j.Reflect
public static void main(String[] args)
{
Set<String> myStr = new HashSet<String>();
myStr.add("obj1");
Iterator itr = myStr.iterator();
// Method mtd = itr.getClass().getMethod("hasNext");
System.out.println(itr.hasNext());
}
}
NB: this works only with dp4j-1.2-SNAPSHOT (I've just added suport for it). If you don't use Maven, download the jar from here. You find the test case with your problem here.

Categories