2017-10-05 6 views
0
이 코드로 연주했다

...조건에 while 루프에서 둥근 괄호 안의 내용을 인쇄 할 수 있습니까?

import java.util.Scanner; 

class plus 
{ 
    public static void main(String[] args) 
    { 
     Scanner scan = new Scanner(System.in); 

     do{ 
      System.out.print("Youe Value: "); 
      long tobe = scan.nextLong(); 

      int total = 0; 

      String parsed = String.valueOf(tobe); 

      for(int i = 0; i < parsed.length(); i++) { 
       total += Character.getNumericValue(parsed.charAt(i)); 
      } 

      System.out.println("Your Result: "+ total); 
     } 
     while(scan.hasNextLong()); 
    } 
} 

출력은 다음 번호를 묻는 메시지를 처리하고 결과로 인쇄해야합니다.

후 다시 인 경우에 다른 입력을 가진 integer(long)

하지만 while 루프 조건 scan.hasnextLong 입력 자체 프로세스를 취하여 출력 this-

사용자 값 같다 : 내 결과 : N

하지만 예상 출력 this-

귀하의 가치있는 것과 같다 E : m

귀하의 결과 : n은 처음으로 같은

. tobe 처음 입력 후 입력하지 않는 것 같습니다. 그것의 루프 상태를 확인하기 위해 무엇을 사용하고있는 것인가? integer. 사용자 값 :에이 값을 사용하십시오.

그래서 나는 그래서 인쇄하고 내가 원하는처럼하라는 메시지가 둥근 괄호
while(scan.hasNextLong()) 

내부 조건이 줄

while 루프 condion의 내부에 인쇄하고 싶었다;

답변

0

초기화하기 전에 값을 인쇄하려면 triyng입니다. println 대신 print을 사용하면 다음 출력이 같은 줄에 표시됩니다.

public static void main(String[] args) 
     { 

      Scanner scan = new Scanner(System.in); 

      do{ 

       long tobe = scan.nextLong(); 
       System.out.println("Your Value: " + tobe); 

       int total = 0; 

       String parsed = String.valueOf(tobe); 

       for(int i = 0; i < parsed.length(); i++) { 
        total += Character.getNumericValue(parsed.charAt(i)); 
       } 

       System.out.println("Your Result: "+ total); 
      } 
      while(scan.hasNextLong()); 
     } 
0

스캐너가 String 입력을 갖도록 코드를 변경했습니다.
while 조건은 숫자 만 들어 있는지 확인합니다. 입력에서 .matches()을 호출하여 입력 문자열을 정규식 \d+과 일치 시키려고 시도합니다. 이 표현식은 일련의 하나 이상의 숫자와 일치합니다. \d은 숫자 용이며 +은 한정 기호입니다. RegExr과 같은 사이트에서 정규 표현식에 대해 배우고 놀 수 있습니다. 문자열은 단지 숫자를 포함하는 경우

Scanner scan = new Scanner(System.in); 
    String input; 

    System.out.print("Your Value: "); 

    while ((input = scan.nextLine()).matches("\\d+")){ 

     int total = 0; 

     for(int i = 0; i < input.length(); i++) { 
      total += Character.getNumericValue(input.charAt(i)); 
     } 

     System.out.println("Your Result: "+ total); 
     System.out.println("\nYour Value: "); 
    } 

    System.out.println("\nTHE END."); 
    scan.close(); 
+0

그래서 .matches ("\\ D +") 수표 while(scan.hasNextLong()); 바꾸기? 그렇다면 나는 이해했다. 그러나 나는 또한 상태의 inaide를 인쇄하고 싶었다. 그리고 또한 어떻게 일치하는 방법을 작동 설명 plz 것인가? 분명히. 이유는 \\ d + 등입니다. – Rabin

+0

@Rabin'.matches()'메소드에 대한 설명을 추가했습니다. 불행히도 나는 왜 당신이 조건의 내부에 무언가를 인쇄하고 싶은지 이해하지 못한다. 나는 아직도 이것이 도움이되기를 바란다. – mumpitz

0

while(scan.hasNextLine());