generate, append and send string to another class using LOOP IN Java - 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());
}

Related

Is it possible to update a reference in a method?

I have asked this question here. I will try to make this one more specific.
class Example {
public static void main(String[] args) {
A a = null;
load(a);
System.out.println(a.toString());
// outcome is null pointer exception
}
private static void load(A a) {
a = new A();
}
}
class A {
public void String toString() {
return "Hello, world!"
}
}
So, does it possible to update a reference in a method? For some reason I need to do this. The reasons can be seen at above linked page.
Yes, it's possible if you define the parameter as A[] i.e. load(A[] a) and then in the method you update the element at position 0 in that array i.e. a[0] = new A(). Otherwise, it's not possible as Java is pass by value. I often use this workaround.
EXAMPLE 1:
class Example {
public static void main(String[] args) {
A[] a = new A[1];
a[0] = new A("outer");
System.out.println(a[0].toString());
load(a);
System.out.println(a[0].toString());
}
private static void load(A[] a) {
a[0] = new A("inner");
}
}
class A {
private String name;
public A(String nm){
name = nm;
}
public String toString() {
return "My name is: " + name;
}
}
EXAMPLE 2:
class Example {
public static void main(String[] args) {
A[] a = new A[1];
a[0] = null; // not needed, it is null anyway
load(a);
System.out.println(a[0].toString());
}
private static void load(A[] a) {
a[0] = new A("inner");
}
}
class A {
private String name;
public A(String nm){
name = nm;
}
public String toString() {
return "My name is: " + name;
}
}
NOTE: In fact, instead of an A[] you can use any wrapper object (an object which contains in itself a reference to an A object). The A[] a is just one such example. In this case a[0] is that reference to an A object. I just think that using an A[] is the easiest (most straightforward) way of achieving this.
As already pointed by other java is pass-by-value.You need something like pointer in C with the object location address so that you can modify that particular address value.As an alternate to pointer you can use array.Example
class Example {
public static void main(String[] args) {
A[] aArray=new A[1];
load(aArray);
System.out.println(aArray[0].toString());
// outcome is Hello, world!
}
private static void load(A[] aArray2) {
aArray2[0] = new A();
}
}
class A {
public String toString() {
return "Hello, world!";
}
}
You could just have:
public static void main(String[] args) {
A a = load();
}
private static A load() {
return new A();
}
No you can't.
In java everything is passed as value not as reference.
I came out with this. Perfectly satisfied my need and looks nice.
class A {
private A reference;
private String name;
public A() {
reference = this;
}
public void setReference(A ref) {
reference = ref;
}
public void setName(String name) {
reference.name = name;
}
public String getName() {
return reference.name;
}
}

Trying to call a Class in an Instance Variable

Add an instance variable called currentPhrase to hold the current round’s Phrase
My error message is "Phrase cannot be resolved to a variable"
I feel like it has something to do with new String()? maybe.
Or could it be something like Phrase phrase = new Phrase();
package edu.htc.java1.phrasegame;
import edu.htc.java1.phrasegame.model.*;
public class PhraseGameController {
public void currentPhrase() {
String p = new String();
p = Phrase;
}
}
and
package edu.htc.java1.phrasegame.model;
import java.util.ArrayList;
public class Phrase {
public void setPhrase(String phrase) {
this.phrase = phrase;
}
private String phrase;
public Phrase(String phrase) {
phrase = phrase.toUpperCase();
for(char c : phrase.toCharArray()) {
letters.add(new Letter(c));
}
}
public String getPhrase() {
return phrase;
}
ArrayList<Letter> letters = new ArrayList<Letter>();
public ArrayList<Letter> getLetters() {
return letters;
}
public boolean guessLetter(char c) {
// convert received character to letter
Letter letter = new Letter(c);
// loop through your list of letters
for(Letter l : letters) {
// if list of letters contains same letter as the one you received then return true
if(l.getLetter() == letter.getLetter()) {
letter.unhide();
// return true;
}
}
// we did not find the letter, so we return false
return false;
}
}
An instance variable is a property of the class.
public class MyClass {
private static String classVariable;
private String instanceVariable;
public String instanceMethod () {
String localVariable = "hey";
}
public static String classMethod {
}
}
To instantiate a variable you have to use the new keyword:
SomeClass someInstance = new SomeClass();
Or if you use generics:
List<SomeType> myList = new ArrayList<SomeType>();
So in your case it should be:
public class PhraseGameController {
private Phrase p = new Phrase();
}
I think that first you will have to import this package:
edu.htc.java1.phrasegame.model;
into your PhraseGameController class. by adding this below the package declaration, but above the class declaration:
import edu.htc.java1.phrasegame.model.*;
Then you will make a new variable in that class called currentPhrase like so:
private Phrase currentPhrase;
What you do with it from there is sort of beyond the scope of your question.

Java CompareTO method issues

I am trying to sort out a simple list of students mark with a simple java program however I am getting
Exception in thread "main" java.lang.ClassCastException: Student cannot be cast to java.lang.Comparable
public class Student {
public String name;
public int mark;
public Student(String name, int mark){
this.name=name;
this.mark=mark;
}
public int compareTo(Student o){
return this.mark-o.mark;
}
public String toString(){
String s = "Name: "+name+"\nMark: "+mark+"\n";
return s;
}
public static void main(String[] args) {
Student Class[] = new Student[9];
Class[0] = new Student("Henry",100);
Class[1] = new Student("Alex", 10);
Class[2] = new Student("Danielle",100);
Class[3] = new Student("Luke",10);
Class[4] = new Student("Bob",59);
Class[5] = new Student("Greg",76);
Class[6] = new Student("Cass",43);
Class[7] = new Student("Leg",12);
Class[8] = new Student("Bobe",13);
Arrays.sort(Class);
for(int i = 0;i<Class.length;i++){
System.out.println(Class[i]);
Your Student class must implement the Comparable interface in order to use Arrays#sort passing Student[] array. The fact that your class currently have a compareTo method doesn't mean it implements this interface, you have to declare this:
public class Student implements Comparable<Student> {
//class definition...
}
Make your Student class implement Comparable<Student>. The compareTo() method doesn't work on it's own while sorting.
Also, Class doesn't look like a very good variable name. How about using students? Also, I see an issue in your compareTo method:
public int compareTo(Student o){
return this.mark-o.mark;
}
Never compare on the result of subtraction of 2 integers, or longs. The result might overflow. Rather use Integer.compare(int, int) method.
Also, get rid of public fields. Make them private, and provide public getters to access them.
public class Fawaz1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// تجربه
String SS[]=new String[6];
double GG[]=new double[6];
SS[0]="fawaz";
SS[1]="ahmd";
SS[2]="hmd";
SS[3]="fos";
SS[4]="raid";
SS[5]="majd";
GG[0]=3.94;
GG[1]=2.50;
GG[2]=2.95;
GG[3]=4.92;
GG[4]=3.0;
GG[5]=3.78;
int i;
for (i=0; i<3; i++){
System.out.print(SS[i]+"\t"+GG[i]+"\t");
if (GG[i]>=4.75)
{System.out.println("A+");}
else if(GG[i]>=4.50){
System.out.println("A");
} else if(GG[i]>=3.70){
System.out.println("B+");
}else if(GG[i]>=3.59){
System.out.println("B");
}else if(GG[i]>=2.78){
System.out.println("C+");
}else if(GG[i]>=2.55){
System.out.println("C");
}else if(GG[i]>=1.52){
System.out.println("D");
}else if(GG[i]>=1.10){
System.out.println("F");
}
}
}
}

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!

tagging methods and calling them from a client object by tag

I have been trying to figure out a way to tag several methods from my base class, so that a client class can call them by tag. The example code is:
public class Base {
public void method1(){
..change state of base class
}
public void method2(){
..change state of base class
}
public void method3(){
..change state of base class
}
}
A client class from a main() method will call each method of Base through a random instruction sequence:
public static void main(String[] args) {
String sequence = "ABCAABBBABACCACC"
Base aBase = new Base();
for (int i = 0; i < sequence.length(); i++){
char temp = sequence.charAt(i);
switch(temp){
case 'A':{aBase.method1(); break;}
case 'B':{aBase.method2(); break;}
case 'C':{aBase.method3(); break;} }
}
System.out.println(aBase.getState());
}
Now I wish to get rid of the switch statement altogether from the Client object. I am aware of the technique to replace switch by polymorphism, but would like to avoid creating a set of new classes. I was hoping to simply store those methods in an appropriate data structure and somehow tag them with a matching character from the sequence.
A map could easily store objects with value/key pairs which could do the job, (as I did here), or the command pattern, but since I don't want to replace those methods with objects, is there a different way perhaps, to store methods and have a client selectively call them?
Any advice is appreciated
Something like this?
public class Base {
private final Map<Character, Method> methods = new HashMap<Character, Method>();
public Base() throws SecurityException, NoSuchMethodException {
methods.put('A', getClass().getMethod("method1"));
methods.put('B', getClass().getMethod("method2"));
methods.put('C', getClass().getMethod("method3"));
}
public Method getMethod(char c) {
return methods.get(c);
}
public void method1() {}
public void method2() {}
public void method3() {}
}
and then
public static void main(String[] args) throws Exception {
String sequence = "ABCAABBBABACCACC";
Base aBase = new Base();
for (int i = 0; i < sequence.length(); i++) {
char temp = sequence.charAt(i);
aBase.getMethod(temp).invoke(aBase);
}
}
I would use annotations on the methods in question, allowing it to be marked as a "tagged method", and providing the tag string to use for that method.
From that point the implementation gets simpler; you can use reflection to iterate over a class' methods and inspect their annotations; perhaps do this statically at startup and populate a mapping from tag string to java.lang.reflect.Method.
Then when processing the command string, invoke the methods that correspond to each tag.
Edit: some example code:
import java.lang.annotation.*;
#Retention(RetentionPolicy.RUNTIME)
#interface TaggedMethod {
String tag();
}
Then in the base class:
public class Base {
#TaggedMethod(tag = "A")
public void method1(){
..change state of base class
}
#TaggedMethod(tag = "B")
public void method2(){
..change state of base class
}
#TaggedMethod(tag = "C")
public void method3(){
..change state of base class
}
}
...and in the client:
private static final Map<String, Method> taggedMethods = new HashMap<String, Method>();
// Set up the tag mapping
static
{
for (Method m : Base.class.getDeclaredMethods())
{
TaggedMethod annotation = m.getAnnotation(TaggedMethod.class)
if (annotation != null)
{
taggedMethods.put(annotation.tag(), m);
}
}
}
so that you can access this as:
public static void main(String[] args) throws Exception
{
String sequence = "ABCAABBBABACCACC"
Base aBase = new Base();
for (int i = 0; i < sequence.length(); i++)
{
String temp = sequence.substring(i,1);
Method method = taggedMethods.get(temp);
if (method != null)
{
// Error handling of invocation exceptions not included
method.invoke(aBase);
}
else
{
// Unrecognised tag - handle however
}
}
System.out.println(aBase.getState());
}
This code hasn't been compiled or tested, by the way... :-)
You could use Attributes for this, in C#. For Java, use annotations. Derive a class from the Attribute class, say, TagAttribute, and apply the attribute to the methods.
[global::System.AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class TagAttribute : Attribute
{
public TagAttribute(char value)
{
this.value = value;
}
private char value;
public char Value
{
get { return value; }
}
}
Apply the attribute to the methods:
public class MyClass
{
[Tag('A')]
public void Method1()
{ Console.Write("a"); }
[Tag('B')]
public void Method2()
{ Console.Write("b"); }
[Tag('C')]
public void Method3()
{ Console.Write("c"); }
}
Invoke the methods using reflection:
private static void CallTaggedMethod(MyClass instance, char value)
{
MethodInfo methodToCall = null;
// From the MyClass type...
Type t = typeof(MyClass);
// ...get all methods.
MethodInfo[] methods = t.GetMethods();
// For each method...
foreach (MethodInfo mi in methods)
{
// ...find all TagAttributes applied to it.
TagAttribute[] attributes = (TagAttribute[])mi.GetCustomAttributes(typeof(TagAttribute), true);
if (attributes.Length == 0)
// No attributes, continue.
continue;
// We assume that at most one attribute is applied to each method.
TagAttribute attr = attributes[0];
if (attr.Value == value)
{
// The values match, so we call this method.
methodToCall = mi;
break;
}
}
if (methodToCall == null)
throw new InvalidOperationException("No method to call.");
object result = methodToCall.Invoke(
// Instance object
instance,
// Arguments
new object[0]);
// 'result' now contains the return value.
// It is ignored here.
}
Call the CallTaggedMethod from your Main method:
static void Main(string[] args)
{
String sequence = "ABCAABBBABACCACC";
MyClass inst = new MyClass();
foreach(char c in sequence)
CallTaggedMethod(inst, c);
// The rest.
Console.ReadLine();
}
Here is my annotations Approach. You don't even need a Map of tags to methods if you are using annotations, just iterate over the sequence and lookup the method for that tag using reflection.
import java.lang.annotation.*;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface Tag {
char value();
}
then:
public class Base {
StringBuilder state = new StringBuilder();
#Tag('A')
public void method1(){
state.append("1");
}
#Tag('B')
public void method2(){
state.append("2");
}
#Tag('C')
public void method3(){
state.append("3");
}
public String getState() {
return state.toString();
}
}
then
public final class TagRunner {
private TagRunner() {
super();
}
public static void main(String[] args) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
Base b = new Base();
run(b, "ABCAABBBABACCACC");
System.out.println(b.getState());
}
private static <T> void run(T type, String sequence) throws
IllegalArgumentException, IllegalAccessException, InvocationTargetException {
CharacterIterator it = new StringCharacterIterator(sequence);
Class<?> taggedClass = type.getClass();
for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
getMethodForCharacter(taggedClass, c).invoke(type);
}
}
private static Method getMethodForCharacter(Class<?> taggedClass, char c) {
for (Method m : taggedClass.getDeclaredMethods()) {
if (m.isAnnotationPresent(Tag.class)){
char value = m.getAnnotation(Tag.class).value();
if (c == value) {
return m;
}
}
}
//If we get here, there are no methods tagged with this character
return null;
}
}

Categories