How To Call A Method With Booleans Passing Through Java - java

I am creating an example login app. For some reason when I call the method checkFinal in my main method it is giving me an error. It says that it needs to call the booleans which check the username and the password. Which I did. It says that they can not be passed through. I do not know if this is an pass by value or a pass by reference issue. I have all of the other code working.
import java.util.Scanner;
public class program {
private static Scanner a;
private static String inputusername;
private static Scanner b;
private static String inputpassword;
private static String validusername;
private static String validpassword;
public static void main(String[] args) {
greeting();
questiona();
questionb();
username();
password();
checkOne(validusername, inputusername);
checkTwo(validpassword, inputpassword);
checkFinal(usernamecheck, passwordcheck);
}
public static void greeting() {
System.out.println("Hello!");
System.out.println("Note: All Things Are Case Sensitive!");
}
public static String questiona() {
System.out.println("What Is Your Username?");
a = new Scanner(System.in);
inputusername = a.next();
return inputusername;
}
public static String questionb() {
System.out.println("What Is Your Password");
b = new Scanner(System.in);
inputpassword = b.next();
return inputpassword;
}
public static String username() {
validusername = "username";
return validusername;
}
public static String password() {
validpassword = "password";
return validusername;
}
public static boolean checkOne(String validusername, String inputusername) {
boolean usernamecheck = false;
if (validusername == inputusername) {
usernamecheck = true;
}
return usernamecheck;
}
public static boolean checkTwo(String validpassword, String inputpassword) {
boolean passwordcheck = false;
if (validpassword == inputpassword) {
passwordcheck = true;
}
return passwordcheck;
}
public static boolean checkFinal(boolean usernamecheck, boolean passwordcheck) {
boolean checkFinal = false;
if (usernamecheck == true && passwordcheck == true) {
checkFinal = true;
} else {
checkFinal = false;
}
return checkFinal;
}
public static void compile(String[] args) {
}
public static void server(String[] args) {
}
}

You have to assign these two method results to variables:
boolean usernamecheck = checkOne(validusername, inputusername);
boolean passwordcheck = checkTwo(validpassword, inputpassword);
checkFinal(usernamecheck, passwordcheck);

usernamecheck is a local variable in checkOne
passwordcheck is a local variable in checkTwo
in your main checkFinal(usernamecheck, passwordcheck); the two arguments are not initialised.
it looks like you want to pass the outputs of checkOne and checkTwo as the arguments
public static void main(String[] args) {
greeting();
questiona();
questionb();
username();
password();
boolean usernamecheck = checkOne(validusername, inputusername);
boolean passwordcheck = checkTwo(validpassword, inputpassword);
checkFinal(usernamecheck, passwordcheck);
}

From the other answers, you should get an idea of what you need to do to fix your error. One other way is to shorten your method to call the checkFinal method with the other two methods as parameters so you don't need to create another variable.
checkFinal(checkOne(validusername, inputusername),
checkTwo(validpassword, inputpassword));
A few additional comments about your code:
The method:
public static boolean checkOne(String validusername, String inputusername) {
boolean usernamecheck = false;
if (validusername == inputusername) {
usernamecheck = true;
}
return usernamecheck;
}
can be changed to:
public static boolean checkOne(String validusername, String inputusername) {
boolean usernamecheck = validusername.equals(inputusername);
return usernamecheck;
}
First thing is that you cannot compare two string using ==. Second thing, you don't need to compare boolean == true. When you say if (boolean) it is implied that it means if (boolean == true). Same goes for your other methods as well.
For example:
public static boolean checkFinal(boolean usernamecheck, boolean passwordcheck) {
boolean checkFinal = false;
if (usernamecheck == true && passwordcheck == true) {
checkFinal = true;
} else {
checkFinal = false;
}
return checkFinal;
}
can be written as:
public static boolean checkFinal(boolean usernamecheck, boolean passwordcheck) {
return usernamecheck && passwordcheck;
}

You are not saving the boolean results so that they can be passed to the next step. But you could pass them into checkfinal() like this:
public static void main(String[] args) {
greeting();
inputusername = questiona();
inputpassword = questionb();
/* these 2 are not used and may not be necessary
username();
password();
*/
checkfinal(checkOne(validusername, inputusername),
checkTwo(validpassword, inputpassword));
}
Also, note that you probably should set the global variables with the result of the questiona() and questionb() methods as I did. It will work as you have it but it is a bad habit.

Related

Boolean wrong output

my code:
public class Kuh {
private String name;
private boolean istSatt;
public Kuh(String name, boolean istSatt) {
}
public double gibMilch() {
if (istSatt == true) {
System.out.println(10.0);
return 10.0;
} else {
System.out.println(3.0);
return 3.0;
}
}
public void grasen() {
istSatt = true;
}
public static void main(String[] args) {
Kuh Frida = new Kuh("Frida", true);
Frida.gibMilch();
Frida.grasen();
Frida.gibMilch();
}
}
My problem: I set "istSatt" of the object "Frida" to "true" at creation. So when using the method "gibMilch", it should put out "10". Despite that, it puts out "3", like the boolean would be false, even tho I set it to true. It only puts out "10" after using "grasen".
What did I do wrong?
You are not assigning the constructor parameters to the fields.
public Kuh(String name, boolean istSatt) {
this.name = name;
this.istSatt = istSatt;
}
You need to set your class variable values in your constructor:
public Kuh(String name, boolean istSatt) {
this.name = name;
this.istSatt = istSatt;
}
Here this refers to the class you are instantiating.
Try this instead, as you did not seem to assign to anything on the call to Kuh Frida = new Kuh("Frida", true);
i.e.
public class Kuh {
private String name;
private boolean istSatt;
public Kuh(String name, boolean istSatt) {
this.istSatt=istSatt;
this.name=name;
}
public double gibMilch() {
if (istSatt) {
System.out.println(10.0);
return 10.0;
} else {
System.out.println(3.0);
return 3.0;
}
}
public void grasen() {
istSatt = true;
}
public static void main(String[] args) {
Kuh Frida = new Kuh("Frida", true);
Frida.gibMilch();
Frida.grasen();
Frida.gibMilch();
}
}

How to return the value of a method where the method name is given by a string?

I need to return the value of a method and also I need to print the name of the method including the object by which it is called. For example:
public class FindMethod {
public void accessor(String m){
String amount = "getamount()" ;
String str="";
if(m.equals("Receive(int)"))
str+= "LS."+amount;
System.out.println(str);
}
public static void main(String[] args)
{
FindMethod fm = new FindMethod();
fm.accessor("Receive(int)");
}
}
Result: LS.getamount()
The above program is printing the method name as a string including the object where LS is the object and getamount() is the method of another class LoanApprovalSystem().
But I need to print the integer value that will be returned by the result LS.getamount(). But I have returned LS.getamount() as a string. I am not sure how to return the actual value of LS.getamount() from the string.
Can any one give me some idea that, how can I return the value of the method getamount() which is given by a string?? I mean can I use the string LS.getamount() as a reference to call the method getamount() from the class LoanApprovalSystem()??
The class LoanApprovalSystem() is given below:
public class LoanApprovalSystem {
private static int amount;
private static String risklevel ;
private static boolean approve;
private static boolean message;
private static String result ;
public LoanApprovalSystem(){
}
void initialize(){
amount=0;
risklevel=null;
approve=false;
message=false;
}
public void Receive(int req){
amount = req;
}
public void Asses(int req){
if (req > 1000 && req <= 5000)
{
risklevel = "low";
approve = true;
}
else if (req > 5000 && req <= 10000)
{
risklevel = "high";
}
else
risklevel = " ";
}
public void Approval(int req){
if ((req > 10000) || ((req <= 10000) & getrisklevel() =="high"))
{
approve = false;
}
else if (amount <= 5000 && getrisklevel() == "low")
{
approve = true;
}
}
public void Sendmessage(String risklevel){
if(risklevel == "low")
{
message=true;
//System.out.println(message);
//System.out.println("Loan approved");
}
else
message=false;
}
public void Reply(boolean message, boolean approve){
if(message == true || approve == true)
{
result = ("Loan Approved");
//System.out.println("Loan Approved");
}
else
{
result = ("Loan Rejected");
//System.out.println("Loan Rejected");
}
}
public int getamount(){
return (amount);
}
public String getrisklevel(){
return(risklevel);
}
public boolean getapprove(){
return (approve);
}
public boolean getmessage(){
return(message);
}
public String getresult(){
return (result);
}
public String toString(){
String str = "";
str += "(" +result+ ").";
return str;
}
public static void main(String[] args){
LoanApprovalSystem LS = new LoanApprovalSystem();
TestdataGeneration testdata = new TestdataGeneration();
LS.initialize();
//for(int data:testdata.Testdata())
{
LS.Receive(testdata.thirddata());
LS.Asses(LS.getamount());
LS.Approval(LS.getamount());
LS.Sendmessage(LS.getrisklevel());
LS.Reply(LS.getmessage(), LS.getapprove());
System.out.println("Final state: "+LS);
}
}
}
Use reflection:
http://java.sun.com/docs/books/tutorial/reflect/member/methodInvocation.html
Class<?> c = Class.forName("className");
Method method = c.getDeclaredMethod ("methodName", parameterTypes)
Object o = method.invoke (objectToInvokeOn, paramList)
But usually you don't use reflection. Only if there is no other way to do.
Look for use and danger of reflection here https://softwareengineering.stackexchange.com/questions/123956/why-should-i-use-reflection

Passing arrays between methods

I'm having difficulty passing arrays between methods, I've managed to set them all to false from boolean, and returned the array to the main. However from there I don't know how to pass it to another method, and then later display the boolean true array as "yes" or the boolean false array as "no". My code looks as follows:
import javax.swing.*;
class methodarrays
{
public static void main (String[]param)
{
arrays();
seen();
display();
}
public static boolean[] arrays()
{
boolean [] birds = new boolean [5];
for (int i=0;i<birds.length;i++)
{
birds[i]=false;
}
return birds;
}
public static boolean seen()
{
String quit = "100";
String ans = "";
while(!ans.eqauls(quit))
{
ans=JOptionPane.showInputDialog(null,"Which bird are you reporting? \n 1) Blue Tit 2) Blackbird 3)Robin 4)Wren 5)Greenfinch");
if (ans.equals("1"))
{
birds[0] = true;
return birds[0];
}
else if (ans.equals("2"))
{ birds[1] = true;
return birds[1];
}
else if (ans.equals("3"))
{
birds[2] = true;
return birds[2];
}
else if (ans.equals("3"))
{
birds[2] = true;
return birds[2];
}
else if (ans.equals("4"))
{
birds[3] = true;
return birds[3];
}
else if (ans.equals("5"))
{
birds[4] = true;
return birds[4];
}
}
}
public static void display()
{
JOptionPane.showMessageDialog(null,"Your Garden Watch results are:");
}
}
To give you are starting hand... you can set the result of your arrays method to a local variable in the main method and pass as a argument to the seen. Then you can do the same for the display method.
public static void main (String[]param)
{
boolean[] birds = arrays();
seen(birds);
display(birds);
}
public static boolean[] arrays()
{
...
}
public static boolean seen(boolean[] birds)
{
...
There are plenty of tutorials around the web for this kind thing. Here being one example.
You need to pass it as a parameter or declare a global array.
Passing by parameter:
class methodarrays {
public static void main (String[]param)
{
boolean [] myArray =arrays();
seen(myArray);
display(myArray);
}
public static boolean seen(boolean [] myArrayParam)
{
for (int i=0;i<myArrayParam.length;i++)
{...}
}
public static boolean display(boolean [] myArrayParam)
{
for (int i=0;i<myArrayParam.length;i++)
{...}
}
}
As global array:
class methodarrays {
boolean [] myArray
public static void main (String[]param)
{
myArray = arrays();
seen();
display();
}
public static boolean seen()
{
for (int i=0;i<myArray.length;i++)
{...}
}
public static boolean display()
{
for (int i=0;i<myArray.length;i++)
{...}
}
}
Declare
boolean [] birds = new boolean [5];
as accessible object for all methods within your class.
import javax.swing.*;
class methodarrays
{
private boolean [] birds = new boolean [5]
...
public static boolean[] arrays()
{
for (int i=0;i<birds.length;i++)
{birds[i]=false;
}
return birds;
}
...
}
Here is the implementation mimicing your own:
import javax.swing.JOptionPane;
public class Example {
private static boolean [] birds = new boolean [5];
public static void main (String[]param){
arrays();
seen();
display();
}
public static boolean[] arrays()
{
// Completely unnecessary since values are set to false by default;
for (int i=0;i<birds.length;i++)
{birds[i]=false;
}
return birds;
}
public static void seen(){
String quit = "100";
String ans = "";
while(!ans.equals(quit))
{
ans=JOptionPane.showInputDialog(null,"Which bird are you reporting? \n 1) Blue Tit 2) Blackbird 3)Robin 4)Wren 5)Greenfinch");
if (ans.equals("1"))
{ birds[0] = true;
}
else if (ans.equals("2"))
{ birds[1] = true;
}
else if (ans.equals("3"))
{ birds[2] = true;
}
else if (ans.equals("3"))
{ birds[2] = true;
}
else if (ans.equals("4"))
{ birds[3] = true;
}
else if (ans.equals("5"))
{ birds[4] = true;
}
}
}
public static void display(){
System.out.println("Your results are: ");
System.out.println("Blue Tit: " + birds[0]);
System.out.println("Blackbird: " + birds[1]);
//and so on..
}
}

Assigning a new boolean value to method?

This is what I have:
public static void main(String[] args){
Main main = new Main();
boolean shouldBeTrue = main.shouldBeTrue();
shouldBeTrue = true;
System.out.println(shouldBeTrue);
System.out.println(main.shouldBeTrue());
}//close main
public boolean shouldBeTrue(){
return false;
}
It prints: true false
However I would to assing main.shouldBeTrue() = true;
which does not work.
My goal is to print main.shouldBeTrue() and have it print true instead of false.
Any ideas?
Thank you all so so much!
System.out.println(main.shouldBeTrue());
The above is line is actually calling shouldBeTrue(), which is returning false.
Either pass a boolean variable to a method and return that values.
public boolean shouldBeTrue(boolean myValue) {
return myValue;
}
For main.shouldBeTrue() to return true, the reference it returns should point to a value of true.
public class Main {
private boolean whatDoIReturn = false;
public static void main(String[] args){
Main main = new Main();
Boolean shouldBeTrue = main.shouldBeTrue();
main.shouldBeTrue( shouldBeTrue = true);
System.out.println(shouldBeTrue);
System.out.println(main.shouldBeTrue());
}//close main
public Boolean shouldBeTrue(){
return whatDoIReturn;
}
public void shouldBeTrue(boolean value){
this.whatDoIReturn = value;
}
}
As others have already mentioned, you can not assign a value to a method! What you need to do is maintain a variable that the method will return.
class MyClass
{
private boolean myReturnValue = false; // can be set to either true or false
public boolean shouldBeTrue()
{
return myReturnValue;
}
// Use this method to set the return value.
public void setMyReturnValue( boolean newValue )
{
myReturnValue = newValue;
}
public static void main( String[] args )
{
MyClass myClass = new MyClass();
System.out.println(myClass.shouldBeTrue()); // this will return false, which is currently the defined value of myReturnValue
// Now we will change the return value.
myClass.setMyReturnValue(true);
System.out.println(myClass.shouldBeTrue()); // Now it will return true.
}
}

How to identify an instance of multidimensional object in java?

Is there any alternative way to identify instance of multidimensional object without hardcode on it?
//source
import java.util.LinkedList;
import java.util.List;
public class Test {
public static <T> boolean isPrimitiveWrapper(T p_obj) throws Exception {
if (Number.class.isInstance(p_obj) || Number[].class.isInstance(p_obj)) {
return true;
} else if (Boolean.class.isInstance(p_obj) || Boolean[].class.isInstance(p_obj)) {
return true;
} else if (Character.class.isInstance(p_obj) || Character[].class.isInstance(p_obj)) {
return true;
}
return false;
}
public static void main(String[] args) throws Exception {
Integer[][][] a = {{{0}}, {{1}}, {{0}}};
println(isPrimitiveWrapper(a));
println(isPrimitiveWrapper(a[0]));
println(isPrimitiveWrapper(a[0][0]));
println(isPrimitiveWrapper(a[0][0][0]));
}
public static <T> void println(T p_t) {
System.out.println(p_t);
}
}
//Actual Result
false
false
true
true
//Expected Result
true
true
true
true
Based on the example above, we have no problem to deal with non-array & single dimension array object, but it is fail to identify multidimensional array object.
It is too ugly to hardcode the number of dimension.
There's no standard way to determine, if the class itself is wrapper for primitive type or not, so, you can do something like this:
private static final Set <Class <?>> primitiveWrappers;
static {
Set <Class <?>> tmp = new HashSet<>();
tmp.add (Integer.class);
tmp.add (Boolean.class);
tmp.add (Character.class);
tmp.add (Long.class);
tmp.add (Double.class);
tmp.add (Float.class);
// ... have I forgotten smth?
primitiveWrappers = Collections.unmodifiableSet(tmp);
}
private static boolean isPrimitiveWrapperOrArrayOf(Object o) {
if (o.getClass().isArray())
return isPrimitiveWrapperOrArrayOf(o.getClass().getComponentType());
else
return primitiveWrappers.contains(o.getClass());
}
When you run isPrimitiveWrapperOrArrayOf, the class is being checked if it's array, if it is, we'll check it's component type (for example, that would be Integer[] for Integer[][]) in the same function isPrimitiveWrapperOrArrayOf, so this way we'll come to just SomeClass, which will be checked if it's contained inside hardcoded primitiveWrappers
By the way, you may take a look at Commons Lang, ClassUtils.wrapperToPrimitive may solve your problem.
Try this approach. I guess that's what you want.
But this code looks like some sort of a hack anyway
(which is not necessarily bad).
private static boolean isPrimitiveWrapper(Object obj){
if (obj == null) {
return false;
} else {
String cls = obj.getClass().getCanonicalName();
return "java.lang.Integer".equals(cls) ||
cls.startsWith("java.lang.Integer[]");
}
}
Here is another hack. Both codes should work OK though.
private static boolean isPrimitiveWrapper(Object obj){
if (obj == null) {
return false;
} else {
String cls = obj.getClass().getName();
cls = cls.replaceAll(";", "");
return cls.matches("\\[*L?java\\.lang\\.Integer");
}
}
public class Test {
public static <T> boolean isPrimitiveWrapper(T p_obj) throws Exception {
return isPrimitiveWrapper(p_obj.getClass());
}
public static boolean isPrimitiveWrapper(Class p_obj) throws Exception {
if (Number.class.isAssignableFrom(p_obj)) {
return true;
} else if (Boolean.class.isAssignableFrom(p_obj)) {
return true;
} else if (Character.class.isAssignableFrom(p_obj)) {
return true;
} else if (p_obj.isArray()) {
//To handle multi dimension array
while (p_obj.isArray()) {
p_obj = p_obj.getComponentType();
}
return isPrimitiveWrapper(p_obj);
}
return false;
}
public static boolean isPrimitiveWrapper(boolean p_obj) {
return false;
}
public static boolean isPrimitiveWrapper(byte p_obj) {
return false;
}
public static boolean isPrimitiveWrapper(short p_obj) {
return false;
}
public static boolean isPrimitiveWrapper(float p_obj) {
return false;
}
public static boolean isPrimitiveWrapper(int p_obj) {
return false;
}
public static boolean isPrimitiveWrapper(long p_obj) {
return false;
}
public static boolean isPrimitiveWrapper(char p_obj) {
return false;
}
public static boolean isPrimitiveWrapper(double p_obj) {
return false;
}
public static void main(String[] args) throws Exception {
Integer[][][] a = {{{0}}, {{1}}, {{0}}};
int[][][] b = {{{0}}, {{1}}, {{0}}};
println(isPrimitiveWrapper(a));
println(isPrimitiveWrapper(a[0]));
println(isPrimitiveWrapper(a[0][0]));
println(isPrimitiveWrapper(a[0][0][0]));
println(isPrimitiveWrapper(b));
println(isPrimitiveWrapper(b[0]));
println(isPrimitiveWrapper(b[0][0]));
println(isPrimitiveWrapper(b[0][0][0]));
}
public static <T> void println(T p_t) {
System.out.println(p_t);
}
}

Categories

Resources