Is there a way to initlalize a static field with a method? - java

How can I initialise an array of Strings within a class by using a method?
private static String[] strNrs2 =
{"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
private static String[] colo = arr();
private String[] arr(){
String[] str99 = new String[strNrs2.length];
for (int i = 0; i<strNrs2.length;i++){
str99[i]= new StringBuilder(strNrs2[i]).reverse().toString();
}
return str99;
}
I want this :
private static String[] strNrs2 =
{"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
To look like this:
private static String[] strNrs =
{"oreZ","enO","owT","eerhT","ruoF","eviF","xiS","neveS","thgiE","eniN"};
But I want to do it only once. Because I plan to loop through the method that will use the array, million of times. Therefore it will decrease my runtime speed considerably.
Full code:
public class IntToStr {
private static String[] strNrs2 = {"Zero","One","Two","Three","Four","Five","Six",
"Seven","Eight","Nine"};
public static String intToStr(int nr) {
StringBuilder str = new StringBuilder("");
while (nr>0) {
int pop = nr%10;
nr= nr/10;
str.append(new StringBuilder(strNrs2[pop]).reverse().toString());
//By using this str.append(strNrs[pop]); runtime will increase considerably.
}
return str.reverse().toString();
}
public static void main(String[] args) {
for (int i = 0; i<10000000;i++)
intToStr(5555555);
System.out.println("Finished");
}
}

The following array initialization:
private static String[] colo = arr();
doesn't work because arr() is a non-static method, so it can't be called in the static context of initializing a static variable.
You'll have to make arr() a static method in order for that static array initialization to work:
private static String[] arr() {
...
}

Related

Can't input data in my array

Keeps saying "incompatible types String[] cannot be converted to string"
do I have something wrong?
public class TimeCard {
private int employeeNum;
private String[] clockInTimes = new String[14];
private String[] clockOutTimes = new String[14];
private float[] decimalClockIn = new float[14];
private float[] decimalClockOut = new float[14];
private float[] timeElapsed = new float[14];
public String getClockInTimes()
{ //im getting the error here
return clockInTimes;
}
public void setClockInTimes(String[] value)
{ //getting the error here
clockInTimes = value;
}
}
Update now it wont let me enter a string within the array.
I'm trying to do it like this:
public class TestTimeCard {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
TimeCard josue = new TimeCard();
System.out.println("Enter Monday Clock In Times:");
josue.setClockInTimes(reader.next());
}
}
You are returning array but return type is defined as just string.
public String[] getClockInTimes()
{ //im getting the error here
return clockInTimes;
}

The blank final field name may not have been initialized error

Following code is giving compilation error mentioned below at line 1
The blank final field name may not have been initialized
My question is why is this error there as i have already initialized field in its constructor.
public class Test1 {
private final String name;
public Test1() {
name = "abc";
}
#SuppressWarnings("rawtypes")
private final Function fs = n -> {
System.out.println(this.name);// Line 1
return n;
};
public static void main(String[] args) {
new Test1();
}
}
During object creation, instance initialisers (i.e. assignments to instance variables and initialisation blocks) get executed before a constructor runs and hence, they would need the values to be initialised by then. Following should work:
public class Test1 {
private final String name;
public Test1() {
name = "abc";
fs = n -> {
System.out.println(this.name);// Line 1
return n;
};
}
#SuppressWarnings("rawtypes")
private final Function fs;
public static void main(String[] args) {
new Test1();
}
}

generate, append and send string to another class using LOOP IN Java

I want to pass a series of the same string using LOOP from a method in Class A to method in Class B. Below is my newbie code but unable to deliver. Thanks!
import java.util.UUID;
public class ClassA {
public String ClassAMethod (String data){
String theString;
StringBuilder builder = new StringBuilder();
ClassA classA = new ClassA();
int k=0;
do {
k++;
String generated = classA.generateString(data);
builder.append(generated);
theString=builder.toString();theString+=theString;
return theString;
} while(k<5);
}
public String generateString(String genText ){
genText = (UUID.randomUUID().toString());
return genText;
}
}
public class ClassB {
private static String data;
public static void main(String arg[]) {
ClassA classA = new ClassA();
String sentString = classA.ClassAMethod(data);
System.out.println(sentString);
}
}
The main error is that you are returning from within your loop, what you want to do is returning after it.
Also as you are in classA you should not instantiate another classA object.
Try
public String ClassAMethod (){
StringBuilder builder = new StringBuilder();
int k=0;
do {
k++;
String generated = this.generateString();
builder.append(generated);
} while(k<5);
return builder.toString ();
}
Edit
As #Andreas metions above, generateString() does not need to be passed any arguments so change to
public String generateString(){
return (UUID.randomUUID().toString());
}

Passing an Array to Different Class...Netbeans Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
A.java
public Class A
{
String a,b;
public static void setArray(String[] array)//This is where i want the array to come
{
array[0]=a;
array[1]=b
}
}
B.java
public class B
{
String[] arr1 = new String[2];
arr1[0]="hello";
arr1[2]="world";
public static void main(String[] args)
{
A a = new A();
a.setArray(arr1);//This is from where i send the array
}
}
I am trying to send an array from one class to another class
I've edited your code a bit. Your main problem was in class A, where you were assigning values backwards. See the updated class A. I also added a constructor to your class, but this isn't strictly necessary.
public Class A {
String a,b;
// A public method with no return value
// and the same name as the class is a "class constructor"
// This is called when creating new A()
public A(String[] array)
{
setArray(array) // We will simply call setArray from here.
}
private void setArray(String[] array)
{
// Make sure you assign a to array[0],
// and not assign array[0] to a (which will clear this array)
a = array[0];
b = array[1];
}
}
public class B {
String[] arr1 = new String[2];
arr1[0]="hello";
arr1[2]="world";
// A a; // You can even store your A here for later use.
public static void main(String[] args)
{
A a = new A(arr1); // Pass arr1 to constructor when creating new A()
}
}
You were getting a NULL value because your String variables in class A were not initialized.
In class A you need to remove the STATIC from the method, and initialize the String a and b with something, like this:
public class A {
String a = "bye";
String b = "bye";
public void setArray(String[] array) {
array[0] = a;
array[1] = b;
}
}
In class B you should add STATIC to your array (you cannot reference a non-static variable within a static method).
public class B {
static String[] arr1 = {"hello", "world"};
public static void main(String[] args) {
A a = new A();
a.setArray(arr1);//This is from where i send the array
System.out.println(arr1[0] + " " + arr1[1]);
}
}
Also, if you want to initialize something the way you did (outside a method):
String[] arr1 = new String[2];
arr1[0]="hello";
arr1[2]="world";
you have to put the initialization within a block, like this:
String[] arr1 = new String[2];
{
arr1[0] = "hello";
arr1[2] = "world";
}
Hope this helps you

Why can I not make an instance of a local Java class in side of a Java WebMethods Services?

I need to be able to create an instance of the following class in my web Services Method and for some reason there is an error.
Question: Why would I not be able to declare and instance of my class in my Java WEBServices?
**GetTheFileListClass FindArrayListOfFiles = new GetTheFileListClass(fileName);**
Error:
The source was saved, but was not compiled due to the following errors:
C:\SoftwareAG\IntegrationServer\packages\DssAccessBackup\code\source\DssAccessBackup\services\flow.java:48: non-static variable this cannot be referenced from a static context
GetTheFileListClass FindArrayListOfFiles = new GetTheFileListClass(fileName);
1 error
Code:
public final class ReturnListOfValidFileNames_SVC
{
/**
* The primary method for the Java service
*
* #param pipeline
* The IData pipeline
* #throws ServiceException
*/
public static final void ReturnListOfValidFileNames(IData pipeline)
throws ServiceException {
IDataCursor pipelineCursor = pipeline.getCursor();
String fileName = IDataUtil.getString(pipelineCursor,"FileName");
ArrayList<String> listOfFileName = new ArrayList<String>();
//This will get the file list and set it to the local parameter for the Service
**GetTheFileListClass FindArrayListOfFiles = new GetTheFileListClass(fileName);**
listOfFileName = FindArrayListOfFiles.getMyFileList();
IDataUtil.put( pipelineCursor,"ListOfFileNames",listOfFileName.toArray());
pipelineCursor.destroy();
}
// --- <<IS-BEGIN-SHARED-SOURCE-AREA>> ---
public class GetTheFileListClass {
String fileName = new String();
ArrayList<String> MyFileList = new ArrayList<String>();
String InputFile = new String();
GetTheFileListClass(String workFile){
setInputFile(workFile);
}
public void setMyFileList(ArrayList<String> myList, String newFileValueToAdd) {
myList.add(newFileValueToAdd);
}
public ArrayList<String> getMyFileList() {
return MyFileList;
}
public void setInputFile(String wFile) {
fileName = wFile;
}
public String getInputFile(){
return fileName;
}
private String returnFileName(String a) {
String matchEqualSign = "=";
String returnFile = new String();
int index = 0;
index = a.indexOf(matchEqualSign,index);
index++;
while (a.charAt(index) != ' ' && a.charAt(index) != -1) {
returnFile += a.charAt(index);
//System.out.println(returnFile);
index++;
}
return returnFile;
}
private void locatedFileName(String s, String FoundFile, ArrayList<String> myFileListParm) {
final String REGEX = ("(?i)\\./\\s+ADD\\s+NAME\\s*=");
Pattern validStringPattern = Pattern.compile(REGEX);
Matcher validRegMatch = validStringPattern.matcher(s);
boolean wasValidRegMatched = validRegMatch.find();
if (wasValidRegMatched) {
FoundFile = returnFileName(s); //OUTPUT variable should go here
setMyFileList(myFileListParm,FoundFile);
}
}
//This is the methods that needs to be called from the main method
private void testReadTextFile() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String FileLine = null;
while ((FileLine = reader.readLine()) != null) {
locatedFileName(FileLine,fileName,MyFileList); //test to see if the "./ Add name=" is found in any of the strings
}
}
private void printArrayFileList(ArrayList<String> myList) {
for (String myIndexFileListVariable : myList) {
System.out.println("File Name: " + myIndexFileListVariable);
}
}
}
// --- <<IS-END-SHARED-SOURCE-AREA>> ---
}
your inner class is not static, try
public static class GetTheFileListClass { ....
The rules of scope still apply, even though GetTheFileListClass is (a) a class and is (b) public. Because it is declared inside of ReturnListOfValidFileNames_SVC, that is its enclosing class, so any non-static reference to it must follow the rules of scope.
So you have two options (I'm using main to simulate your static method):
Declare the inner class static:
public final class Outer {
public static void main(String[] args) {
Inner inner = new Inner ();
inner.doIt();
}
public static class Inner {
public void doIt() {
System.out.println("Do it");
}
}
}
OR
Within your static method, create an instance of the enclosing class and use the new operator on it like this
public final class Outer {
public static void main(String[] args) {
Outer outer = new Outer();// Now we have an enclosing instance!
Inner inner = outer.new Inner ();
inner.doIt();
}
public class Inner {
public void doIt() {
System.out.println("Do it");
}
}
}
Have fun!

Categories