non-static variable cannot be referenced from a static context java [duplicate] - java

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 7 years ago.
I am writing a program to connect to the console pixel example sketch with java. Im still prety new and I got this error:
non-static variable fast cannot be referenced from a static context
I don't know what the error means but my code is:
package javaapplication5;
import java.net.*;
import java.io.*;
import java.util.Scanner;
/**
*
* #author preferreduser
*/
public class JavaApplication5 {
int fast = 0;
public static void main(String[] args) throws IOException {
Scanner x = new Scanner(System.in);
System.out.print("Yun ip: ");
String IP = x.nextLine();
System.out.println("Loding...");
try {
// Create a URL for the desired page
URL url = new URL("http://"+ IP +"/arduino/digital/13/1");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
try {
// Create a URL for the desired page
URL url = new URL("http://"+ IP +"/arduino/digital/13/0");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
System.out.println("Connected to YUN on "+ IP);
OUTER:
while (true) {
Scanner y = new Scanner(System.in);
System.out.print("> ");
String str = y.nextLine();
switch (str) {
case "on":
try {
// Create a URL for the desired page
URL url = new URL("http://"+ IP +"/arduino/digital/13/1");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
} break;
case "off":
try {
// Create a URL for the desired page
URL url = new URL("http://"+ IP +"/arduino/digital/13/0");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
} break;
case "help":
System.out.println("");
System.out.println("on exit");
System.out.println("off help");
System.out.println("");
break;
case "exit":
try {
// Create a URL for the desired page
URL url = new URL("http://"+ IP +"/arduino/digital/13/0");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
} break OUTER;
}
if ( fast == 1 ){
URL oracle = new URL("http://"+ IP +"/arduino/digital/13");
try (BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
}
} else {System.out.println("Success");}
}
}
}
I want to connect to an arduino yun and type commands like on or off and that part worked. I wanted to add an optional option fast to eliminate connecting to http:// * /aruino/digital/13 each time you typed in a command to make things faster. This was my start. I'm going to add a command for it but I can't until I get this figured out

You can access member variable of a class directly only by making it static. Om making an variable static one more method to access it is by class_name.variable_name.
Otherwise you have to make an object of the class and then you can access that varible through that object.
Example:
either you change
int fast=0; to static int fast = 0;
or you do this
JavaApplication5 j5 = new JavaApplication5(); and now access the variable by j5.fast and do further calculations.

change int fast = 0; to static int fast = 0;
You are using variable fast in main method which is a static method. All the variables that are used in any static method should be static. The reason is static method is common for a class, it does not depend on the instance of the class. So it can not use any instance variable(unless you specify which particular instance to use) inside it because the method does not know which instance variable to use.

Related

Using Java to login into www.messenger.com

I am having trouble using code that I found to log into www.messenger.com. It seems like I am not able to write out form parameters because I do not have the right form names. I am having trouble finding the form name of the button and what to set it equal to. My end goal, is to get the html code after I log in.
Source: http://www.dreamincode.net/forums/blog/114/entry-2715-login-to-a-website-from-java/
import java.net.*;
import java.io.*;
private static URL URLObj;
private static URLConnection connect;
public static void main(String[] args) {
try {
// Establish a URL and open a connection to it. Set it to output mode.
URLObj = new URL("http://www.messenger.com/#");
connect = URLObj.openConnection();
connect.setDoOutput(true);
}
catch (MalformedURLException ex) {
System.out.println("The URL specified was unable to be parsed or uses an invalid protocol. Please try again.");
System.exit(1);
}
catch (Exception ex) {
System.out.println("An exception occurred. " + ex.getMessage());
System.exit(1);
}
try {
// Create a buffered writer to the URLConnection's output stream and write our forms parameters.
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connect.getOutputStream()));
writer.write("email=MyEmail&pass=MyPassword&submit=Sign In");
//writer.close();
// Now establish a buffered reader to read the URLConnection's input stream.
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
String lineRead = "";
// Read all available lines of data from the URL and print them to screen.
while ((lineRead = reader.readLine()) != null) {
System.out.println(lineRead);
}
reader.close();
}
catch (Exception ex) {
System.out.println("There was an error reading or writing to the URL: " + ex.getMessage());
}
}
This are the post parameters, that are send by a browser, when you click login:
default_persistent=0
email=user
initial_request_id=A2NPA_SLbM3wAkFRM_Y0fLx
lgndim=eyJ3IjoxOTIwLCJoIjoxMjAwLCJhdyI6MTkyMCwiYWgiOjExNjAsImMiOjI0fQ==
lgnjs=n
lgnrnd=125813_Br9w
login=1
lsd=AVrsF9i0
pass=pass
timezone=-120
Maybe you need some of these to get a successfull login.
You can find these as hidden parameters in the form with the id "login_form".

Single URLConnection to fetch only the first line in java using BufferedReader

I am trying to write a Java program that should automatically download text from a website if and only if it gets updated. The problem I am running into is using only one HTTPURLConnection to do that because if i don't there will be billions of HTTPURLConnections to the web server since I am using a while(true) loop. Here is my work-in-progress, the getMsg() method receives a url and opens an HTTPURLConnection. Currently I am starting a new connection every time I have to read a line, which is not the most efficient way I am sure. How do I keep reading the same line with the same HTTPURLConnection?
// Starts a new URLConnection to "localhost/currentmsg.dat"
// Receives JSON string from the URLConnection
// Sets up a different variable for each object received from the URL for eg. if delete=1 means that the admin is requesting to delete a message from the screen.
import java.io.*;
import java.net.*;
import org.json.*;
import java.io.*;
import java.util.Scanner;
public class jListenerURL {
// Current arguments retrieved from the URL
private static int msgID = 0;
private static int aptID = 1; // Apartment ID of current device
private static int unitID = 3; // Unit ID of current device
static String message; // Message received from admin
static int delete; // Delete a message?
static int dmsgID; // What message to delete?
public static void jListener() {
URL url;
boolean keepGoing = true;
String msg = "";
try {
url = new URL("http://www.lotussmoke.com/msgtest/currentmsg.dat");
while (keepGoing) {
msg = getMsg(url);
JSONObject jObj = null;
try {
jObj = new JSONObject(msg);
}
catch (JSONException je) {
System.out.println("JSON Exception for message, try restarting terminal.");
}
int current = jObj.getInt("msgID");
int targetaptID = jObj.getInt("aptID");
int targetunitID = jObj.getInt("unitID");
// Keep listening, if the message changes meaning a different msgID then print that message
if (current!=msgID && targetaptID == aptID && targetunitID == unitID) {
msgID = jObj.getInt("msgID");
message = jObj.getString("message");
delete = jObj.getInt("delete");
dmsgID = jObj.getInt("dmsgID");
if (delete==1) {
// Delete a message
System.out.println("Delete msg ID? " + dmsgID);
continue;
}
System.out.println("Message ID: " + msgID);
System.out.println("Apartment ID: " + aptID);
System.out.println("Unit ID: " + unitID);
System.out.println("Message: " + message);
}
}
}
catch (MalformedURLException e) {
System.err.println();
}
}
public static void main(String args[]) throws Exception {
jListener();
}
private static String getMsg(URL url) {
HttpURLConnection con = null;
try {
con = (HttpURLConnection) url.openConnection();
} catch (IOException e1) {
e1.printStackTrace();
}
BufferedReader in = null;
String msg = "";
try {
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String received;
while((received = in.readLine()) != null) {
//System.out.println(received);
msg = received;
}
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
return msg;
}
}
Why don't you simply declare your HttpURLConnection object outside of your while loop ? It will then not open a connection at each call inside the loop.
HttpURLConnection cannot be reused, but it can reuse an open connection to the same server internally by setting the header Connection: keep-alive. It doesn't make sense if you connect to different servers, obviously.
One way to efficiently test whether there are changes, is to use If-Modified-Since header or the like If-Unmodified-Since, If-None-Match or If-Match (see HTTP Headers). In this case the web-server decides to deliver a new document if there are changes or just sends the response code 304 Not Modified without a body.
One last thing regarding the use of members (and especially static members): I'd refactor this code and the only item which would be left as static is static void main(). You can see the static members as some kind of global variables. Observing something like 'the connection is returning the same message' might be a effect of inappropriate exception handling and usage of static members.

How to read line from txt?

How can I read line from text? Look at my code:
public static String getTemplateFromFile() {
String name = null;
try {
BufferedReader reader = new BufferedReader(new
FileReader(
"http://localhost:8080/blog/resources/cache/templateName.txt"));
name = reader.readLine();
//name="TEST";
//NULL anyway
reader.close();
}
catch (Exception e) {
}
return name;
}
Also I have got secnod version, but my server freeze.
public static String getTemplateFromFile() {
String name = null;
/*
try {
URL url = new URL("http://localhost:8080/blog/resources/cache/templateName.txt");
Scanner s = new Scanner(url.openStream());
name=s.nextLine();
s.close();
}
catch(IOException ex) {
ex.printStackTrace();
}*/
return name;
}
I think it can't close connection or something.
It returns me NULL even I say name="TEST"; in try construction.
FileReader is exactly that – a class that reads from files, not HTTP requests.
You're getting an invalid file path exception, which you're then ignoring in your evil empty catch block.
Instead, you should use URLConnection.
Try this
try{
URL reader=new URL("http://localhost:8080/blog/resources/cache/templateName.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(reader.openStream()));
name = br.readLine();
//name="TEST";
br.close();
}catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
AFAIK, URL#openStream() internally calls URL#openConnection() which creates an instance of URLConnection and calls URLConnection#getInputStream() on it.

how to run .exe file of a java file in other computers

I have developed a java code in eclipse.My code reads data from a .txt file by using server_ip. I have created an executable jar file of the code and then created an .exe file using launch4j. The .exe file shows data if I run it in my laptop,but it does not show any data if I run it in other pc. then it shows null point exception. my operating system is windows 7-32 bit. I am giving my code here. please give me solutions.
package remotedata;
import java.awt.*;
import java.net.;
import java.io.;
public class remotedataread extends Frame
{
public static void main(String[] args)
throws InterruptedException, IOException{
BufferedReader br = null;
TextArea FileText =
new TextArea(" Content of the File \'temp1.txt\' :");
try
{
URL url =
new URL("file://server_ip/path_file.txt");
InputStream is = url.openStream();
br = new BufferedReader(new InputStreamReader(is));
/* String line = null;
while (true) {
line = br.readLine();
if (line == null) {
//wait until there is more of the file for us to read
Thread.sleep(1000);
}
else {
System.out.println(line);
}
}*/
}
catch (MalformedURLException e)
{
System.out.println("Bad URL");
}
catch (IOException e)
{
System.out.println("IO Error : "+e.getMessage());
}
FileText.setBackground(Color.white);
FileText.append(String.valueOf('\n'));
Frame f = new Frame("server data");
f.setSize(200,200);
f.add(FileText);
f.setVisible(true);
try
{
String s;
s=null;
boolean eof = false;
//while (true) {
s = br.readLine();
System.out.println("Time Temperature");
while( !eof )
{
FileText.append(s + String.valueOf('\n'));
try
{
s = br.readLine();
if ( s == null )
{
// eof = true;
// br.close();
Thread.sleep(1000);
}
else{
//System.out.println("Time Temperature");
System.out.println(s);
}
}
catch (EOFException eo)
{
eof = true;
}
catch (IOException e)
{
System.out.println("IO Error : "+e.getMessage());
}
}
//}
}
catch (IOException e)
{
System.out.println("IO Error : "+e.getMessage());
}
}
}
Maybe , you're application is not able to connect to the other node ..hence its throwing a NullPointer exception .Make sure that computers are in the Network
your prolem seems to be here:
URL url =
new URL("file://server_ip/path_file.txt");
InputStream is = url.openStream();
br = new BufferedReader(new InputStreamReader(is));
the url "file://server_ip/path_file.txt" is valid on your laptop, but not on other pc's

Java text file reading program with bufferedreader and FileReader. Compiling But not working

This program is compiling though not working. It just handling the opening file exception. Please help me.Thanks for your time.
import java.io.*;
import java.util.Scanner;
public class ReadingFile {
/**
* #param args
*/
public static void main(String[] args) {
ReadingFile rf = new ReadingFile();
rf.printOnScr();
}
private BufferedReader openFile(String meString){
Scanner sc = new Scanner(System.in);
BufferedReader bf = null;
while (bf == null) {
try {
System.out.println("Enter a file name");
String fileName = sc.nextLine();
FileReader b = new FileReader(fileName);
bf = new BufferedReader(b);
} catch (IOException e) {
System.out.println("The file you are trying to open dose not exist.");
}
}
return bf;
}
private void printOnScr() {
BufferedReader br = openFile("Please enter a file");
try {
while(true){
String line = br.readLine();
if(line == null) break;
System.out.println(line);
}
br.close();
} catch (IOException e) {
System.out.println("The line you are trying to access have problem/s");
}
}
}
Very probably you're not specifying the correct path to the file when you type it. It should either be an absolute path or a relative path based at your current working directory. To see exactly what's happening, though, you'll need to look at the exception that's thrown. Either print it out with
e.printStackTrace()
or wrap it in an unchecked exception:
throw new IllegalStateException(e);
or let IOException be thrown from openFile(), through printOnScr(), and out of main()

Categories