2016-10-01 4 views
0

본질적으로 내 과제는 2 단어를 취하여 내가 수행 한 두 단어 중 가장 작은 단어를 계산해야하지만 지금은 번호 대신 가장 작은 단어 자체를 참조해야합니다. 나는 If 문이 필요하다고 믿지만, 초기화 할 문자열을 얻을 수 없으며 system.out.println 명령으로 프로그램을 끝내면 콘솔이 까다로워진다.현재 문자열이 포함 된 If 문

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;}; 

또한 Else if 문은 not 문으로 나타나고 첫 번째 문법은 잘못된 식의 시작입니다.

그렇다면 내가 spass를 system.out이라고 부르면 초기화되지 않았다고합니다. 방금 자바를 배우기 시작했는데 전에는 문자열 관련 if 문이 아니라 정수를 처리했습니다.

답변

1

거의 다 왔어. 변수 spass는 최종 else가없는 블록을 사용할 때 초기화해야합니다. 둘 중 하나를 spass = ""로 지정하거나 다른 경우 else를 다음과 같이 변경하십시오.

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); 
+0

내 생각에 당신은 초보자를위한 브라켓없이 코드를 추천 shoudn't =/ –

+0

당신은 소바 맞다. 필요한 중괄호를 추가했습니다. –

0

문제 문은 다음과 같이 formatet 경우 단지 형식화하는 문제가있다 :

if(condition){ 
    do_something; 
}else if(second_condition){ 
    do_something_else; 
}else{ 
    alternative; 
} 
귀하의 경우에는

당신이 세미콜론을 설정하는 경우 몰라요 것 같다;

는이 같은 경우 블록 내부에 세미콜론을 설정해야합니다 :

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