class Exercise6_2 {
public static void main(String[] args) {
Student s = new Student("홍길동", 1, 1, 100, 60, 76);
String str = s.info();
System.out.printin(str);
}
}
class Student {
/*
(1) 알맞은 코드를 넣어 완성하시오.
*/
}
결과 : 홍길동, 1,1,100,60,76,236,78.7
홍길동, 1,1,100,60,76,236,78.7
가 나와야 한다. s.info()는 객체의 주소값이 저장된 참조변수를 통해 접근하니 인스턴스 메서드이다. (클래스 메소드는 주로 클래스명.메소드명으로 접근한다.)<내 풀이>
public class Chapter6_Practice {
public static void main(String[] args) {
//Student 클래스의 새 인스턴스를 생성하여 그 주소값을 동타입 참조변수 s에 저장
Student s = new Student("홍길동", 1, 1, 100, 60, 76);
// String str에는 s.info()를 저장한다. info( )는 인스턴스 메서드이다.
String str = s.info(); //info()는 인스턴스 s를 통해 접근할 수 있는 메서드일 것이다.
System.out.println(str);
}
}
class Student {
String name; //학생이름
int ban; //반
int no; //번호
int kor; //국어점수
int eng; //영어점수
int math; //수학점수
Student(String name, int ban, int no, int kor, int eng, int math) {
this.name = name;
this.ban = ban;
this.no = no;
this.kor = kor;
this.eng = eng;
this.math = math;
}
String info() {
int sum = this.kor+this.eng+this.math;
float avg = (int)(sum/3.0f*10)/10.0f; // 소수점 한자리까지만 남기고 나머지 소수점은 버리기 위해 10을 곱하고 int를 씌워서 버린다음 다시 10.0f로 나눔
String info = new String(""+ this.name +"," + this.ban+"," + this.no+"," + this.kor+"," + this.eng+"," + sum +","+ avg);
return info;
}
}
<결과>
홍길동,1,1,100,60,236,78.6
class Exercise6_2 {
public static void main(String args[]) {
Student s = new Student(" ",1,1,100,60,76); 홍길동
String str = s.info();
System.out.println(str);
}
}
class Student {
String name;
int ban;
int no;
int kor;
int eng;
int math;
Student(String name, int ban, int no, int kor, int eng, int math) {
this.name = name;
this.ban = ban;
this.no = no;
this.kor = kor;
this.eng = eng;
this.math = math;
}
public String info() {
return name ✔️
+","+ban
+","+no
+","+kor
+","+eng
+","+math
+","+(kor+eng+math)
+","+((int)((kor+eng+math) / 3f * 10 + 0.5f) / 10f) //❗ 이 부분 반올림!
;✔️
}
}
<결과>
홍길동, 1,1,100,60,76,236,78.7❗
public static void main(String[] args) {
Student s = new Student();
s.name = "홍길동";
s.ban = 1;
s.no = 1;
s.kor = 100;
s.eng = 60;
s.math = 76;
System.out.println ("이름:" + s.name);
System.out.println ("총점:" + s.getTotal());
System.out.println("평균:" + s.getAverage());
}
<Student 클래스에는 무엇이 와야할까?>
float result= (Math.round((int)(this.getTotal()/3.0f*100)))/100.0f;
) ➡️ (Math.round((int)(236/3.0f100)))/100.0fpublic class Chapter6_Practice {
public static void main(String[] args) {
Student s = new Student();
s.name = "홍길동";
s.ban = 1;
s.no = 1;
s.kor = 100;
s.eng = 60;
s.math = 76;
System.out.println ("이름:" + s.name);
System.out.println ("총점:" + s.getTotal());
System.out.println("평균:" + s.getAverage());
}
}
class Student {
String name; //학생이름
int ban; //반
int no; //번호
int kor; //국어점수
int eng; //영어점수
int math; //수학점수
int getTotal() {
int result = this.kor+this.eng+this.math;
return result;
}
float getAverage() {
float result = (int)(Math.round(this.getTotal()/3.0f*100))/100.0f;
return result;
}
}
<결과>
이름:홍길동
총점:236
평균:78.67
return (int)(getTotal() / 3f * 10 + 0.5f) / 10f;
class Exercise6_4 {
// 두 점 (x,y)와 (x1,y1)간의 거리를 구한다.
static double getDistance(int x, int y, int xl, int yl) {
/*
(1) 알맞은 코드를 넣어 완성하시오.
*/
}
public static void main(String[] args) {
System.out.println(getDistance(1, 1, 2, 2));
}
}
^
로 사용되지 않는다. 이는 정수 유형에서만 사용되는 비트 배타적 논리합이다. 제곱은 Math.power()
메서드를 사용해야 한다.<내 풀이>
// 두 점 (x,y)와 (x1,y1)간의 거리를 구한다.
static double getDistance(int x, int y, int x1, int y1) {
double base = Math.abs(x1-x); //밑변
double height = Math.abs(y1-y); //높이
double hypotenuse = Math.sqrt(Math.pow(base, 2)+Math.pow(height, 2)); //Math.pow(대상숫자, 지수)
return hypotenuse; //빗변이 곧 두 점 사이의 거리이다.
}
public static void main(String[] args) {
System.out.println(getDistance(1, 1, 2, 2));
}
<결과>
1.4142135623730951
<모범답안>
class Exercise6_4 {
// (x,y) (x1,y1) . 두 점 와 간의 거리를 구한다
static double getDistance(int x, int y, int x1, int y1) {
return Math.sqrt((x-x1)*(x-x1) + (y-y1)*(y-y1)); // x, y는 지역변수
}
public static void main(String args[]) {
System.out.println(getDistance(1,1,2,2));
}
}
<모범결과>
1.4142135623730951
-💡 모범답안 해설 : 제곱도 Math sqrt(double a) . Math.pow(double
a, double b) , 2 . 를 사용하면 되지만 제곱이므로 그냥 곱셈연산자를 사용했다 어느 쪽을 사용해도 괜찮지만 메서드를 호출하는 것은 곱셈연산보다 비용이 많이 드는 작업이라는 것은 기억해두자. 그렇다고 해서 보다 빠른 코드를 만들겠다고 코드를 복잡하게 하는 것은 좋지 않다.
<제곱연산 메서드를 사용했을 때
static double getDistance(int x, int y, int x1, int y1) {
return Math.sqrt(Math.pow(x-x1,2) + Math.pow(y-y1,2));
}
class MyPoint {
int x;
int y;
MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
/*
(1) 인스턴스메서드 getDistancel 작성하시오.
*/
}
class Exercise6_6 {
public static void main(String[] args) {
MyPoint p = new MyPoint(1, 1);
// p와 (2,2)의 거리를 구한다.
System.out.println(p.getDistance(2, 2));
}
}
<내 풀이>
package effort;
import java.util.Arrays;
import java.util.Scanner;
class MyPoint {
int x;
int y;
MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
double getDistance(int i, int j) {
return Math.sqrt((i-this.x)*(i-this.x) +(j-this.y)*(j-this.y));
}
}
public class PNote {
public static void main(String[] args) {
MyPoint p = new MyPoint(1, 1);
System.out.println(p.getDistance(2,2));
}
}
<내 답>
1.4142135623730951
<문제>
class Exercise6_17 {
/*
* ( 1) shuffle메서드를 작성하시오.
*/
public static void main(String[] args) {
int[] original = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
System.out.printIn(java.util.Arrays.toString(original));
int[] result = shuffle(original);
System.out.println(java.util.Arrays.toString(result));
}
}
<나와야하는 결과>
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[4, 6, 8, 3, 2, 9, 7, 1, 5]
public class PNote {
static int[] shuffle(int[] arr) {
int[] result = arr;
for(int i=0; i<result.length; i++) {
int random = (int)(Math.random()*result.length);
int tmp = result[i];
result[i] = result[random];
result[random] = tmp;
}
return result;
}
public static void main(String[] args) {
int[] original = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
System.out.println(java.util.Arrays.toString(original));
int[] result = shuffle(original);
System.out.println(java.util.Arrays.toString(result));
}
}
<결과>
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[4, 1, 6, 2, 9, 3, 5, 8, 7]
class Exercise6_17 {
public static int[] shuffle(int[] arr) {
if (arr == null || arr.length == 0)
return arr; //⭐⭐ 유효성 검사
for (int i = 0; i < arr.length; i++) {
int j = (int) (Math.random() * arr.length);
// arr[i] arr[j] . 와 의 값을 서로 바꾼다
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
return arr;
}
public static void main(String[] args) {
int[] original = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
System.out.println(java.util.Arrays.toString(original));
int[] result = shuffle(original);
System.out.println(java.util.Arrays.toString(result));
}
}
if(arr==null || arr.length==0) return arr;
class Exercise6_18 {
/*
* (1) isNumber메서드를 작성하시오.
*/
public static void main(String[] args) {
String str = "123";
System.out.println(str + "는 숫자입니까? " + isNumber(str));
str = "1234o";
System.out.printIn (str + "는 숫자입니까? " + isNumber(str));
}
}
public class PNote {
static boolean isNumber(String str) {
boolean isNumber = true; //반환하는 기본값 true로 설정
// 주어진 문자열이 null이거나 빈 문자열이라면 false를 반환(유효성 검사)
if((str==null)||(str.equals("")))
isNumber = false;
// 문자열의 모든 요소가 숫자가 아니면 isNumber 값을 false 바꾸면된다.
// 숫자가 아닌 건 어떤 조건식으로 두어야할지 모르겠으므로, ch에 담아서 소문자나 대문자인지 체크하자.
for(int i=0; i<str.length(); i++) {
char ch = str.charAt(i);
if(('a'<=ch && ch<'z')||('A'<=ch&&ch<='Z')) {
isNumber = false;
break;
}
}
return isNumber;
}
public static void main(String[] args) {
String str = "123";
System.out.println(str + "는 숫자입니까? " + isNumber(str));
str = "1234o";
System.out.println (str + "는 숫자입니까? " + isNumber(str));
}
}
<결과>
123는 숫자입니까? true
1234o는 숫자입니까? false
class Exercise6_18 {
public static boolean isNumber(String str) {
if(str==null || str.equals(""))
return false;
for(int i=0; i< str.length();i++) {
char ch = str.charAt(i);
if(ch < '0' || ch > '9') { //⭐ 내 답과의 차이점
return false;
}
} // for
return true;
}
public static void main(String[] args) {
String str = "123";
System.out.println(str+" ? "+isNumber(str)); 는 숫자입니까
str = "1234o";
System.out.println(str+" ? "+isNumber(str));
if(ch<'0' || ch>'9') return false;
!(ch >= '0' && ch <= '9')
를 써도 되는구나...Java에서 음의 정수는 또는 와 -같이 숫자 앞에 기호 로 표시됩니다 . 그러나 문자 '0'에서 '9'는 양의 정수만 나타냅니다. 따라서 문자가 숫자가 아닌지 확인하는 경우 음수인지 확인할 필요가 없습니다.
메서드 컨텍스트에서 isNumber()입력 문자열의 모든 문자가 숫자 문자인지 확인하고 그렇다면 true를 반환합니다. 문자가 숫자가 아닌 경우 메서드는 즉시 false를 반환합니다. 조건식은 가 문자 '0'(숫자가 아님)보다 작거나 문자 '9'(역시 숫자가 아님)보다 큰지 확인 ch < '0' || ch > '9'합니다 . ch따라서 ch'0'과 '9' 사이에 있지 않으면 표현식은 true를 반환하여 ch숫자가 아님을 나타냅니다.
if(ch<'0' || ch>'9') return false;
를 사용해도 문제가 없다.class MyTv {
boolean isPowerOn;
int channel;
int volume;
final int MAX_VOLUME = 100;
final int MIN_VOLUME = 0;
final int MAX_CHANNEL = 100;
final int MIN_CHANNEL = 1;
void turnOnOff() {
// (1) isPowerOn의 값이 true면 false로, false면 true로 바꾼다.
}
void volumeUp() {
// (2) volume의 값이 MAX_VOLUME보다 작을 때만 값을 1증가시킨다.
}
void volumeDown() {
// (3) volume의 값이 MIN_VOLUME보다 클 때만 값을 1감소시킨다.
}
void channellUp() {
// (4) channel의 값을 1증가시킨다.
// 만일 channel이 IW(_CHANNEL이면, channel의 값을 MIN_CHANNEL로 바꾼다.
}
void channelDown() {
// (5) channel의 값을 1감소시킨다.
// 만일 channel이 MIN_CHANNEL이면, channel의 값을 MAX.
if(channel == MIN_CHANNEL) {
channel = MAX_CHANNEL;
}
else channel--;
}
} // class MyTv
class Note {
public static void main(String[] args) {
MyTv t = new MyTv();
t.channel = 100;
t.volume = 0;
System.out.println("CH:" + t.channel + ", VOL:" + t.volume);
t.channelDown();
t.volumeDown();
System.out.println("CH:" + t.channel + ", VOL:" + t.volume);
t.volume = 100;
t.channellUp();
t.volumeUp();
System.out.println("CH:" + t.channel + ", VOL:" + t.volume);
}
}
package effort;
class MyTv {
boolean isPowerOn;
int channel;
int volume;
final int MAX_VOLUME = 100;
final int MIN_VOLUME = 0;
final int MAX_CHANNEL = 100;
final int MIN_CHANNEL = 1;
void turnOnOff() {
// (1) isPowerOn의 값이 true면 false로, false면 true로 바꾼다.
isPowerOn = !isPowerOn;
}
void volumeUp() {
// (2) volume의 값이 MAX_VOLUME보다 작을 때만 값을 1증가시킨다.
if(volume < MAX_VOLUME) volume++;
}
void volumeDown() {
// (3) volume의 값이 MIN_VOLUME보다 클 때만 값을 1감소시킨다.
if(volume > MIN_VOLUME) volume--;
}
void channellUp() {
// (4) channel의 값을 1증가시킨다.
// 만일 channel이 MAX_CHANNEL이면, channel의 값을 MIN_CHANNEL로 바꾼다.
if(channel == MAX_CHANNEL) {
channel = MIN_CHANNEL;
}
else channel++;
}
void channelDown() {
// (5) channel의 값을 1감소시킨다.
// 만일 channel이 MIN_CHANNEL이면, channel의 값을 MAX.
if(channel == MIN_CHANNEL) {
channel = MAX_CHANNEL;
}
else channel--;
}
} // class MyTv
class Note {
public static void main(String[] args) {
MyTv t = new MyTv();
t.channel = 100;
t.volume = 0;
System.out.println("CH:" + t.channel + ", VOL:" + t.volume);
t.channelDown();
t.volumeDown();
System.out.println("CH:" + t.channel + ", VOL:" + t.volume);
t.volume = 100;
t.channellUp();
t.volumeUp();
System.out.println("CH:" + t.channel + ", VOL:" + t.volume);
}
}
<결과>
CH:100, VOL:0
CH:99, VOL:0
CH:100, VOL:100
class Exercise6_20 {
/*
* ( 1) max메서드를 작성하시오.
*/
public static void main(String[] args) {
int[] data = { 3, 2, 9, 4, 7 };
System.out.println(java.util.Arrays.toString(data));
System.out.println("최대값:" + max(data));
System.out.println("최대값:" + max(null));
System.out.println("최대값:" + max(new int[] {})); // 크기가 0인 배열
}
}
<결과>
[3, 2, 9, 4, 7]
최대값:9
최대값:-999999
최대값:-999999
package effort;
class Note {
/*
* ( 1) max메서드를 작성하시오.
*/
static int max(int[]arr) {
if(arr==null || arr.length==0) {
return -999999;
}
int tmp=arr[0];
for(int i=0; i<arr.length; i++) {
if(tmp<arr[i]) {
tmp = arr[i];
}
}
return tmp;
}
public static void main(String[] args) {
int[] data = { 3, 2, 9, 4, 7 };
System.out.println(java.util.Arrays.toString(data));
System.out.println("최대값:" + max(data));
System.out.println("최대값:" + max(null));
System.out.println("최대값:" + max(new int[] {})); // 크기가 0인 배열
}
}
<결과>
[3, 2, 9, 4, 7]
최대값:9
최대값:-999999
최대값:-999999
class Exercise6_20{
public static int max(int[] arr) {
if(arr==null || arr.length==0)
return -999999;
int max = arr[0]; // . 배열의 첫 번째 값으로 최대값을 초기화 한다
for(int i=1; i< arr.length;i++) { ⭐// . 배열의 두 번째 값부터 비교한다
if(arr[i] > max)
max = arr[i];
}
return max;
}
public static void main(String[] args)
{
int[] data = {3,2,9,4,7};
System.out.println(java.util.Arrays.toString(data));
System.out.println(" :"+max(data)); 최대값
System.out.println(" :"+max(null)); 최대값
System.out.println(" :"+max(new int[]{})); // 크기가 0인 배열
}
}
class Exercise6_21 {
/*
(1) abs메서드를 작성하시오.
*/
public static void main(String[] args)
{
int value = 5;
System. out. println (value + "의절대값:" + abs(value));
value = -10;
System. out. println(value + "의 절대값:" + abs(value));
}
}
<결과>
5의 절대값:5
-10의 절대값:10
class Note {
/*
(1) abs메서드를 작성하시오.
*/
static int abs(int value) {
int result = (int)Math.sqrt(value*value); //어차피 정수^2를 루트씌우면 정수이므로 (int) 강제형변환 가능
return result;
}
public static void main(String[] args)
{
int value = 5;
System. out. println (value + "의 절대값:" + abs(value));
value = -10;
System. out. println(value + "의 절대값:" + abs(value));
}
}
<결과>
5의절대값:5
-10의 절대값:10
<모범답안1>
class Exercise6_21
{
public static int abs(int value) {
return value >=0 ? value : -value;
}
public static void main(String[] args)
{
int value = 5;
System.out.println(value+" :"+abs(value)); 의 절대값
value = -10;
System.out.println(value+" :"+abs(value)); 의 절대값
}
}
<모범답안2>
public static int abs(int value) {
if(value >=0) {
return value;
} else {
return -value; // value , . 가 음수인 경우 부호를 변경한다
}
}