have two strings, String1 = hello String2 = world, I want to call a class Hello and send to the two strings. The class should return a boolean value and a string. If the boolean is true it should do the followig:
System.out.println("Hello to you too!");
Can someone help me out with this code?
First, a terminology problem: you cannot "call a class." You can call a method on a class, such as:
someObject.someMethod(string1, string2);
More to the point, you can't return two different values from a method. You could certainly store two different values in the object and return them from different methods, though. Perhaps a class like:
public class Foo {
protected boolean booleanThing;
protected String stringThing;
public void yourMethod(String string1, String string2) {
// Do processing
this.booleanThing = true;
this.stringThing = "Bar";
}
public String getString() {
return this.stringThing;
}
public boolean getBoolean() {
return this.booleanThing;
}
}
Which would be used as:
someObject.yourMethod(string1, string2);
boolean b = someObject.getBoolean();
String s = someObject.getString();
Having said all that, though, this may not at all be the best way to solve your actual problem. Perhaps you can explain better what you're trying to accomplish. Perhaps throwing an Exception is better than trying to return a boolean, or perhaps there's another solution entirely.
The more detail we have, the better.
You should review your definition of classes but for now I'll assume this is what you meant, comment if this isn't what your looking for:
public class Hello {
private final String first;
private final String second;
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "World";
Hello h = new Hello(s1,s2);
if(h.isHelloWorld()) {
System.out.println("Hello to you too!");
}
}
private Hello(String first, String second) {
this.first = first;
this.second = second;
}
private boolean isHelloWorld() {
return (first.equals("Hello") && second.equals("World"));
//If that scares you then do this instead:
/**
if(first.equals("Hello") && second.equals("World") {
return true;
} else { return false; }
**/
}
}
When you run this program it will always print "Hello to you too!", if you change s1 or s2 it won't print anything.
public class Hello{
boolean val = false;
String str = "";
public Hello(String a, String b){
if(a == "hello" && b == "world"){
this.val = true;
this.str = "hello to you too";
}
}
public static void main(String args[]){
String a = "hello";
String b = "world";
Hello hello = new Hello(a,b);
if(hello.val == true)
System.out.println(hello.str);
}
}
Related
I need to write a Java enumeration LetterGrade that represents letter grades A through F, including plus and minus grades.
Now this is my enumeration code:
public enum Grade {
A(true),
A_PLUS(true),
A_MINUS(true),
B(true),
B_PLUS(true),
B_MINUS(true),
C(true),
D(true),
E(true),
F(false);
final private boolean passed;
private Grade(boolean passed) {
this.passed = passed;
}
public boolean isPassing() {
return this.passed;
}
#Override
public String toString() {
final String name = name();
if (name.contains("PLUS")) {
return name.charAt(0) + "+";
}
else if (name.contains("MINUS")) {
return name.charAt(0) + "-";
}
else {
return name;
}
}
What I am confused about is writing the main program. I think it could be quite straightforward but I have no clue on how to start it.
I don't want the whole code. Just a few lines to give me a head start. The rest I will try to figure out on my own.
I imagine you have a Student class that looks like this:
class Student {
protected Grade grade = null;
public Student(Grade g) {
this.grade = g;
}
}
Then you simply add a method in this class calling the isPassing method from your enum:
public boolean isPassing() {
if (this.grade != null)
return this.grade.isPassing();
return false;
}
This is supposing the passed boolean in Grade are correctly set and are invariant.
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;
}
}
I have some very crazy Problem with my java class. The code will explan it:
This is my class:
public class myclass
{
public int myint;
public String mystring;
public myclass()
{
myint = 0;
mystring = "Test";
}
public void setStringInt(String s)
{
s = String.valueOf(myint);
}
public void somefunc()
{
setStringInt(mystring);
}
}
This is a Part of the MainActivity:
//...
public myclass thisismyclass;
public String mysecondstring;
//...
thisismyclass = new myclass();
thisismyclass.myint = 5;
thisismyclass.somefunc();
//...
The Output of thisismyclass.mystring is "Test". Why doesn't the code set it to "5"?
I tried something out. This works:
//...
thisismyclass.myint = 5;
thisismyclass.setStringInt(thisismyclass.mystring);
//...
But why did the other code not work?
mfg
lolxdfly
Edit: I am sorry.. I wrote it wrong.. I my code it was mystring!
s = String.valueOf(myint); within setStringInt does not change the string value in the caller.
This is because the string reference is passed by value, as are all Java function parameters.
Update your following method
public void setStringInt(String s)
{
s = String.valueOf(myint);
}
as follows
public void setStringInt(String s)
{
mystring = String.valueOf(myint);
}
You are not setting mystring value anywhere except in the constructor. Did you mean to write this:
public void setStringInt(String s)
{
mystring = String.valueOf(myint);
}
Java passes parameters by value.
When you pass that String reference into setStringInt and try to set it equal to the String value of the int state, you cannot alter the reference that's passed in. String is immutable, so you don't get what you want.
Your logic is rather convoluted. I can't tell what you want to do here. But here's my best guess:
public class MyClass
{
public int myint;
public String mystring;
public MyClass()
{
myint = 0;
mystring = "Test";
}
public void setStringInt(String s)
{
this.myint = Integer.valueOf(s);
this.mystring = s;
}
public void setStringInt(int i) {
this.myint = i;
this.mystring = Integer.parseInt(i);
}
public void somefunc()
{
setStringInt(myint);
}
}
You should correct this to:
public void somefunc()
{
setStringInt(mystring);
}
But as mentioned above these methods use call by value not call by references hence you won't change the callers variable.
I have this class
public class Model {
private String a;
private String b;
public synchronized String getA() {
return a;
}
public synchronized void setA(String a) {
this.a = a;
}
public synchronized String getB() {
return b;
}
public synchronized void setB(String b) {
this.b = b;
}
}
I try to get the value of a, and I know that by default this variable is initialize to null. But, is it possible that if I call the getA() method, afterwards this variable has the String "null" on it (not null but the String)? So a.equals("null") == true.
public static void main(String[] args) throws ParseException {
Model m = new Model();
String test = m.getA();
m.getA().equals("null");//No Exception occurs
}
And in fact the code where I eval the String is part of an Android Application:
mAirline = (Airline) extras.getSerializable("airline");
#SuppressWarnings("unused")
String test = mAirline.getPhone(); //(1)
String test2 = mAirline.getHref(); //(2)
If I check mAirline in (1) mAirline has it fields in null, but in (2) has some of them to "null" And my method for get is
public synchronized String getPhone() {
return phone;
}
No, with the code you showed us, it's not possible that you automatically get the String "null".
Note, however, that some methods will convert null to "null". The most notable examples are PrintWriter.println() (as in System.out.println()) and String.valueOf().
System.out.println(null);
System.out.println("null".equals(String.valueOf(null)));
These line will print null (i.e. the 4 characters) and true respectively
Maybe just:
private String a = "null";
Why don't you just check if the string is not null?
Model m = new Model();
String test = m.getA();
if(test==null) {
//is null
} else {
//is not null
}
You can also alter the getter method, so it returns your default value if the field is not initialized:
public class Model {
private String a;
public synchronized String getA() {
//if a is null, return "null", else return a
return a==null?"null":a;
}
}
The method String.valueOf() returns "null" if the argument is null or the argument itself if it is a String that is different from null.
Model m = new Model();
String test = m.getA();
if (String.valueOf(a).equals("null")) //No Exception occurs
but this is kind of cryptic, pretty hard to understand what you want to do.
Check for null directly, much easier to read:
Model m = new Model();
String test = m.getA();
if (a == null || a.equals("null")) //No Exception occurs
So you mean, the value of a is the string null, rather than a pointer with value null? That well never happen, unless you set it like that using setA("null");.
If you want a to be initialized as null, write a constructor:
public Model() {
a = "null";
}
This will fix the problem for you. If the variable is null you will return "null" and if not you will return the value.
public class Model {
private String a;
private String b;
public synchronized String getA() {
return (if (a ==null) ? "null" : a);
}
public synchronized void setA(String a) {
this.a = a;
}
public synchronized String getB() {
return (if (b ==null) ? "null" : b);
}
public synchronized void setB(String b) {
this.b = b;
}
}
I wrote this code but I am still new in JUnit and have no idea of testing equal and equal2 method. Below is the code I wrote. My object in this code is to see if the fname is equal to lname using equal method and by using equal2 to check if fname is same as fname(it self) maybe my code have errors too.
public class EqualMethods {
/**
* #param args
*/
private String fname;
private String lname;
public EqualMethods(String fl)
{
fname = fl;
}
public EqualMethods(String f, String l)
{
fname = f;
lname = l;
}
public String getFname() {
return fname;
}
public String getLname()
{
return lname;
}
public void setLname(String lname)
{
this.lname = lname;
}
public void setFname(String fname) {
this.fname = fname;
}
public int equal(EqualMethods name)
{
if(fname == name.getFname() && lname == name.getLname())
{
return 1;
}
else
{
return 0;
}
}
public int equal2(Object o)
{
if(o.getClass() == EqualMethods.class )
{
EqualMethods e = (EqualMethods) o;
if(this.fname.equals(e.fname))
{
return 1;
}
return 0;
}
return 0;
}
public String toString()
{
return (" My first name is: "+fname + " Last name is: " + lname);
}
The objective is to create a Junit test case to equal and equal2 as the test case i created does not provide a proper output.Here is the JUnit test case I wrote but I cant make my method static though how to get around it?
public class EqualMethodsTest extends TestCase{
#Test
public void testEqual2() {
String name = "goma";
int ret = 1;
int ans ;
ans= EqualMethods.equal2(name);
assertEquals(ret,ans);
}
}
You need to create instances of EqualMethods to compare them. Like this:
public class EqualMethodsTest extends TestCase{
#Test
public void testEqual2() {
assertEquals(1, new EqualMethods("goma").equal(new EqualMethods("goma")));
}
}
Edit:
A few comments about the code:
If you work with an actual version of junit you don't need to extend TestCase and the name of the test method does not need to start with "test".
Naming a method "equal" or "equal2" might not be the best idea ... in Object, the root of all other objects, there is already a method with the name "equals" ... might be confusing.
Most probably fname == name.getFname() does not what you want to accomplish. This compares the references to two strings, not the content. Strings are objects and are to be compared like this string1.equals(string2).
This is probably a better way to do this:
private EqualsMethods a;
private EqualsMethods b;
#Before
public void before {
a = EqualsMethods("a);
b = EqualsMethods("b);
}
#Test
public void equalTest() {
assertTrue(a.equal(b));
}
#Test
public void equal2Test() {
assertTrue(a.equal2(b));
}
I still think what your doing is a bit odd though, you should probably have two classes with the same attributes and methods - each with an equals method. Then you should created tests for both those classes. Not sure what your trying to achieve here.