구구단
1단 2단 3단 : 한 묶음
4단 5단 6단 : 한 묶음
7단 8단 9단 : 한 묶음
for(int lines=1;lines<=3;lines++){
System.out.println(lines + " 단\t\t" + (lines+1) + " 단\t\t" + (lines+2) + " 단");
for(int numbers=1;numbers<=9;numbers++){
System.out.println(lines + " X " + numbers + "=" + (lines*numbers)+"\t"
+(lines+1)+"X"+numbers+"="+((lines+1)*numbers) +"\t"
+ (lines+2)+"X "+numbers+"="+((lines+2)*numbers));
}
System.out.println();
}
do-while문
while문의 조건이 실행 불가해도, 한번이라도 실행하게 해줌
boolean runFlag=false; // while문에 넣으면 실행불가
do{
keyInt = sc.nextInt();
if(keyInt == 1) {
speed++;
System.out.println("현재 속도 : "+speed);
}else if(keyInt == 2) {
speed--;
System.out.println("현재 속도 : "+speed);
}else if(keyInt==3) {
runFlag = false;
System.out.println("프로그램 종료");
}else {
System.out.println("1,2,3 중에서 하나만 입력하고 엔터를 치세요");
}
}while(runFlag);
runFlag을 true로 해서 만든 코드
boolean runFlag=true ;
while(runFlag){
keyInt = sc.nextInt();
if(keyInt == 1) {
speed++;
System.out.println("현재 속도 : "+speed);
}else if(keyInt == 2) {
speed--;
System.out.println("현재 속도 : "+speed);
}else if(keyInt==3) {
runFlag = false;
System.out.println("프로그램 종료");
}else {
System.out.println("1,2,3 중에서 하나만 입력하고 엔터를 치세요");
}
}
nextInt()를 가져와서 숫자열만 받을 수 있지만. 사용자가 문자열을 입력할 수도 있다.
이때는 에러가 난다
해결방법
String값으로 준다..
boolean runFlag = true;
int speed = 0;
String choiceStr = null;
Scanner sc = new Scanner(System.in);
while(runFlag) {
System.out.println("-------------------");
System.out.println("1.증속 | 2.감속|3.중지");
System.out.println("-------------------");
System.out.println("1,2,3 중 입력> ");
choiceStr = sc.next(); // 하나의 단어만 입력가능
if(choiceStr == "1") {
speed++;
System.out.println("현재 속도 : "+speed);
}else if(choiceStr =="2") {
speed--;
System.out.println("현재 속도 : "+speed);
}else if(choiceStr=="3") {
runFlag = false;
System.out.println("프로그램 종료");
}else {
System.out.println("1,2,3 중에서 하나만 입력하고 엔터를 치세요");
}
}
근데 speed가 안나옴 계속 else만 프린트
String 값인데 ==로 해서 프린트가 안된것이다
String.equals("str")로 만들자
boolean runFlag = true;
int speed = 0;
//String keyStr = null;
String choiceStr = null;
Scanner sc = new Scanner(System.in);
while(runFlag) {
System.out.println("-------------------");
System.out.println("1.증속 | 2.감속|3.중지");
System.out.println("-------------------");
System.out.println("1,2,3 중 입력> ");
choiceStr = sc.next(); // 하나의 단어만 입력가능
if(choiceStr.equals("1")) {
speed++;
System.out.println("현재 속도 : "+speed);
}else if(choiceStr.equals("2")) {
speed--;
System.out.println("현재 속도 : "+speed);
}else if(choiceStr.equals("3")) {
runFlag = false;
System.out.println("프로그램 종료");
}else {
System.out.println("1,2,3 중에서 하나만 입력하고 엔터를 치세요");
}
}
nextLine()VS next()
next(): 입력값의 한 단어만 반환한다.
String text = "programmers love java\n"
+"userInput with java is so easy\n";
Scanner sc = new Scanner(text);
System.out.println("first call: " + sc.next());
System.out.println("second call: "+ sc.next());
first call: programmers
second call:love
nextLine(): 입력값 모든 문자열을 반환한다.
String text = "programmers love java\n"
+"userInput with java is so easy\n";
Scanner sc = new Scanner(text);
System.out.println("first call: " + sc.nextLine());
System.out.println("second call: "+ sc.nextLine());
First call : programmers love java
second call: userInput with java is so easy
Scanner 는 항상 사용 후에 close해준다.
Scanner sc = new Scanner(System.in);
sc.close();
nullPointException
null값을 while문의 기준으로 사용하려고 하면 에러가 난다.
null은 아직 객체가 만들어지지 않은 상태라서 쓸 수 없다.
Scanner sc = new Scanner(System.in);
String myInput = null; // while문에 넣을 수 없음
while(!myInput.equals("q")) {
}
sc.close();
Exception in thread "main" java.lang.NullPointerException // 객체타입이지만 객체가 없음
정수값을 문자열로 바꾸는 String.valueOf
Scanner sc = new Scanner(System.in);
String myInput = ""; //저장타입 String
do {
myInput = String.valueOf(sc.nextInt());
if(!myInput.equals("q")) {
System.out.print("입력한 내용: \n");
System.out.println(myInput);
System.out.println();
}else {
System.out.println("프로그램 종료");
}
}while(!myInput.equals("q"));
sc.close();
for문은 각각 레이블을 지정해서 , 중첩 for문안의 break문의 실행이 끝나면 전체 for문이 실행 나가고 싶을 때 쓴다.
outer: for(char upper='A';upper<='Z';upper++) {
for(char lower='a';lower<='z';lower++) {
System.out.println(upper + ":" + lower );
if(lower=='g') {
break outer; // 전체 for문을 나간다.
}
}
if(upper=='G') {
break;
}
}//end-for
continue 반복문을 나가지 않지만 , 그 구간 출력을 안한다.
for(int i=1;i<=50;i++) {
if(i%2==1) {
continue;
}
System.out.println(i);\
}
홀수빼고 출력
기본타입(byte short int long float double char boolean)은 값을 동등 비교할 때 ==나 =!을 사용한다. 스택메모리 주소만 확인하기 때문이다. heap영역에 가서 객체를 비교하지 않는다
int a = 1;
int b = 1;
(a==b) => true
객체타입인 문자열의 경우는 값을 비교할 때 .equals를 사용한다.
String name = "pudding";
String name2 = "pudding";
name.equals(name2) 이런식으로 비교 !
참고로 string은 객체타입이여도 값이 똑같다면 똑같은 메모리주소를 가지고 있음
하지만 !!!
new로 만든 객체는 무조건 주소가 다름
only stack메모리 형식으로 객체를 선언하면 메모리 주소는 같다.
String strVar1 = "홍길동";
String strVar2 = "홍길동";
String strVar3 = new String("홍길동");
String strVar4 = new String("홍길동");
System.out.println((strVar1==strVar2)); // TRUE
System.out.println((strVar3==strVar4)); //false
instance = 객체 = 프로세스 같은 말
배열은 값을 하나 바꿔도 주소값이 똑같이 나옴. 둘다 값이 똑같이 바뀜
int[] myIntArr = {1,2,3};
int[] yourIntArr = myIntArr; // {1,2,3}
yourIntArr[1]에 100추가
yourIntArr[1] = 100;
System.out.println(myIntArr);
System.out.println(yourIntArr);
for(int value : myIntArr) {
System.out.println(value);
}
for(int value : yourIntArr) {
System.out.println(value);
}
둘다 1,100,3 나옴
객체 주소값이 같기 때문에 둘다 값이 공유되게 됨
String name = "" 랑 String name = null; 의 차이
"" : 길이가 0인 String 객체를 생성함
null : 객체 생성을 안함 , stack영역에 변수이름과 null을 기록함
String myName = "";
String yourName = null;
if(!myName.equals(yourName)) {
System.out.println(" 두 변수가 다른 문자열 값을 가지고 있습니다. ");
}
if(!yourName.equals(myName)) { // 오류: NullPointerException
System.out.println(" 두 변수가 다른 문자열 값을 가지고 있습니다. ");
}
객체가 있어야 객체를 사용할 수 있는데 yourName은 객체 자체가 생성되지 않았기 때문에 NullPointerException이 일어난 것이다.
'Development (국비 복습 ) > 자바' 카테고리의 다른 글
[2023-03-20]배열복사,다차원 배열,자바 문제 (0) | 2023.03.20 |
---|---|
[2023-03-17]NullPointException,String메소드,인코딩,배열 (0) | 2023.03.17 |
[2023-03-15]for문 활용 (0) | 2023.03.15 |
[2023-03-14]연산자,캐스팅 (0) | 2023.03.14 |
[2023-03-13]메모리 구조(heap,stack영역), 기본타입 (0) | 2023.03.13 |
댓글