I got a noob question concerning Static vs. Non-Static Methods.
In this example I parse Data out and want to write it to my DB. I was doing fine as long as I declared the method getData() static. But now when im invoking Database.insert(x,y,z) - the static-non static error comes into play. I just can't wrap my thoughts around the problem how to solve this issue.
Can anyone explain to me, how I can write those variables into my DB? your help is highly valued and will help me advance in java.
EDIT:
Error message saying:
Cannot make a static reference to the non-static method insert(String, String, String, String) from the type Database
Code:
package org.jsoup.examples;
import java.io.*;
import org.jsoup.*;
import org.jsoup.nodes.*;
import org.jsoup.select.Elements;
import java.io.IOException;
/**
* Example program to list links from a URL.
*/
public class parseEasy {
String companyName = "Platzhalter";
String jobTitle = "Platzhalter";
String location = "Platzhalter";
String timeAdded = "Platzhalter";
public static void main(String[] args) throws IOException
{
Database connect = new Database();
connect.OpenConnectionDB();
getData();
connect.closeConnectionDB();
}
// FIRMENNAME
public static void getData() throws IOException
{
int count = 0;
Document document = Jsoup.parse(new File("C:/Talend/workspace/WEBCRAWLER/output/keywords_SOA.txt"), "utf-8");
Elements elements = document.select(".joblisting");
for (Element element : elements)
{
// Counter for Number of Elements returned
count++;
// Parse Data into Elements
Elements jobTitleElement = element.select(".job_title span");
Elements companyNameElement = element.select(".company_name span[itemprop=name]");
Elements locationElement = element.select(".locality span[itemprop=addressLocality]");
Elements dateElement = element.select(".job_date_added [datetime]");
// Strip Data from unnecessary tags
String companyName = companyNameElement.text();
String jobTitle = jobTitleElement.text();
String location = locationElement.text();
String timeAdded = dateElement.text();
Database.insert(companyName, jobTitle, timeAdded, location);
// Test output
System.out.println("Firma:\t"+ companyName + "\t" + jobTitle + "\t in:\t" + location + " \t Erstellt am \t" + timeAdded + "\t. Eintrag Nummer:\t" + count);
}
}
/* public void writeDB(String a,String b,String c,String d){
Database.insert(a, b, c, d);
}
String getcompanyName(){
return companyName;
}
String getjobTitle(){
return jobTitle; }
String gettimeAdded(){
return timeAdded; }
String getlocation(){
return location; }
*/
}
Static and Non-Static also have 2, perhaps better names.
Static is also known as Class-Level, and Non-Static is Instance-Level
Example:
class SomeClass {
static void staticPrint() {
// ^^^^^^^^^^^ static
System.out.println("Hello from static");
}
void instancePrint() {
// ^^^^ not static
System.out.println("Hello from non-static");
}
}
So here's where these two types of methods differ:
SomeClass obj = new SomeClass();
SomeClass.staticPrint(); // prints "Hello from static"
SomeClass.instancePrint(); // throws an error
obj.staticPrint(); // throws an error
obj.instancePrint(); // prints "Hello from non-static"
That's it. That's the difference between static and non-static
One works directly from the class, the other works from the object you create when you new it
Related
This point of this program is to limit the character length of a username to 20 characters. It is one part of a larger program which currently only contains a Main method. In the interest of cleaning and clarifying my code, I would like to separate the various functions into distinct methods.
Currently, I'm trying to set class variables so that they can be used in multiple methods. This is what I have so far:
public class Program
{
Scanner read = new Scanner(System.in);
String firstName = read.nextLine();
String lastName = read.nextLine();
public void main(String[] args) {
domainCharLimit();
}
public void domainCharLimit() {
String firstNameNew = firstName.replace("'", "");
String lastNameNew = lastName.replace("'", "");
String domainUsername = firstNameNew + "." + lastNameNew;
if (domainUsername.length()>20) {
String cutName = domainUsername.substring(0, 20);
domainUsername = cutName;
}
System.out.print(domainUsername);
}
}
I have tried setting one or both methods to static, which did not resolve the issue. In this state, when run, the program will not return an errors but rather give "no output"
Main method has to be static! It is entry to your program and its signature has to be like that.
In order to call non static method inside it you need to instantiate an object and call it on that object. In your case something like
public static void main(String[] args) {
Program p = new Program();
p.domainCharLimit();
}
First: Main Method should be always static.
Second: Because you are calling domainChatLimit() from Main(static) than it should be also static
Third: Because you used firstName, lastName attributes in a static method domainChatLimit() then they should be also static
Fourth: Scanner should be also static because you are using it to get firstName, lastName and they are both static.
NOTE: There is no need to define a new instance of this class to call an internal method
Solution should be like below (tested successfully):
import java.util.Scanner;
public class Program{
// variables below should be defined as static because they are used in static method
static Scanner read = new Scanner(System.in);
static String firstName = read.nextLine();
static String lastName = read.nextLine();
// Main method is static
public static void main(String[] args) {
//There is no need to define a new instance of this class to call an internal method
domainCharLimit();
}
// calling from main static method so it should be static
public static void domainCharLimit() {
String firstNameNew = firstName.replace("'", "");
String lastNameNew = lastName.replace("'", "");
String domainUsername = firstNameNew + "." + lastNameNew;
if (domainUsername.length()>20) {
String cutName = domainUsername.substring(0, 20);
domainUsername = cutName;
}
System.out.print(domainUsername);
}
}
if you want to create a Generic Util for that functionality you can do below logic:
PogramUtil.java
import java.util.Scanner;
public class ProgramUtil {
Scanner read = new Scanner(System.in);
String firstName = read.nextLine();
String lastName = read.nextLine();
public void domainCharLimit() {
String firstNameNew = firstName.replace("'", "");
String lastNameNew = lastName.replace("'", "");
String domainUsername = firstNameNew + "." + lastNameNew;
if (domainUsername.length()>20) {
String cutName = domainUsername.substring(0, 20);
domainUsername = cutName;
}
System.out.print(domainUsername);
}
}
now you can call this way :
Program.java
public class Program{
// Main method is static
public static void main(String[] args) {
ProgramUtil programUtil = new ProgramUtil();
programUtil.domainCharLimit();
}
}
I'm really new to Java and programming in general (~3 weeks of experience) so sorry if this question is obvious for you guys. I tried searching for answers here but couldn't find any that fit my specific problem. And yeah it's for school, I'm not trying to hide it.
Here I'm supposed to write an object method that returns the string contained in the object oj, in reverse. I do know how to print a string in reverse, but I don't know how I should call the object since the method isn't supposed to have any parameters.
import java.util.Random;
public class Oma{
public static void main(String[] args){
final Random r = new Random();
final String[] v = "sininen punainen keltainen musta harmaa valkoinen purppura oranssi ruskea".split(" ");
final String[] e = "etana koira kissa possu sika marsu mursu hamsteri koala kenguru papukaija".split(" ");
OmaMerkkijono oj = new OmaMerkkijono(v[r.nextInt(v.length)] + " " + e[r.nextInt(e.length)]);
String reve = oj.printreverse();
System.out.println(reve);
}
}
class OmaMerkkijono{
private String jono;
public OmaMerkkijono(String jono){
this.jono=jono;
}
public String printreverse(){
//so here is my problem, i tried calling the object in different ways
//but none of them worked
return reversedstringthatdoesnotexist;
}
}
You just need to add this to your "printreverse" method :
new StringBuilder(this.jono).reverse().toString()
With this, when you call the method with the object "oj":
String reve = oj.printreverse();
After the previous line, "reve" must contain the value of the String reversed.
Olet hyvä, moi moi!
To revers a String use StringBuilder and reverse()
public String printreverse(){
return new StringBuilder(jono).reverse().toString();
}
To access private attributes from outside the class you use what are called accessors and mutators, aka getters and setters.
You just need a basic getter that also reverses the string.
public class MyObject {
private String objectName;
MyObject(String objectName) {
this.objectName = objectName;
}
public String getObjectName() {
return objectName; // returns objectName in order
}
public String getReversedObjectName() {
return new StringBuilder(objectName).reverse().toString();
}
public static void main(String[] args) {
MyObject teslaRoadster = new MyObject("Telsa Roadster");
System.out.println(teslaRoadster.getObjectName());
System.out.println(teslaRoadster.getReversedObjectName());
}
}
Output:
Telsa Roadster
retsdaoR asleT
Edited the getTypeString method in the Flowers class now I just get the pointer to the object
I'm working on a project for one of my classes. I haven't worked with HashMap before and I need to use one. In this java class I'm trying to print out the full description that I have set. But it wont print the HashMap value from the key. I have tried to use some code from my book, but with no luck.
This is the class that is calling the class that has the HashMap:
public class Garden
{
private Gardener gardener;
private Tools tools;
private Flowers flowers;
/**
* Constructor for objects of class Garden
*/
public Garden()
{
gardener = new Gardener();
tools = new Tools();
Flowers rose;
rose = new Flowers("a beautiful red flower");
rose.setFlower("red", rose);
System.out.println(rose.fullDescription());
}
}
Edited the getTypeString method
This is the class that is using the HashMap:
import java.util.Set;
import java.util.HashMap;
public class Flowers
{
private String fDescription;
private HashMap<String, Flowers> flowers;
/**
* Constructor for objects of class Flowers
*/
public Flowers(String fDescription)
{
this.fDescription = fDescription;
flowers = new HashMap<String, Flowers>();
}
public void setFlower(String color, Flowers type)
{
flowers.put(color, type);
}
public String flowerDescription()
{
return fDescription;
}
public String fullDescription()
{
return "The "+ getTypeString() + " is " + fDescription;
}
private String getTypeString()
{
String des = "";
Collection<Flowers> vals = flowers.values();
for(Flowers f : vals){
des += f;
}
return des;
}
}
The problem, I think, is in the getTypeString() function. Can anyone point me in the right direction?
Edit
I removed the getTypeString method and edited the fullDescription method:
public String fullDescription()
{
return "The "+ type + " is " + fDescription;
}
now I'm trying to get the 'HashMap' to print the objects like so:
"Flower [type= type, description= Description "]"
using thes methods:
public static void printHashMap()
{
System.out.println("hashmap: " + flowers);
}
#Override
public String toString()
{
return "Flower [type=" + type + ", description=" + fDescription ]";
}
From your post, what I have understood is that you want to print the description of flowers. So I think you can try something like:
private String getTypeString(){
String des = "";
Collection<String> vals = flowers.values();
for(String f : vals){
des = des + f.flowerDescription();
}
return des;
}
Override the toString method in your class
Declare a toString method with the following modifiers and return type:
#Override
public String toString() {
return this.fDescription;
}
Implement the method so that it returns a string.
I am new at coding. I was doing a project but I was stuck. My code reads a sentence from a text file. It seperates the sentence and gets the second word and records it in an array. I need to use this word in another place but I couldn't do it.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Classroom {
private String classname;
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public void classroomreader(String filename) {
// This method gets the name for Classroom
File text = new File("C:/classlists/" + filename + ".txt");
Scanner scan;
try {
scan = new Scanner(text);
String line = scan.nextLine();
String classroomarray[] = line.split("\t");
// ** right now classroomarray[1] has the word which I want.**
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
Here is my main class:
public class ProjectMain {
public static void main(String[] args) {
// I created an array with 3 Classroom object inside it.
Classroom[] classarray = new Classroom[3];
//I hope I did this correct.
// I used classroomreader method on my first object.
classarray[0].classroomreader("class1");
// Now I need to use the word in classroomarray[1].
classarray[0].setClassname(????)
}
}
I tried: classarray[0].setClassname(classroomarray[1]); but it gave an error. How can I set the name for my first object?
i'm making just few changes in your code.. try this....definitely this'll work
class Classroom {
private String classname;
String classroomarray[]=null;//declare classroomarray[] here
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public void classroomreader(String filename) {
File text = new File("C:/classlists/" + filename + ".txt");
Scanner scan;
try {
scan = new Scanner(text);
String line = scan.nextLine();
classroomarray = line.split("\t");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
class ProjectMain {
public static void main(String[] args) {
Classroom[] classarray = new Classroom[3];
//here you need to initialize all elements of the array
classarray[0]=new Classroom();
classarray[1]=new Classroom();
classarray[2]=new Classroom();
classarray[0].classroomreader("class1");
classarray[0].setClassname(classarray[0].classroomarray[1]);
System.out.println(classarray[0].getClassname());// here you'll surely get the the desired results
}
}
Its a little hard for me to understand what your code in the top is doing.. that being said I believe if you have a private variable in your top class and then have an accessor method like
public String getPrivateFieldValue()
{
return somePrivateFieldName;
}
Then you can can set the private variable in your main class when you find the value for it. In your main class you can then say:
Object.getPrivateFieldValue() to get that value
or in your situation:
classarray[0].setClassname(classroomreader.getPrivateFieldValue())
I think your problem lies with the concept of scope. Whenever you create a variable, like classroomarray, java registers that the name of that variable then represents the value you assign to it (in simple terms).
Now what Scope means is that not all variables can be accessed from every place. Classroomarray is created inside classroomReader(), but does not get out of that function once it completes. In a way "lives" inside that function, and that's why you can't use it in the main() method.
If you want to use classroomarray inside the main() method, you'll need to transport it there through some means. There are multiple ways of doing this:
Create a field in ClassRoom, like public String[] classroomarray
Return the classroom array you read from the file from the classroomreader() function. Returning a value means that you're "sending back" a value to whatever code called the function in the first place. For example, add(a, b) would return the sum of a and b. You do this by changing:
public void classroomreader(String filename)
To:
public String[] classroomreader(String filename)
And change:
String classroomarray[] = line.split("\t");
To:
return line.split("\t");
Then, in the main() method, you can use:
String[] classroomFile = classarray[0].classroomreader("class1");
And use the contents as you please.
This is an Example,Hope you don't mind hard interpretation. Please add return to your method like this.
public String[] demo() //Added ()
{
String[] xs = new String[] {"a","b","c","d"}; //added []
String[] ret = new String[4];
ret[0]=xs[0];
ret[1]=xs[1];
ret[2]=xs[2];
ret[3]=xs[3];
return ret;
}
So your new code will be like this
public String[] classroomreader(String filename) {
// This method gets the name for Classroom
File text = new File("C:/classlists/" + filename + ".txt");
String[] classroomarray;
Scanner scan;
try {
scan = new Scanner(text);
String line = scan.nextLine();
classroomarray = new String[] {line.split("\t")};//Change this
// ** right now classroomarray[1] has the word which I want.**
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
return classroomarray;
}
In Main method change this:
String [] strArr = demo();//Calling method which returns value clasroomarray
for ( int i = 0; i < strArr.length; i++) {
System.out.println(strArr[3]);//Printing whatever index you want
//Set Values here like this
Classroom classroom=new Classroom();//Initialize your object class
classroom.set(strArr[3]); //Set value
Hi i suggest you declare
classroomarray[]
as a member variable. Then generate getters and setters.
Later you can do what you want by setting
classarray[0].setClassname(classarray[0].getClassroomarray[1]);
I'm trying to help you on the way you want it to be done, but i don't understand why you wanna it to be done like that.
Edit : Here is the code i'm talking about in the comments below
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Classroom {
private String classname;
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public void classroomreader(String filename) {
// This method gets the name for Classroom
File text = new File("C:/classlists/" + filename + ".txt");
Scanner scan;
try {
scan = new Scanner(text);
String line = scan.nextLine();
String classroomarray[] = line.split("\t");
// ** right now classroomarray[1] has the word which I want.**
this.classname = classroomarray[1];
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
And finally your main method should look like
public class ProjectMain {
public static void main(String[] args) {
// I created an array with 3 Classroom object inside it.
Classroom[] classarray = new Classroom[3];
classarray[0]=new Classroom();
//I hope I did this correct.
// I used classroomreader method on my first object.
classarray[0].classroomreader("class1");
// Now classname is already set
System.out.println(classarray[0].getClassname());
}
}
I have a class Components:
public class Components {
int numberOfNets;
String nameOfComp;
String nameOfCompPart;
int numOfPin;
public components(int i, String compName, String partName, int pin) {
this.numberOfNets = i;
this.nameOfComp = compName;
this.nameOfCompPart = partName;
this.numOfPin = pin;
}
}
Inside another class I created an arraylist of Components class:
List<Components> compList = new ArrayList<Components>();
Later in the code, I am adding the elements in List in this way:
compList.add(new Components(0,compName,partName,0));
See, here numberOfNets and numOfPin variables in Components class are initiated with 0 values. But these values are getting calculated/incremented in a later part of code and hence I need to update the new values of only these two variables in each list element. Now from ArrayList doc I get the idea of updating a list element using its index by set operation. But I am confused how to set/update a particular variable of a class in an ArrayList of a class. I need to update only these two mentioned variables, not all of the four variables in Components class. Is there any way to do that?
You should add getter/setter to your component class so that outer class can update component's members
public class Components {
private int numberOfNets;
private String nameOfComp;
private String nameOfCompPart;
private int numOfPin;
public components(int i, String compName, String partName, int pin) {
setNumberOfNets(i);
setNameOfComp(compName);
setNameOfCompPart(partName);
setNumOfPin(pin);
}
public void setNumberOfNets(int numberOfNets) {
this.numberOfNets = numberOfNets;
}
// Similarly other getter and setters
}
You can now modify any data by using following code because get() will return reference to original object so modifying this object will update in ArrayList
compList.get(0).setNumberOfNets(newNumberOfNets);
Example code.
public class Main {
public static void main(String[] args) {
List<Components> compList = new ArrayList<Components>();
compList.add(new Components(0, "compName", "partName", 0));
System.out.println(compList.get(0).toString());
compList.get(0).numberOfNets = 3;
compList.get(0).numOfPin = 3;
System.out.println(compList.get(0).toString());
}
}
Your class.
public class Components {
int numberOfNets;
String nameOfComp;
String nameOfCompPart;
int numOfPin;
public Components(int i, String compName, String partName, int pin) {
this.numberOfNets = i;
this.nameOfComp = compName;
this.nameOfCompPart = partName;
this.numOfPin = pin;
}
public String toString() {
return this.numberOfNets + " " + nameOfComp + " " + nameOfCompPart
+ " " + numOfPin;
}
}
The output:
0 compName partName 0
3 compName partName 3