Static method ... gives an error
Program-1
This is OK.
Will give expected the output - Hello
public class test{
public static void main(String argv[]){
test t = new test();
t.Hello();
public void Hello(){
System.out.println("Hello");
Program-2
This is also OK.
Will give expected output - Hello
public class test{
public static void main(String argv[]){
Hello();
public static void Hello(){
System.out.println("Hello");
Program-A
import java.awt.*;
import java.awt.event.*;
public class test extends Frame {
public static void main(String argv[]){
test mwc = new test();
mwc.MyWc();
public void MyWc(){
setSize(300,300);
setVisible(true);
}This program is much similar to the above Program-1
This is also give the expected output.
BUT...
this is also similar to the above Program-2
This gives compilation error
WHY IS THAT ???
Program-B
import java.awt.*;
import java.awt.event.*;
public class test extends Frame {
public static void main(String argv[]){
MyWc();
public static void MyWc(){
setSize(300,300);
setVisible(true);
Simply,
Program-1 and Program-A are logically similar. And they behave as expected.
(Creating the object and calling the method)
Also
Program-2 and Program-B are logically similar.(Seems to be)
(Call the method without creating the object.used static)
But why Program-B gives an error ???
Remember that static methods do not belong to a particular instance of a class. Therefore what are setting the size of and what are you making visible?
Similar Messages
-
Compilation error while calling static method from another class
Hi,
I am new to Java Programming. I have written two class files Dummy1 and Dummy2.java in the same package Test.
In Dummy1.java I have declared a static final variable and a static method as you can see it below.
package Test;
import java.io.*;
public class Dummy1
public static final int var1= 10;
public static int varDisp(int var2)
return(var1+var2);
This is program is compiling fine.
I have called the static method varDisp from the class Dummy2 and it is as follows
package Test;
import java.io.*;
public class Dummy2
public int var3=15;
public int test=0;
test+=Dummy1.varDisp(var3);
and when i compile Dummy2.java, there is a compilation error <identifier > expected.
Please help me in this program.public class Dummy2
public int var3=15;
public int test=0;
test+=Dummy1.varDisp(var3);
}test+=Dummy1.varDisplay(var3);
must be in a method, it cannot just be out somewhere in the class! -
Non-static method setUp() cannot be referenced (error)
Hi;
I have this error
"findContainer.java": non-static method setUp() cannot be referenced from a static context at line 10, column 26
everytime i am trying to make this call
jade.core.AddContTry.setUp();in
public class findContainer {
public findContainer() {}
public void sUp(){
System.out.println("please wait, this is first try to find he agents in the main container"+"\n");
jade.core.AddContTry.setUp();
this setup() method
is written as follows
public void AddContTry () {
public void setUp(){
AID[] list= null;
try {
MyMainContainer = myprofile.getMain();
System.out.println("\n"+"This is the new container created in case of failure"+"\n");
list = MyMainCont.agentNames();
for (int i=0; i<list.length; i++){
System.out.println("names = " + list.toString() + " \n");
catch (ProfileException pe) { System.out.println("there is not main container");
could you please help me?My guess is that it is throwing a NullPointerException because you have not set 'a' to be anything.
The sample code you provided does not make sense.
AddContTry is a method in the code but you are using it like a class.
You have to set the following before you can use the object 'a'
AddContTry a = // something
I am just guessing here but can you write
AddContTry a = new AddContTry();
a.setUp();
Note, If this is the case, the code in setUp should be in the constructor. -
Non-static method error message
why this error message? i'm new to Java.
Non-static method compare(java.lang.object,java.lang.Object) cannot be referenced from a static context at line 54.
Any assistance would be greatly appreciated. Thanks.
Calling Method;
private static void selectionSort(Object[] objectArray)
int min, temp;
for (int index = 0; index < objectArray.length-1; index++)
min = index;
int alen = objectArray.length;
for (int scan = index+1; scan < alen; scan++)
(Line 54) NameComparator.compare(objectArray[scan],objectArray[min]);
Invoked Class/Method:
import java.util.Comparator;
public class NameComparator implements Comparator {
private String object, object1, firstCompare, secondCompare;
// Constructors
public NameComparator()
firstCompare = object;
secondCompare = object1;
// Compare method
public int compare(Object object, Object object1)
int result = firstCompare.compareTo(secondCompare);
return result;
}That message occurs when you attempt to call a regular class method from a static class method, which usually means that you've called a regular method from main(). Remember this is main:
public static void main( String[] args ) { . . . }The static keyword means that main() is part of the class, but not part of objects created from that class. The error message is really saying:
// You're trying to use a method that needs an object of this class type,
// but you don't have an object of this class type.I get this message often enough. It just means that I forgot to create an object, or that I forgot to use it when I called the method.
class SomeThing {
public static void main( String[] args {
doWhatever(); // wrong - requires a SomeThing object
SomeThing st = new SomeThing(); // got a SomeThing now
doWhatever(); // still wrong - only works for an object
st.doWhatever(); // finally right!
} // end main()
SomeThing() { . . . } // constructor for SomeThings
doWhatever() { . . . } // method that a SomeThing can perform
} // end of class SomeThing -
Php5 static class method access syntax error
Dreamweaver is complaining about this syntax
$class = 'ClassName';
$class::method(); // static method
Is there a way to omit these error warnings?Thanks for pointing out the reference to the change in PHP syntax.
To the best of my knowledge, there is no way to turn off the syntax checking. You can turn off code hints, but that doesn't have any effect on the syntax checker.
I suggest that you file a bug report to Adobe using the form at https://www.adobe.com/cfusion/mmform/index.cfm?name=wishform. Include the reference to the syntax change with your report. -
Error: Cannot make a static reference to the non-static method
Below is a java code. I attempt to call method1 and method2 and I got this error:
Cannot make a static reference to the non-static method but If I add the keyword static in front of my method1 and method2 then I would be freely call the methods with no error!
Anyone has an idea about such error? and I wrote all code in the same one file.
public class Lab1 {
public static void main(String[] args) {
method1(); //error
public void method1 ()
public void method2 ()
}See the Search Forums at the left of the screen?
If you had searched with "Cannot make a static reference to the non-static method"
http://search.sun.com/search/onesearch/index.jsp?qt=Cannot+make+a+static+reference+to+the+non-static+method+&rfsubcat=siteforumid%3Ajava54&col=developer-forums
you would have the answer. Almost every question you will ask has already been asked and answered. -
Redefine Static Methods in ABAP OO
Hello,
I want to redefine an public static method and returns always an error.
Okay, I already solved the problem with an workaround, but I still don't understand, why it is not possible to redefine static methods in ABAP OO.
If someone can give me an plausible reason, so I don't have do die stupid. G
Thanks for help!
MatthiasIt is built into the language that way. HEre is a link that may or may not give you an answer.
redefine static method?
Regards,
Rich Heilman -
Reading from text file gives IndexOutOfBoundsException error
Dear All
I really need your help in doing my assignment as soon as possible
I am reading from a text file the following data
4231781,Ali,AlAli
4321790,Adnan,AlAli
using two classes first one is
public class Student
private String studFName;
private String studLName;
private String studID;
private double assignment1;
private double assignment2;
private double final_exam;
private double total;
public String getstudfName() {
return studFName;
public void setstudfName(String studFName) {
this.studFName = studFName;
public String getstudlName() {
return studLName;
public void setstudlName(String studLName) {
this.studLName = studLName;
public String getstudid() {
return studID;
public void setStudID(String studID){
this.studID = studID;
public double getAssignment1() {
return assignment1;
public void setAssignment1(double Assignment1) {
this.assignment1 = assignment1;
public double getAssignment2() {
return assignment1;
public void setAssignment2(double Assignment2) {
this.assignment2 = assignment2;
public double getFinal_exam() {
return final_exam;
public void setFinal_exam(double final_exam) {
this.final_exam = final_exam;
public double getTotal() {
return total;
public void setTotal(double total) {
this.total = total;
Student[] students = new Student[30];
the second is manager one which is:
import java.io.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
public class manager {
public static Student[] students = new Student[30];
public static void main(String args[]) {
// We want to let the user specify which file we should open
// on the command-line. E.g., 'java TextIO TextIO.java'.
if(args.length != 1) {
System.err.println("usage: java manager (file_name)");
System.exit(1);
// We're going to read lines from 'input', which will be attached
// to a text-file opened for reading.
BufferedReader input = null;
try {
FileReader file = new FileReader(args[0]); // Open the file.
input = new BufferedReader(file); // Tie 'input' to this file.
catch(FileNotFoundException x) { // The file may not exist.
System.err.println("File not found: " + args[0]);
System.exit(2);
// Now we read the file, line by line, echoing each line to
// the terminal.
try {
String line;
// Student[] students = new Student[30];
while( (line = input.readLine()) != null ) {
// System.out.println(line);
int m = line.indexOf(",");
int j = line.lastIndexOf(",");
String sID = line.substring(0,m);
String sfn = line.substring(m+1,j) ;
String sln = line.substring(j+1);
int n = 0;
students[n] = new Student();
students[n].setStudID(sID);
students[n].setstudfName(sfn);
students[n].setstudlName(sln);
students[n].setAssignment1(0.0);
students[n].setAssignment2(0.0);
students[n].setFinal_exam(0.0);
students[n].setTotal(0.0);
++n;
catch(IOException x) {
x.printStackTrace();
// Arrays.sort(Student.students);
int length = args.length;
System.out.println();
// System.out.println("Sorted by stuID");
for (int i=0; i<length; i++) {
System.out.print("Student ID "+students.getstudid() + "|||");
System.out.print("Student Fname "+students[i].getstudfName() + "|||");
System.out.print("Student name "+students[i].getstudlName());
when I comile progrma it doesn't give any error but when I run it gives me the following exception:
java.lang.String.substring. IndexOutOfBoundsException string index out of range : -1
as can be seen from the manager class I form the read line from readline method as follows:
int m = line.indexOf(",");
int j = line.lastIndexOf(",");
String sID = line.substring(0,m);
String sfn = line.substring(m+1,j) ;
String sln = line.substring(j+1);
Therefore, student ID should be read from the beggining tel the character before the comma (,) then from the character after first comma tel that before second comma will be firstname, finally the rest after second comma will be last name.
I want my program to read all lines in the text file and put them in order as above forming the array like database record and print them all.
Could you please Help me in this matter friends as soon as possible.
Regards,
Java_Hobbyplease, format you code first (select your java code and hit the code button), then post all the error log message.
-
Method not found error even though method exists....
hello
i m a newbee to sun and oracle technologies
these days i m doing teh SRDemo tutorial with JDeveloper (ADF)
I m having a problem and cannot figure out its solution so far
problem is i have a utility funtion defined in a AFDUTIL javaclass,
when i call this function in any class ,
and one of its method
compiler gives me error method not found
even though i select the method from the list, plus when from cotenxt menu it can go to method as welll
please help me to solve this issue
regardswell the code behind for the button is as follows
public String cancelButton_action() {
This action is actually reused from two pages, so we just need to ensure that we
use the correct binding container reference.
DCBindingContainer dcBindings =
(DCBindingContainer)ADFUtils.findBindingContainer(getBindings(),
"app_SRCreatePageDef");
Reset the product list to the first item:
DCIteratorBinding productsIter =
dcBindings.findIteratorBinding("findAllProductsIter");
productsIter.setCurrentRowIndexInRange(0);
Clean out the description field:
AttributeBinding problem =
(AttributeBinding)dcBindings.getControlBinding("problemDescription");
problem.setInputValue(null);
Navigate back to the list page
return "GlobalHome";
and in ADF UTILS the method findBindingContainer is defined as
public static BindingContainer findBindingContainer(BindingContainer bindings, String pageDefName){
BindingContext bctx = ((DCBindingContainer)bindings).getBindingContext();
BindingContainer foundContainer = bctx.findBindingContainer(pageDefName);
return foundContainer;
plus in source code of cancelbutton window message gives error BindingContainer findBindingContainer(BindingContainer bindings, String pageDefName) cannot invoke BindingContainer findBindingContainer(BindingContainer bindings, String pageDefName)(ADFUTILS)
Message was edited by:
user518797 -
Generic static methods in a parameterized class
Is there anything wrong with using generic static methods inside of a parameterized class? If not, is there anything special about defining them or calling them? I have a parameterized class for which I'd like to provide a factory method, but I'm running into a problem demonstrated below:
class MyClass<T> {
private T thing;
public
MyClass(T thing) {
this.thing = thing;
public static <U> MyClass<U>
factoryMakeMyClass(U thing) {
return new MyClass<U>(thing);
class External {
public static <U> MyClass<U>
factoryMakeMyClass(U thing) {
return new MyClass<U>(thing);
class Test {
public static void
test()
// No problem with this line:
MyClass<String> foo = External.factoryMakeMyClass("hi");
// This line gives me an error:
// Type mismatch: cannot convert from MyClass<Object> to MyClass<String>
MyClass<String> bar = MyClass.factoryMakeMyClass("hi");
}Does this code look ok to you? Is it just a problem with my ide (Eclipse 3.1M2)? Any ideas to make it work better?I've been working on essentially the same problem, also with eclipse 3.1M2. A small variation on using the external class is to use a parameterized static inner class. I'm new enough to generics to not make definitive statements but it seems to me that the compiler is not making the correct type inference.
I think the correct (or at least a more explicit) way of invoking your method would be:
MyClass<String> bar = MyClass.<String>factoryMakeMyClass("hi");
See http://www.langer.camelot.de/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ401
See http://www.langer.camelot.de/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ402
Unfortunately, this does not solve the problem in my code. The compiler reports the following error: The method myMethod of raw type MyClass is no more generic; it cannot be parameterized with arguments <T>.
Note that in my code MyClass is most definitely parameterized so the error message is puzzling.
I would like to hear from more people on whether the sample code should definitely work so I would appreciate further comments on whether this an eclipse problem or my (our) misunderstanding of generics. -
Can Static Methods be overridden ?
My question is can static methods be overridden ?
I found this thread [Can Static Method be overridden ?|http://forums.sun.com/thread.jspa?threadID=644752&start=0&tstart=0] .Since it was too old,i have created this new thread.
According to that thread discussion, Java language states that static methods cannot be overridden.
To which kajbj posted a program which did allow overriding of static methods.To quote him :
I filed a bug report on it. I don't know if it's expected behaviour or not, but I expect the compiler to complain if you add @Override to a static method (since it can't be overridden)
/Kaj This is one small program code which i wrote ,which did not allow static methods to be overridden,but no error as such was displayed.
package fundamentals;
class SuperClass
public static String getName()
return "HI,CLASS...SUPER CLASS";
public int getAge()
return 20;
} // END OF SUPER CLASS
public class SubClass extends SuperClass{
public static void main(String[] args)
SubClass objSubClass=new SubClass();
SuperClass objSuperClass=new SubClass();
System.out.println(objSubClass.getName()); // SUB CLASS
System.out.println(objSuperClass.getName()); // SUPER CLASS
System.out.println(objSubClass.getAge()); // SUB CLASS
System.out.println(objSuperClass.getAge()); // SUPER CLASS
public static String getName()
return "HI,CLASS...SUB CLASS";
public int getAge()
return 40;
} // END OF MAIN CLASSWhich gives the O/P :
HI,CLASS...SUB CLASS
HI,CLASS...SUPER CLASS
40
40So,the static method was not overridden.
But ,why was no error message displayed ?
Also when i modify the subclass static method,by removing the static keyword as follows :
public String getName()
return "HI,CLASS...SUB CLASS";
}A Error Message as :
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
This instance method cannot override the static method from SuperClassis displayed.
Why this message is displayed after i remove the static keyword ?
So can we say that Java does not allow static method to be overridden but does not display a compile/run time error when this is done ?
Is this a bug as stated by kajbj ?
Please let me know if i am not clear.If this question has been answered somewhere else in this forum,kindly let me know.
Thank you for your consideration.amtidumpti wrote:
My question is can static methods be overridden ?
I found this thread [Can Static Method be overridden ?|http://forums.sun.com/thread.jspa?threadID=644752&start=0&tstart=0] .Since it was too old,i have created this new thread.
According to that thread discussion, Java language states that static methods cannot be overridden.
To which kajbj posted a program which did allow overriding of static methods.To quote him :
I filed a bug report on it. I don't know if it's expected behaviour or not, but I expect the compiler to complain if you add @Override to a static method (since it can't be overridden)
/Kaj
Sigh! Amti, are you being misleading on purpose? Kaj did not "post a program which did allow overriding of static methods." He posted a program which used the annotation @Override on a static method, like this:
class A {
public static void m() {}
class B extends A {
@Override public static void m() {}
}He wondered why it didn't generate an error message. Well, it does now:
A.java:6: method does not override or implement a method from a supertype
@Override public static void m() {}
^
1 error -
Static methods are class spacific
By mistake First message was posted by me Sorry........
Static methods are class spacific these methods are not overridable by sub class,
But if i write
class Super{
public static void printFunction(){
System.out.println("In Super Class Method");
public class SubClass extends Super{
private static void printFunction(){
System.out.println("In Super Class Method");
}compiler gives me error
c:>javac SubClass.java
SubClass.java:12: printFunction() in SubClass cannot override printFunction() in
Super; attempting to assign weaker access privileges; was public
private static void printFunction(){
1] Why he is trying to override the printFunction() Which is static?
2] if it is not overriding then why this error comes?
Edited by: rahul_p on Apr 28, 2008 7:45 AM -
Static method are not overriden ?
Hi,
as I try to understand java in depth, I come back with this simple question:
public class hiddenVar1 {
boolean aVariable=true;
public static void main (String [] args) {
System.out.println("Hello");
public class hiddenVar2 extends hiddenVar1 {
boolean aVariable;
public hiddenVar2() {
aMethod();
void aMethod() {
aVariable = false;
System.out.println(aVariable);
System.out.println(super.aVariable);
public static void main (String [] args) {
new hiddenVar2();
hiddenVar1.main(new String[2]);
The result is :
false
true
Hello
Conclusion:
the main static method of hiddenVar1 as not been overrided by the main static method in hiddenVar2.
So inheritance does not apply for static method ?
Any explanation ?
Thank's.
JohnFirstly i think there should not be two public classes in only one file it gives compile time error.
Secondly the output is correct.
Static methods cannot be overriden because it will get initialize when u create instance of the class so u r calling
-- new hiddenVar2();
so it calls the constructor in that respective method is called.
And the second line is calling the super class so it calls the main method of that class and prints "hello"
hiddenVar1.main(new String[2]); -
Interesting Qtion: Synchronize a static method
I know that a non-static method and a block can be synchronized.
Can anyone tell me as to what it means to synchronize a static method of a class and how/when is it used. I just tried compiling the code and it gives no compiler/syntactical errors.
it would be helpful if u could take up a simple class example.
Thanks,
NoviceHi,
A good example for using synchronized static methods is the singleton pattern. E.g.
public class Singleton
private Singleton() {}
private static Singleton fgUniqueInstance;
public static synchronized Singleton getInstance()
if (fgUniqueInstance==null) {
fgUniqueInstance = new Singleton();
return fgUniqueInstance;
}If you won't synchronize this class in a multi-threading environment, it could happen, that more than one instance is created.
Andre -
Help to solve the static method....pls.
package readtext;
import java.io.*; // For input & output classes
import java.util.Date; // For the Date class
public class Main {
public Main() {
public static void main(String[] args)
throws IOException{
BufferedReader in = new BufferedReader(
new FileReader("C:/Documents and Settings/seng/Desktop/testfile/txt.txt"));
*use ' ' as a separator, and rearrange back the datastream column
String text;
while ((text = in.readLine()) != null)
int count = 0; // Number of substrings
char separator = ' '; // Substring separator
// Determine the number of substrings
int index = 0;
do
++count; // Increment count of substrings
++index; // Move past last position
index = text.indexOf(separator, index);
while (index != -1);
// Extract the substring into an array
String[] subStr = new String[count]; // Allocate for substrings
index = 0; // Substring start index
int endIndex = 0; // Substring end index
for(int i = 0; i < count; i++)
endIndex = text.indexOf(separator,index); // Find next separator
if(endIndex == -1) // If it is not found
subStr[i] = text.substring(index); // extract to the end
else // otherwise
subStr[i] = text.substring(index, endIndex); // to end index
index = endIndex + 1; // Set start for next cycle
String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
// Directory name
File aFile = new File(dirName, "data.txt");
aFile.createNewFile(); // Now create a new file if necessary
if(!aFile.isFile()) // Verify we have a file
System.out.println("Creating " + aFile.getPath() + " failed.");
return;
BufferedWriter out = new BufferedWriter(new FileWriter(aFile.getPath(), true));
* Display output at data.txt file
// provide initial (X,Y,Z) coordinates for mobiles
out.write("$node_(" + subStr[0] + ") set X_ " + subStr[0] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Y_ " + subStr[1] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Z_ " + subStr[2] +
System.getProperty("line.separator"));
out.flush();
out.close();
package readtext;
import java.io.*; // For input & output classes
import java.util.Date; // For the Date class
public class create_table {
public create_table() {
public static void main(String[] args)
throws IOException{
BufferedReader in = new BufferedReader(
new FileReader("C:/Documents and Settings/seng/Desktop/testfile/txt.txt"));
*use ' ' as a separator, and rearrange back the datastream column
String text;
while ((text = in.readLine()) != null)
substring(subStr); //problem at here
String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
// Directory name
File aFile = new File(dirName, "data.txt");
aFile.createNewFile(); // Now create a new file if necessary
if(!aFile.isFile()) // Verify we have a file
System.out.println("Creating " + aFile.getPath() + " failed.");
return;
BufferedWriter out = new BufferedWriter(new FileWriter(aFile.getPath(), true));
* Display output at data.txt file
// problem at here
// provide initial (X,Y,Z) coordinates for mobiles
out.write("$node_(" + subStr[0] + ") set X_ " + subStr[0] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Y_ " + subStr[1] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Z_ " + subStr[2] +
System.getProperty("line.separator"));
out.flush();
out.close();
static void substring(String[] subStr)
int count = 0; // Number of substrings
char separator = ' '; // Substring separator
String text;
// Determine the number of substrings
int index = 0;
do
++count; // Increment count of substrings
++index; // Move past last position
index = text.indexOf(separator, index);
while (index != -1);
// Extract the substring into an array
subStr = new String[count]; // Allocate for substrings
index = 0; // Substring start index
int endIndex = 0; // Substring end index
for(int i = 0; i < count; i++)
endIndex = text.indexOf(separator,index); // Find next separator
if(endIndex == -1) // If it is not found
subStr[i] = text.substring(index); // extract to the end
else // otherwise
subStr[i] = text.substring(index, endIndex); // to end index
index = endIndex + 1; // Set start for next cycle
*on top is the original code, bottom is after modified
i would like to create a static method for the static void substring(String[] subStr). But when i use the substring() on the main program, the compiler give me error. Is that my substring () created wrongly?? pls help...package readtext;
import java.io.*; // For input & output classes
import java.util.Date; // For the Date class
public class Main {
public Main() {
public static void main(String[] args)
throws IOException{
BufferedReader in = new BufferedReader(
new FileReader("C:/Documents and Settings/seng/Desktop/testfile/txt.txt"));
*use ' ' as a separator, and rearrange back the datastream column
String text;
while ((text = in.readLine()) != null)
int count = 0; // Number of substrings
char separator = ' '; // Substring separator
// Determine the number of substrings
int index = 0;
do
++count; // Increment count of substrings
++index; // Move past last position
index = text.indexOf(separator, index);
while (index != -1);
// Extract the substring into an array
String[] subStr = new String[count]; // Allocate for substrings
index = 0; // Substring start index
int endIndex = 0; // Substring end index
for(int i = 0; i < count; i++)
endIndex = text.indexOf(separator,index); // Find next separator
if(endIndex == -1) // If it is not found
subStr = text.substring(index); // extract to the end
else // otherwise
subStr = text.substring(index, endIndex); // to end index
index = endIndex + 1; // Set start for next cycle
String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
// Directory name
File aFile = new File(dirName, "data.txt");
aFile.createNewFile(); // Now create a new file if necessary
if(!aFile.isFile()) // Verify we have a file
System.out.println("Creating " + aFile.getPath() + " failed.");
return;
BufferedWriter out = new BufferedWriter(new FileWriter(aFile.getPath(), true));
* Display output at data.txt file
// provide initial (X,Y,Z) coordinates for mobiles
out.write("$node_(" + subStr[0] + ") set X_ " + subStr[0] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Y_ " + subStr[1] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Z_ " + subStr[2] +
System.getProperty("line.separator"));
out.flush();
out.close();
package readtext;
import java.io.*; // For input & output classes
import java.util.Date; // For the Date class
public class create_table {
public create_table() {
public static void main(String[] args)
throws IOException{
BufferedReader in = new BufferedReader(
new FileReader("C:/Documents and Settings/seng/Desktop/testfile/txt.txt"));
*use ' ' as a separator, and rearrange back the datastream column
String text;
while ((text = in.readLine()) != null)
String[] subStr;
String[] substring;
int i;
substring(subStr); //PROBLEM: substring in readtext can not apply
String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
// Directory name
File aFile = new File(dirName, "data.txt");
aFile.createNewFile(); // Now create a new file if necessary
if(!aFile.isFile()) // Verify we have a file
System.out.println("Creating " + aFile.getPath() + " failed.");
return;
BufferedWriter out = new BufferedWriter(new FileWriter(aFile.getPath(), true));
* Display output at data.txt file
// provide initial (X,Y,Z) coordinates for mobiles
out.write("$node_(" + subStr[0] + ") set X_ " + subStr[0] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Y_ " + subStr[1] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Z_ " + subStr[2] +
System.getProperty("line.separator"));
out.flush();
out.close();
static void substring(String[] subStr)
int count = 0; // Number of substrings
char separator = ' '; // Substring separator
String text;
// Determine the number of substrings
int index = 0;
do
++count; // Increment count of substrings
++index; // Move past last position
index = text.indexOf(separator, index);
while (index != -1);
// Extract the substring into an array
subStr = new String[count]; // Allocate for substrings
index = 0; // Substring start index
int endIndex = 0; // Substring end index
for(int i = 0; i < count; i++)
endIndex = text.indexOf(separator,index); // Find next separator
if(endIndex == -1) // If it is not found
subStr[i] = text.substring(index); // extract to the end
else // otherwise
subStr[i] = text.substring(index, endIndex); // to end index
index = endIndex + 1; // Set start for next cycle
the problem is here
String text;
while ((text = in.readLine()) != null)
String[] subStr;
String[] substring;
int i;
substring(subStr); //PROBLEM: substring in readtext can not apply
String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
the system say that my substring(subStr[i]) (java.lang.String[])in read.text can not applied to (java.lang.String)...how can i solve for tis problem? is that i have to use for loop to create an array for subStr???
Maybe you are looking for
-
HP PSC 1315, Brother HL-2040 & D-Link DPG321 wireless print server
Hi all...I've had the D-Link wireless print server for awhile, and originally had an ancient Samsung attached to it. Now though, the old Samsung printer is gone and I'm using the print server in my office with my new Brother HL-2040, which connected
-
Photoshop CS4 has quit asking for quality level when 'Saving As'?
Windows Vista 64bit / CS4 v11 I had to reinstall CS4 after a hard drive failure. In the new setup, Photoshop CS4 has quit asking for quality level when 'Saving As'? Help appreciated, IM
-
Reports exported to Excel - Formatting issues
We have two Business Objects Enterprise servers (boxi r2 and boxi r3.1 sp3) running side by side. We find that reports created using boxi r2 and exported to Excel format look fine. When we run the same report and export to excel using boxi r3.1 sp3
-
Can you play home movies from imovie on atv?
Can you use imovie to play home movies through atv? If so, how is it done?
-
I now get a external monitor error after a year
I have been using an external lcd monitor for about a year and this week I started getting an error after I plugged it in for a while. It would work for 1-4 hours and then the external monitor would say that the frequency was not supported. At this p