public class Question6_letterCapitalize {
public static void main(String[] args) throws Exception{
//문자열을 입력받을 객체를 생성
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//문자열을 출력할 객체를 생성
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
//문자열을 입력받을 변수를 생성
String words = br.readLine();
String arr[] = words.split(" ");
//조건 생성
if(arr.length == 0 || words.isBlank()) { //빈 문자열이거나 공백이면
bw.write(words); //그대로 출력한다
} else {
Pattern pattern = Pattern.compile("([a-z])([a-z]*)"); //모든 문자열에 대한 정규식
Matcher matcher = pattern.matcher(words); //pattern과 일치하는 문자열을 찾아서 객체에 전달
//위의 두 코드를 하나로 합칠 수 있다
// Matcher match = Pattern.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(words);
StringBuffer str = new StringBuffer(); //변경한 문자열을 저장할 공간을 생성한다
while (matcher.find()) { //matcher.find()) 메서드로 매칭되는 위치로 이동한다
//appendReplacement 메서드로 (str, 바꿀 문자열)을 통해 바뀐 문자열을 str에 저장한다
matcher.appendReplacement(str, matcher.group(1).toUpperCase() + matcher.group(2).toLowerCase());
}
matcher.appendTail(str); //더이상 찾을 문자열이 없으므로 꼬리를 붙이기 위한 메서드를 사용한다
bw.write(str.toString()); //str 값을 String으로 변환하여 출룍한다
}
// bw.flush();//남아있는 데이터를 모두 출력
bw.close();//스트림 닫음
}
}
Result
> Task :classes
java is good
> Task :Question6_letterCapitalize.main()
Java Is Good
public class Question3_powerOfTwo {
public static void main(String[] args) {
//수를 입력받는다
Scanner sc = new Scanner(System.in);
System.out.println("수를 입력하세요 : ");
long num = sc.nextInt();
//2의 거듭제곱인지 확인 후 boolean 값을 출력한다
while (num >= 1) {
if (num % 2 == 0 || num == 1) {
System.out.println(true);
} else {
System.out.println(false);
}
break;
}
}
}
배열을 입력받아 차례대로 배열의 첫 요소와 마지막 요소를 키와 값으로 하는 HashMap을 리턴
Code
public class Question1_transformFirstAndLast {
public static void main(String[] args) {
//입력받을 데이터의 개수를 입력받는다
Scanner sc = new Scanner(System.in);
System.out.println("입력받을 문자의 개수는?");
Integer count = sc.nextInt();
sc.nextLine();
//배열에 들어갈 문자열을 입력한다
System.out.println(count + "개의 문자를 입력하세요");
String[] arr = new String[count];
for (int i = 0; i < count; ++i) {//
arr[i] = sc.nextLine();
//배열에 빈문자열이 입력되면 null을 반환한다
if(arr[i].length()==0){
arr[i]=null;
}
}
//저장된 배열의 데이터 중에서 첫번째와 마지막 데이터를 key와 value 로 저장한다
HashMap result = new HashMap();
//배열의 첫번째와 마지막 값을 key와 value로 저장한다
result.put(arr[0], arr[arr.length - 1]);
//저장된 값을 출력한다
System.out.println("{" + result.keySet() + " : " + result.values() + "}");
}
}
Result
입력받을 문자의 개수는?
5
5개의 문자를 입력하세요
a
s
d
f
g
{[a] : [g]}
.length 메서드는 index 값으로 변황하는 역활을 한다 - index로 변환하여 해당 위치에 있는 배열의 값을 환원한다
package array;
public class Test1 {
public static void main(String[] args) {
//scores 변수에 5개의 int 값을 배정한다
int[] scores = {100, 90, 85, 95, 100};
int sum =0; //합계를 구하기 위하여 sum 변수를 0으로 지정한다
//scores.length로 배열의 index값인 0~4까지를 지정한다
for (int i=0; i<scores.length; i++) {
sum = sum + scores[i];
/* 0 = 0 + 100
190 = 100 + 90
275 = 190 + 85
370 = 275 + 95
470 = 370 + 100
*/
}
System.out.println(sum); //최종 sum 값이 출력된다
}
}
2) array와 while를 사용한 코드
package array;
public class ArrayWhile {
public static void main(String[] args) {
int[] scores = {100, 90, 85, 95, 100};
int sum=0;
int i=0;
while(i<scores.length){
sum = sum + scores[i++];
}
System.out.println(sum);
}
}
/*
상현이가 가르치는 아이폰 앱 개발 수업의 수강생은 원섭, 세희, 상근, 숭, 강수이다.
어제 이 수업의 기말고사가 있었고, 상현이는 지금 학생들의 기말고사 시험지를 채점하고 있다.
기말고사 점수가 40점 이상인 학생들은 그 점수 그대로 자신의 성적이 된다.
하지만, 40점 미만인 학생들은 보충학습을 듣는 조건을 수락하면 40점을 받게 된다.
보충학습은 거부할 수 없기 때문에, 40점 미만인 학생들은 항상 40점을 받게 된다.
학생 5명의 점수가 주어졌을 때, 평균 점수를 구하는 프로그램을 작성하시오.
입력
입력은 총 5줄로 이루어져 있고, 원섭이의 점수, 세희의 점수, 상근이의 점수, 숭이의 점수, 강수의 점수가 순서대로 주어진다.
점수는 모두 0점 이상, 100점 이하인 5의 배수이다. 따라서, 평균 점수는 항상 정수이다.
출력
첫째 줄에 학생 5명의 평균 점수를 출력한다.
예제 입력 1
10
65
100
30
95
예제 출력 1 : 68
힌트
숭과 원섭이는 40점 미만이고, 보충학습에 참여할 예정이기 때문에 40점을 받게 된다. 따라서, 점수의 합은 340점이고, 평균은 68점이 된다.
출처
Olympiad > Japanese Olympiad in Informatics > Japanese Olympiad in Informatics Qualification Round > JOI 2014 예선 1번
*/
2. 풀이
import java.io.IOException;
import java.util.Scanner;
public class AverageScore_me {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int sum = 0;
int average = 0;
for (int i = 0; i < 5; i++) {
int score = sc.nextInt();
if (score > 40) {
score = score;
} else if (score == 40) {
score = score;
} else if (score < 40) {
score = 40;
}
System.out.println("환산 점수는 = " + score);
sum = sum + score;
average = sum / 5;
}
System.out.println("5명의 평균 점수는 = " + average);
}
}
3. 백준 채점용 코드
// import java.io.IOException;
import java.util.Scanner;
public class AverageScore_me {
public static void main(String[] args) /* throws IOException */ {
Scanner sc = new Scanner(System.in);
int sum = 0;
int average = 0;
for (int i = 0; i < 5; i++) {
int score = sc.nextInt();
if (score > 40) {
score = score;
} else if (score == 40) {
score = score;
} else if (score < 40) {
score = 40;
}
// System.out.println("환산 점수는 = " + score);
sum = sum + score;
average = sum / 5;
}
System.out.println(/* "5명의 평균 점수는 = " + */ average);
}
}
public class Grade {
int a[2];
int b[2];
void input_grade(){
a[0]=90;
a[1]=80;
b[0]=85;
b[1]=80;
}
void output_grade(){
System.out.printf("%c, %c", a[0]+b[0], a[1]+b[1]);
}
void main(void) {
input_grade();
output_grade();
}
}
해답은 아래에...
.
.
.
.
.
.
.
.
.
class Record {
int a;
int b;
void output_grade(){
System.out.println(a+b);
}
}
public class Grade{
public static void main(String[] args) {
Record c1=new Record();
Record c2=new Record();
c1.a=90;
c1.b=80;
c2.a=85;
c2.b=80;
c1.output_grade();
c2.output_grade();
}
}
※ 다음과 같이 작성할 수도 있다
class Record {
int e; //성적1을 위한 필드
int m; //성적2를 위한 필드
void input_record(int a,int b){ //input_record에 대한 함수 정의
e=a; //성적1 입력
m=b; //성적2 입력
}
void output_record(){ //output_record에 대한 함수 정의
System.out.println(e+m); //합계 출력
}
}
public class Grade{
public static void main(String[] args) {
Record c1=new Record(); //학생1에 대한 객체 생성
Record c2=new Record(); //학생2에 대한 객체 생성
c1.input_record(90,80); //학생1에 대한 성적 입력
c2.input_record(80,85); //학생2에 대한 성적 입력
c1.output_record(); //합계 출력
c2.output_record(); //합계 출력
}
}