배열 복사시
for문을 쓸 수도 있지만 System.arrraycopy(복사배열 , 인덱스 위치. 복사 당사자 배열, 복사 갯수)도 가능하다
for문을 쓴 경우
String[] myNameArray = {"홍길동",null,"이순신"}; // index : 2 , 길이 : 3
String[] yourNameArray = new String[4]; // index : 3 , 길이 4
int j = 0;
while(j<myNameArray.length){
yourNameArray[j] = myNameArray[j];
j++;
}
int i =0;
while(i<yourNameArray.length){
System.out.println(yourNameArray[i]);
i++;
}
System.arraycopy를 쓴 경우
String[] myNameArray = {"홍길동",null,"이순신","슈퍼맨"};
String[] yourNameArray = new String[6];
System.arraycopy(myNameArray, 0, yourNameArray, 0, myNameArray.length);
for(int i =0; i<yourNameArray.length;i++) {
System.out.println(i+" : " + yourNameArray[i]);
}
mynamearray 0번 위치부터 복사 . yournameArray 0번 위치부터 넣겠다. myNameArra.length개를 넣겟다
다차원배열
int[][] mathScores = new int[2][3]; // 배열이 2개 있고 , 그 안의 배열은 3개의 값이 있음
System.out.println(mathScores.length); // 2
System.out.println(mathScores[0].length); //3
다차원 배열에 값 넣기
for(int i=0;i<number.length;i++){
for(int j=0;j<number[i].length;j++){
number[i][j] = 1;
}
}
//값표시
for(int m=0;m<number.length;m++){
for(int n=0;n<number[m].length;n++){
System.out.println(number[m][n]);
}
}
배열값 3개를 가지고 있는 배열이 2개 있는 mathScore
int[][] mathScores = new int[2][3];
for(int i=0;i<mathScores.length;i++) {
for(int j=0;j<mathScores[i].length;j++) {
mathScores[i][j] = i + j ;
System.out.println(mathScores[i][j]);
}
}
0
1
2
1
2
3
다차원 배열 출력
String[][] heros = {{"이순신","베트맨"},{"홍길동","스파이더맨","아이언맨"}};
for(int i=0;i<heros.length;i++){
for(int j=0;j<heros[i].length;j++){
System.out.println(heros[i][j]);
}
}
double을 0.0으로 나누려고 할 때 infinity와 NaN이 나옴
double a = 1.1;
double b = 0.0;
double z = a/b;
double d = a%b;
System.out.println(z);//infinity
System.out.println(d);//NaN
문자열 비교
String grade = "B";
int score1 = 0;
if(grade.equals("A")) {
score1=100;
}else if(grade.equals("B")) {
int result = 100-20;
score1 = result;
}else {
score1 =60;
}
숫자인지 아닌지 확인하는 메소드 !!
\d로는 정규식 표현이 안된다 \ <== 이게 인식이 안되서
\\d로 씀 !!
//숫자인지 아닌지 확인
public static boolean ischeckAmount(String userInputAmount) {
String checkNum = "[0-9]+"
return Pattern.matches(checkNum,userInputAmount);
// String checkNum = "\\d";
// boolean checkResult = Pattern.matches(checkNum, userInputAmount);
// return checkResult;
}
예금액 부분에 문자열을 넣으면 에러가 나서 저렇게 메소드를 적은 것이다 !
사용예시 )
public class Q7_01 {
//입력값이 숫자 문자열로만 되어 있는지 확인하는 메서드
public static boolean isCheckAmount(String userInputAmount) {
String checkNumRegExp = "\\d+" ;
// boolean checkResult = Pattern.matches(checkNumRegExp, userInputAmount) ;
// return checkResult ;
return Pattern.matches(checkNumRegExp, userInputAmount) ;
}
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in) ;
long balance = 0L ;
boolean runFlag = true ;
while (runFlag) {
System.out.println("-----------------------------");
System.out.println("1.예금 | 2.출금 | 3.잔고 | 4.종료");
System.out.println("-----------------------------");
System.out.println("선택> ");
String myChoice = myScanner.next() ;
//int myChoice = myScanner.nextInt() ;
//0 ~ 9 아닌 다른 키를 입력하는 경우, 아래의 오류가 발생됩니다.
//InputMismatchException 오류가 발생됩니다.
if (myChoice.equals("1")) {
while (true) {
System.out.println("예금액> " );
String myAmountStr = myScanner.next();
if (!isCheckAmount(myAmountStr)) {
System.out.println("숫자키로만 입금액을 입력하세요.");
} else {
int myAmount = Integer.parseInt(myAmountStr);
balance = balance + myAmount ;
System.out.println("총 예금액: " + balance);
break ;
}
}
} else if (myChoice.equals("2")) {
while (true) {
System.out.println("출금액> " );
String myAmountStr = myScanner.next();
if (!isCheckAmount(myAmountStr)) {
System.out.println("숫자키로만 입금액을 입력하세요.");
} else {
int myAmount = Integer.parseInt(myAmountStr);
if (balance == 0L) {
System.out.println("귀하의 잔액이 0 입니다.");
System.out.println("처음부터 다시 거래해 주십시오.");
break ;
}
if (balance >= myAmount) {
balance = balance - myAmount ;
System.out.println("총 예금액: " + balance);
break ;
} else {
System.out.println("현재 잔액은 " + balance + "원입니다.");
}
}
}
} else if (myChoice.equals("3")) {
System.out.println("잔고> " + balance);
} else if (myChoice.equals("4")) {
runFlag = false ;
} else {
System.out.println("1 ~ 4 중에서 원하는 하나의 숫자를 선택하십시오.");
}
}
myScanner.close();
System.out.println("프로그램 종료");
}
}
배열의 최대값 구하기
예시 1 )
int[] array = {1,5,3,8,2};
int maxInt = 0;
for(int i=0;i<array.length;i++){
maxInt = (array[i]>maxInt)?array[i]:maxInt;
}
System.out.println(maxInt); // 8
예시 2)
int[] array = {1,5,3,8,2} ;
int max = 0;
for(int i = 0 ; i < array.length ; i++) {
if(array[i] > max ) {
max = array[i] ;
//max = 1;
// max = 5;
// max = 5;
// max = 8;
}
}
System.out.println("array 배열중 가장 큰 숫자는 : "+max + " 입니다.");
-가 들어갔을 경우
int[] array = {-1,-5,-3,-8,-2};
int max = array[0];
for(int i=0;i<array.length;i++){
if(array[i] > max ) {
max = array[i] ;
}
}
System.out.println(max); // -1
최소값 구하기
int[] array = {1,5,3,8,2};
int min = array[0];
for(int num : array) {
min = (num<min)?num : min;
}
이차원배열 합 , 평균 구하기
int[][] array = {
{95,86},
{83,92,96},
{76,83,93,87,88}
};
int sum = 0;
for(int i=0;i<array.length;i++) {
for(int j=0;j<array[i].length;j++) {
sum = sum + array[i][j]; // 0번째 95 , 86 , 1번째 : 83 92 96 , 2번째 : 76
}
}
System.out.println(sum);
float average = 0F;
average = (sum*1.0F) /(array[0].length+array[1].length+array[2].length);
System.out.println(average);
배열 갯수를 count변수로 따로 줘서 만들 수 있다.
int sum = 0;
float average = 0F;
int count = 0;
for(int i=0;i<array.length;i++) {
for(int j=0;j<array[i].length;j++) {
sum = sum + array[i][j]; // 0번째 95 , 86 , 1번째 : 83 92 96 , 2번째 : 76
}
count = count + array[i].length;
}
System.out.println(sum);
average = (sum*1.0F) /count;
System.out.println(average);
}
학생들의 점수를 분석하는 프로그램
//학생수 변수
int studentNum = 0;
//프로그램 무한반복을 위한 변수
boolean isValid = true;
//점수 저장 변수
int[] scores = null;
while(isValid){
//번호 선택
int input = myScanner.nextInt();
if(input==1){
System.out.println("학생 수>");
studentNum = myScanner.nextInt();
//학생수로 배열 길이 셋팅
scores = new int[studentNum];
}else if(input==2){
System.out.println("점수 입력>");
for(int i=0;i<scores.length;i++){
int score = myScanner.nextInt();
scores[i] = score;
}
}else if(input == 3){
System.out.println("점수 리스트>");
for(int i=0;i<scores.length;i++){
System.out.println(scores[i]);
}
}else if(input==4){
System.out.println("분석>");
//최고점수
int maxInt = 0;
//최소점수
int minInt = 0;
for(int i=0;i<scores.length-1;i++){
maxInt=(maxInt>scores[0])?scores[0]:maxInt;
minInt=(minInt<scores[0])?scores[0]:minInt;
}
System.out.println("최고점수는: "+maxInt);
//평균값 구하기
int sum = 0;
for(int i=0;i<scores.length;i++){
sum = sum + scores[i];
}
double average = (double)sum/scores.length;
System.out.println("평균점점수는: "+average);
}else if(input == 5){
isValid = false;
}//if문 종료
}//while문 종료 3
System.out.println("프로그램 종료");
myScanner.close();
}
'Development (국비 복습 ) > 자바' 카테고리의 다른 글
[2023-03-22]인스턴스,VO,오버로딩 (0) | 2023.03.22 |
---|---|
[2023-03-21]배열 중복값, (0) | 2023.03.21 |
[2023-03-17]NullPointException,String메소드,인코딩,배열 (0) | 2023.03.17 |
[2023-03-16]입력값을 받는 Scanner객체, String객체,Null (0) | 2023.03.16 |
[2023-03-15]for문 활용 (0) | 2023.03.15 |
댓글