String 변수에 입력 받은 값을 charAt()을 사용하기 위해 String으로 다시 변환하려면 String.valueOf(char형)을 사용해야
한다는 것을 알았다.
다음은 코드이다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class Main { | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
String a = sc.nextLine(); | |
int cnt=0; | |
String word = ""; | |
for(int i=0; i<a.length(); i++) { | |
String b = String.valueOf(a.charAt(i)); | |
if(b.equals(" ")) { | |
word=""; | |
}else { | |
if(word.length()==0) { | |
cnt++; | |
} | |
word=b; | |
} | |
} | |
System.out.print(cnt); | |
} | |
} |
다음은 꼼수(?) 코드이다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class Main{ | |
public static void main(String[] args){ | |
Scanner scan = new Scanner(System.in); | |
String str = scan.nextLine().trim(); | |
scan.close(); | |
if(str.isEmpty()){ | |
System.out.println(0); | |
}else{ | |
String[] words = str.split(" "); | |
System.out.println(words.length); | |
} | |
} | |
} |
'프로그래밍 > JAVA' 카테고리의 다른 글
JAVA 상속(Override) 재정의, super (0) | 2018.07.17 |
---|---|
자바 Static 변수 (0) | 2018.07.16 |
리펙토링(Refactoring)의 원칙과 정의 (0) | 2018.07.16 |
자바 소수점 자리 표현 하는 법 (0) | 2018.07.05 |
자바 성능 향상 보조 스트림 - BufferedInputStream, BufferedReader / BufferedOutputStream, BufferedWriter (0) | 2018.07.04 |