자바 시리즈 12 - Scanner 와 String 류 의 사용
                                            
 91179 단어  Java자바문자열프로 그래 밍 언어
                    
1. Scanner 의 사용
/**
 * Scanner   
 * 	1、JDK5  ,          
 * 
 * 	2、    :
 * 		public Scanner(InputStream is)
 * 		Scanner sc = new Scanner(System.in);
 * 
 * 	3、    :
 * 		A:hasNextXxx()	     xxx     
 * 		B:nextXxx() 	  xxx     
 * 
 * 	4、       
 * 		nextInt():	    int     
 * 		next()/nextLine():	    String     
 * 
 *  5、      :
 *  	int  	--->	int
 *  	String	--->	String
 *  	String	--->	int
 *  	int		--->	String
 *  	
 *  	    :
 * 			A:      String  ,     ,      
 * 			B:        Scanner  
 * */
import java.util.Scanner;
public class ScannerTest001 {
	
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		if(sc.hasNextInt()) {
			int number = sc.nextInt();
			System.out.println("number"+number);
		}else {
			String str1 = sc.nextLine();
			System.out.println("str1"+str1);
		}
		
		int x = sc.nextInt();
		
		sc = new Scanner(System.in);
		
		String y = sc.nextLine(); //          
		System.out.println(x);
		System.out.println(y);	
	}
}
  2. String 류
/**
 * 	1、   :            
 * 
 * 	2、     :	
 * 		public String():  String  
 * 		public String(byte[] bytes):          
 * 		public String(byte[] bytes,int index,int length):              
 * 		public String(char[] value):          
 * 		public String(char[] bytes,int index,int length):              
 * 		public String(byte[] bytes):          
 * 		public String(String original):         
 * 
 * 	3、  :
 * 		1、               ,          toString()  。
 * 			toString()          ...  @        
 * 			             ,        ,       toString()  
 * 		2、        
 * 			public int length()
 * 
 * 		   :   length() ?String length() ?
 * 				  				 
 * 		
 * 	4、      ,           
 * 
 * 	5、String s =  new String("hello"); String s = "hello";   
 * 		==:              
 * 		equals():         。String    equals()  ,                   
 * 
 * */
public class StringTest001 {
	int number=1;
	
	public static void main(String[] args) {
		// public String()    String  
		String s1 = new String();
		System.out.println("s1:"+s1);
		System.out.println("s1.length():"+s1.length());
		System.out.println("--------------------------");
		
		// public String(byte[] bytes):          。
		byte[] bytes = { 97, 98, 99, 100, 101 };
		String s2 = new String(bytes); //            
		System.out.println("s2:" + s2);
		System.out.println("s2.length():" + s2.length());
		System.out.println("--------------------------");
		
		// public String(byte[] bytes,int index,int length):               
		// String s3 = new String(bytes, 1, 2);
		String s3 = new String(bytes, 0, bytes.length);
		System.out.println("s3:" + s3);
		System.out.println("s3.length():" + s3.length());
		System.out.println("--------------------------");
		// public String(char[] value):          
		char[] chs = { 'a', 'b', 'c', 'd', 'e', ' ', ' ', ' ' };
		String s4 = new String(chs);
		System.out.println("s4:" + s4);
		System.out.println("s4.length():" + s4.length());
		System.out.println("--------------------------");
	
	
		// public String(char[] value,int index,int count):              
		//   :         :de  
		String s5 = new String(chs, 3, 4);
		System.out.println("s5:" + s5);
		System.out.println("s5.length():" + s5.length());
		System.out.println("--------------------------");
	
		// public String(String original):         
		String s6 = new String("helloworld");
		System.out.println("s6:" + s6);
		System.out.println("s6.length():" + s6.length());
		System.out.println("--------------------------");
	
		// Java             (  "abc" )          。
		String s7 = "helloworld";
		System.out.println("s7:" + s7);
		System.out.println("s7.length():" + s7.length());
		
		//            ,           
		String s8 = "hello";
		s8 += "\tworld";
		System.out.println("s8:"+s8);
		}
		
		//     toString,         ,         
		public String toString() {
			return "111";
		}
}
 /**
 * 	== equals   
 * */
public class StringTest003 {
	public static void main(String[] args) {
		// == equal   
		String s1 = new String("abc");
		String s2 = new String("abc");
		System.out.println(s1==s2);			// false	
		System.out.println(s1.equals(s2));	// true
		
		
		String s3 = "abc";
		String s4 = "abc";
		System.out.println(s3==s4);			// true	
		System.out.println(s3.equals(s4));	// true
		
		String s5 = "abc";
		String s6 = new String("abc");
		System.out.println(s5==s6);			// false	
		System.out.println(s5.equals(s6));	// true
	}
}
 연습: 프로그램 보고 결과 말 하기 /**
 * 	      
 * 	       :    ,    
 * 	       :  ,  ,      
 * */
public class StringTest004 {
	public static void main(String[] args) {
		
		String s1 = "Hello";	
		String s2 = "World";
		String s3 = "HelloWorld";
		String s4 = s1 + s2;
		String s5 = "Hello" + "World";
		System.out.println(s4);
		System.out.println(s5);
		
		System.out.println(s3==s4);				// false
		System.out.println(s3=="Hello"+"World");// true	
		System.out.println(s3==s5);				// true	
		System.out.println(s3.equals(s4));		// true
		System.out.println(s3.equals(s5));		// true
	}
}
 /**
 * 	String      
 * 	boolean equals(Object obj):            ,       
 * 	boolean equalsIgnoreCase(String str):            ,      
 * 	boolean contains(String str):           ,     
 * 	boolean startsWith(Stirng str):             
 * 	boolean endsWith(String str):             
 * 	boolean isEmpty():            		
 * 
 * */
public class StringDemo {
	public static void main(String[] args) {
		String s = "helloworld";
		System.out.println(s.equals("helloworld")); // true
		System.out.println(s.equals("Helloworld")); // false
		
		System.out.println(s.equalsIgnoreCase("helloworld")); // true
		System.out.println(s.equalsIgnoreCase("Helloworld")); // true
		
		System.out.println(s.contains("world")); 	// true
		System.out.println(s.contains("Hello")); 	// false
		
		System.out.println(s.startsWith("hello"));	// true
		System.out.println(s.endsWith("wrold"));	// false
		
		String s1 = "";
		System.out.println(s1.isEmpty());	// true
		System.out.println(s1 == "");		// true
	}
}
 사례 연습: /**
 * 	       :			
 * 		               ,         
 * */
import java.util.Scanner;
public class StringTest001 {
	public static void main(String[] args) {
		String username = "admin";
		String password = "admin";
		System.out.println("--------------------------");
		System.out.println("        ");
		System.out.println("             ");
		System.out.println("             ");
		System.out.println("    !");
		System.out.println("--------------------------");
		int i = 3;
		while(i>0) {
			Scanner sc = new Scanner(System.in);
			String sc_username = sc.next();
			System.out.println(sc_username);
			if (sc_username.equals(username)) {
				String sc_password = sc.next();
				if (sc_password.equals(password)) {
					System.out.println("    ");
					break;
				}
			}
			i-=1;
			if (i==0) {
				System.out.println("      ,      ");
			}else {
			System.out.println("   "+i+"   ");
			}
		}
	}
	
}	
 /**
 * 	String      :
 * 		int length():        
 * 		char charAt(int index):             
 * 		int indexOf(int ch):                 
 * 		int indexOf(Stirng str):                    
 * 		int indexOf(String str,int fromIndex):                           
 * 		String substring(int start):               
 * 		String substring(int start,int end):                   ,  :     
 * 
 * */
public class StringDemo {
	
	public static void main(String[] args) {
		
		String str1 = "hello";
		System.out.println(str1.length());  		// 5
		System.out.println(str1.charAt(1)); 		// e
		// System.out.println(str1.charAt(10)); 	// index of range
		System.out.println(str1.indexOf('h')); 		// 0
		System.out.println(str1.indexOf("h")); 		// 0
		System.out.println(str1.indexOf('l',3)); 	// 3
		System.out.println(str1.substring(0)); 		// hello
		System.out.println(str1.substring(0,3)); 	// hel
	}
}
 연습 1: 작은 문자열 마다 옮 겨 다 니 기 /**
 * 	       :
 * 		        
 * 
 * */
public class StringTest001 {
	
	public static void main(String[] args) {
		String s1 = "HelloWorld";
		for(int index=0;index<s1.length();index++) {
			System.out.println("   "+index+"  "+s1.charAt(index));
		}
	}
}
 연습 2: 통계 문자열 개수 /**
 * 	            :    :
 * 		      
 * 		      
 * 		    
 * 
 * */
import java.util.Scanner;
public class StringTest002 {
	
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		int bigCount= 0;
		int smallCount= 0;
		int intCount= 0;
		
		for(int i=0;i<s.length();i++) {
			char ch = s.charAt(i);
			if(ch >= 'A' && ch <= 'Z') {
				bigCount+=1;
			}else if(ch >= 'a' && ch <= 'z') {
				smallCount+=1;
			}else if(ch >= '0' && ch <= '9') {
				intCount+=1;
			}
		}
		System.out.println("     :"+bigCount);
		System.out.println("     :"+smallCount);
		System.out.println("   :"+intCount);
	}
}
 package com.bj.study.test006;
/**
 * 	String     
 * 		byte[] getBytes():           
 * 		char[] toCharArray():           
 * 		static String valueOf(char[] chs):           
 * 		static String valueOf(int i): int          
 * 										              。
 * 		String toLowerCase():       
 * 		String toUpperCase():       
 * 		String concat(String str):      
 * 
 * */
public class StringDemo {
	public static void main(String[] args) {
		
		String s = "abcde";
		// byte[] getBytes():           
		byte[] bys = s.getBytes();
		for (int x = 0; x < bys.length; x++) {
			System.out.println(bys[x]);
		}
		
		// char[] toCharArray():           
		char[] chs = s.toCharArray();
		System.out.println(chs);
		for (int x = 0; x < chs.length; x++) {
			System.out.println(chs[x]);
		}
		
		// static String valueOf(char[] chs):          
		String s2 = String.valueOf(chs);
		System.out.println("s2:" + s2);
		System.out.println("----------------");
		// static String valueOf(int i): int          
		int number = 100;
		String s3 = number + "";
		String s4 = String.valueOf(number);
		System.out.println("s3:" + s3);
		System.out.println("s4:" + s4);
		System.out.println("----------------");
		// String toLowerCase():       
		// String toUpperCase():       
		System.out.println("toLowerCase():" + "HelloWorld11  ".toLowerCase());
		System.out.println("toUpperCase():" + "HelloWorld11  ".toUpperCase());
		System.out.println("----------------");
		// String concat(String str):      
		String s5 = "hello";
		String s6 = "world";
		String s7 = s5.concat(s6);
		String s8 = s5 + s6;
		System.out.println("s7:" + s7);
		System.out.println("s8:" + s8);
		
	}
}
 연습: 문자열 변환 /**
 * 	  :            :
 * 		         ,       
 * 
 * */
import java.util.Scanner;
public class StringTest001 {
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		String first = s.substring(0,1).toUpperCase();
		String end = s.substring(1).toLowerCase();
		
		String newWords = first+end;
		System.out.println(newWords);
	}
}
 /**
 * 	     
 * 		String replace(char old,char new)
 * 		String replace(String old,String new)
 * 
 * 	       :
 * 		String trim():       
 * 	
 *	            :a-z
 * 	 	int compareTo(String str)
 * 		int compareToIgnoreCase(String str) 
 * 
 * */
public class StringDemo {
	
	public static void main(String[] args) {
		String s = "helloworld";
		String s2 = s.replace('l', 'b');
		System.out.println("s:" + s);
		System.out.println("s2:" + s2);
		String s3 = s.replace("owo", "ak47");
		String s4 = s.replace("j", "h");
		System.out.println("s3:" + s3);
		System.out.println("s4:" + s4);
		
		String s5 = "    hello     ";
		System.out.println("s5:" + s5);
		System.out.println("s5.trim:" + s5.trim());
		
		String s6 = "hello";
		System.out.println(s.compareTo("hello")); // 0
		System.out.println(s.compareTo("Hello")); // 32
		System.out.println(s.compareTo("mello")); // -5
		System.out.println(s.compareTo("hgllo"));//           -2
	}
}
 연습 1: 배열 의 데 이 터 를 지정 한 형식 으로 문자열 로 연결 /**
 * 	  :                     
 * 			  :int[] arr = {1,2,3}
 * 			  :[1,2,3]
 * 
 * */
public class StringDemo2 {
	public static void main(String[] args) {
		
		int[] arr = {1,2,3};
		String s = "[";
		for(int i=0;i<arr.length;i++) {
			if(i==arr.length-1) {
				s += arr[i];
			}else {
				s += arr[i]+",";
			}
		}
		s += "]";
		System.out.println(s);
	}
}
 연습 2: 반전 문자열 /**
 * 	  :             	
 * 		 :  abc	
 * 			  :cba
 * */
import java.util.Scanner;
public class StringDemo3 {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		String s = sc.nextLine();
		
		String result = "";
		for (int i=s.length()-1;i>=0;i--) {
			result += s.charAt(i);
		}
		System.out.println(result);
	}
}
 연습 3: 긴 문자열 중 작은 문자열 의 출현 횟수 찾기 /**
 * 	  4:                   
 * */
public class StringDemo4 {
	public static void main(String[] args) {
		String maxString = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";
		String minString = "java";
		int count = getCount(maxString, minString);
		System.out.println(count);
		System.out.println("hello".indexOf("z",0));
		
	}
	//      :
	//     :String maxString,String minString;
	//      :int
	public static int getCount(String maxString, String minString) {
		//       
		int count = 0;
		//      
		int index = maxString.indexOf(minString);
		//       ,             
		int startIndex = 0;
		//        -1,   ,     
		while (index != -1) {
			//      1
			count++;
			//          
			startIndex = index + minString.length();
			//         ,               
			index = maxString.indexOf(minString, startIndex);
		}
		return count;
	}
}
 연습 5: 두 문자열 의 일치 여 부 를 비교 package com.bj.study.test007;
/**
 * 	  5:       ,           
 * 
 * 	  :
 * 		A:       
 * 		B:        ,    false
 * 		C:           
 * 		D:            
 * */
public class StringDemo5 {
	
	public static void main(String[] args) {
		String s1 = "abcdef";
		String s2 = "abcd";
		boolean result = checkString(s1,s2);
		System.out.println(result);
	}
	private static boolean checkString(String s1, String s2) {
		if (s1.length() == s2.length()) {
			for(int i=0;i<s1.length();i++) {
				if(s1.charAt(i) == s2.charAt(i)) {
					return true;
				}
			}
			return false;
		}
		return false;
	}
	
}
 이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.