JAVA Step6-2 (배열 응용)
배열값에서 특정 음절갯수 이상만 출력
import java.util.Arrays;
public class arrayif {
public static void main (String [] args){
String a[] = {"hong", "lee", "kim", "jang", "dongbang"};
int b = a.length; // 객체갯수 5개
int c = 0;
while(c < b) { // 반복변수가 객체 객수보다 작을때 까지
int d = a[c].length();
// System.out.println(a[c]); // 배열의 데이터값 출력
if (d > 3) {
System.out.println(a[c]); // 조건문에 만족하는 3음절 이상의 단어 hong jang dongban 출력
}
c++;
}
}
}
[응용문제]
다음 배열 데이터의 값을 보두 더하여 최종 결과값 출력
[15, 60, 11, 14, 27]
import java.util.Arrays;
public class Note {
public static void main (String [] args){
int a [] = {15, 60, 11, 14, 27};
int b = a.length; // 5개
int c = 0;
int total = 0;
// for문
for (c = 0; c < b; c++) {
total += a[c];
}
System.out.println(total); //127
/============================================================================
// while문
while (c < b) {
total += a[c];
c++;
}
System.out.println(total); //127
/============================================================================
//dowhile문
do {
total += a[c];
c++;
} while(c < b);
System.out.println(total); //127
}
}
for each
for each문을 사용할 때에는 inex 번호가 필요없이 사용 할 경우 .
단순한 배열에서 사용. (1차배열)
for ~ do while문 사용할 때에 index 번호가 필요할 때 사용.
for (int 변수 : 배열변수) {
System.out.println (변수)
}
출력
import java.util.Arrays;
public class foreach {
public static void main (String [] args){
int a [] = {5, 10, 15, 20, 25, 30, 35};
for (int b : a) {
System.out.println(b + " "); // 출력값 5 10 15 20 25 30 35
}
}
}
for each + scanner + array
import java.util.Arrays;
import java.util.Scanner;
public class Note {
public static void main (String [] args){
String paytype [] = {"무통장", "카드", "휴대폰", "상품권", "쿠폰"};
Scanner sc = new Scanner(System.in);
System.out.println("결제 하고자 하는 방법을 입력해주세요.");
String userpay = sc.next();
for (String a : paytype) {
if (userpay.equals(a)) {
if(a.equals("카드")) {
System.out.println("카드사 점검중입니다.");
}
else {
System.out.println(userpay +" 결제 방식으로 진행합니다.");
}
}
}
sc.close();
}
}
[응용문제] 반복문 + 조건문 + 스캐너 + 배열
[햄버거, 피자, 치킨, 커피]의 배열.
"주문하고자 하는 음식을 입력해주세요"
출력. (해당 질문은 4회 반복)
단, "주문 종료" 입력시 즉시 반복문 종료 되며
주문내역을 출력
import java.util.Arrays;
import java.util.Scanner;
public class Note {
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
String menu [] = {"햄버거", "피자", "치킨", "커피"};
String bill[] = new String [4];
String order;
int ct=0;
for (String a : menu) {
System.out.println("주문하고자 하는 음식을 입력해주세요.");
order = sc.next();
if(order.equals("주문종료")) {
break;
}
else {
for(String b : menu) {
if (order.equals(b)) {
bill[ct] = b;
ct++;
}
}
}
}
System.out.println(Arrays.toString(bill));
sc.close();
}
}
for each/ 배열에서 원하는 값만 배열 형태로 출력
import java.util.Arrays;
import java.util.Scanner;
public class foreachselectarray {
public static void main(String[] args) {
String[] emname = new String[3]; // 빈 배열 [3]개 만들기
String name[] = {"홍길동","이순신","강감찬"};
// System.out.println(name[0]); // 출력값 : 홍길동
int ct = 0; //foreach에는 인덱스 번호가 없으므로 인덱스번호를 따로 지정해주기 위한 변수 생성이 필요함.
for(String a : name) {
if(a.equals("홍길동")||a.equals("강감찬")) {
//해당 (기존)배열값 중 조건에 맞는 값만 추려서 새로운 배열값에 추가함.
emname[ct] = a;
ct++;//인덱스 번호를 순차적으로 적용하기 위한 증가값.
}
}
// int name_ea=name.length; //객체 갯수 3개
System.out.println(Arrays.toString(emname));
}
}
배열에서 짝수만 배열로 출력
import java.util.Arrays;
public class Note {
public static void main(String[] args) {
int a[] = {1, 2, 3, 4, 5, 6, 7}; // 배열
int b [] = new int [3]; // 빈 배열 생성
int c = a.length; // 객체 갯수 7
int d = b.length; // 객체 갯수 3
int e; // 반복
int f = 0; // 조건반복
for (e = 0; e < c; e++) {
if(a[e] % 2 == 0 && f < d) { // 배열[반복] % 2 ==0 && 조건반복 < 빈배열 객체수
b[f] = a[e]; // 빈 배열[조건반복] = 배열[반복]
f++;
}
}
System.out.println(Arrays.toString(b));
}
}
[응용문제]
배열 객체의 총 합
[1500, 22000, 13000, 14500, 113800, 45000]
배열 안에 있는 숫자의 총 합을 결과값으로 출력하시오.
import java.util.Arrays;
import java.util.Scanner;
public class arrayplus {
public static void main(String[] args) {
int price [] = {1500, 22000, 13000, 14500, 113800, 45000};
int total = 0;
int a;
int b = price.length;
for (a=0; a < b; a++) {
total += price[a];
}
System.out.println(total);
}
}
[응용문제]
다음 중 장바구니에 여러개의 상품이 담겨져있다.
그 중 택배비가 별도로 측정되는 금액만 추출하여 배열로 출력하시오.
택배비는 30000원 이상은 무료.
15000 48000 67000 8000 118200 49800 6000 18700
import java.util.Arrays;
public class arrayselect {
public static void main(String[] args) {
int price [] = {15000, 48000, 67000, 8000, 118200, 49800, 6000, 18700};
int basket [] = new int [4]; // 빈 배열 생성
int price_ea = price.length;
int a; // 반복문
int b = 0; // 조건반복문
for (a = 0; a < price_ea; a++) {
if (price[a] >= 30000) {
basket[b] = price[a];
b++;
}
}
System.out.println(Arrays.toString(basket));
}
}
[응용문제]
해당 사용자 정보 데이터 및 각 레벨 데이터가 있습니다.
그 중 레벨 데이터 값에 3미만의 값만 확인하여 배열 데이터를 재가공합니다.
[홍길동, 이순신, 강감찬, 세종대왕, 유관순, 김유신]
[4, 3, 1, 1, 2, 2]
import java.util.Arrays;
import java.util.Scanner;
public class ifarrays {
public static void main(String[] args) {
String user [] = {"홍길동", "이순신", "강감찬", "세종대왕", "유관순", "김유신"};
int lv [] = {4, 3, 1, 1, 2, 2};
String notvip [] = new String [4]; // 빈 배열
int user_ea = user.length;
int re;
int ct = 0;
for (re=0; re<user_ea; re++) {
if(lv[re] < 3) {
notvip[ct] = user[re];
ct++;
}
}
System.out.println(Arrays.toString(notvip));
}
}
출력값 : [강감찬, 세종대왕, 유관순, 김유신]