M Quade
M Quade

Reputation: 3

Current If statement involving String

Essentially my assignment is supposed to take 2 words, calculate the smallest of the two which I have done, but now I need to reference the smallest word itself instead of the number. Which I believe requires an If statement, but I cannot get my String to initialize and the console gets picky when I end the program with the system.out.println command.

Scanner scan = new Scanner(system.In); 
System.out.println(" Input first password ");
String pass1 = scan.nextLine();
Int pass1l = pass1.length();
System.out.println(" input second password "); 
String pass2 = scan.nextLine();
Int pass2l = pass2.length();
Int spassl = Math.min(pass1l,pass2l);
// problematic part here. 
String spass;
If (pass1l > pass2l){ spass = pass2}
else if (pass1l < pass2l) {spass = pass1}
else if (pass1l == pass2l) {spass = null;};

Also the Else if statements come up as not statements and the first is an illegal start of an expression.

Then if I fix those I call spass with system.out and it says it's not initialized. I just started learning basic Java, I've used processing before but not for String related if statements, only integers.

Upvotes: 0

Views: 60

Answers (2)

Ganesh S
Ganesh S

Reputation: 520

You are almost there. the variable spass needs to be initialized as you are using if blocks without final else. Either you give spass="" or change final else if to else as below.

    Scanner scan = new Scanner(System.in);
    System.out.println(" Input first password ");
    String pass1 = scan.nextLine();
    System.out.println(" input second password ");
    String pass2 = scan.nextLine();
    // problematic part here.
    String spass;
    if (pass1.length() > pass2.length()) {
        spass = pass2;
    } else if (pass1.length() < pass2.length()) {
        spass = pass1;
    } else {
        spass = null;
    }
    System.out.println("result: " + spass);

Upvotes: 1

Mein Name
Mein Name

Reputation: 527

your problem is just a formating problem, if statements are formatet like this:

if(condition){
    do_something;
}else if( second_condition ){
    do_something_else;
}else{
    alternative;
}

In your case it seems that you dont know where to set semicolons ;

You have to set semicolons inside the if block like this:

String spass;
If (pass1l > pass2l){ 
    //Here semicolon
    spass = pass2;
} else if (pass1l < pass2l) {
    //Here semicolon
    spass = pass1;
}else if (pass1l == pass2l) {
    //Here semicolon
    spass = null;
}
//No semicolon at the end of the if-else-statement

Upvotes: 0

Related Questions