java中的nextInt()等


若n=sc.nextInt()輸入一個數字,然后若后面有String str=sc.nextLine();語句會出現錯誤,

nextLine()自動讀取了被next()去掉的Enter作為台的結束符,所以沒辦法給從鍵盤給str輸入值,其他的next()用法,如double nextDouble()。float nextFloat(),int nextInt()

等與nextLine()連用時都存在這個問題,解決是在next()后面加一個nextLine()語句,將被next()去掉的enter結束符過濾掉

public class RightId {

	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		sc.nextLine();//過濾掉enter
		while(n--!=0){
			String str=sc.nextLine();
			int count=0;
			if(str.charAt(0)>='a'&&str.charAt(0)<='z'||str.charAt(0)>='A'&&str.charAt(0)<='Z'||str.charAt(0)=='_'){
				for(int i=1;i<str.length();i++){
					if(str.charAt(i)>='a'&&str.charAt(i)<='z'||str.charAt(i)>='A'&&str.charAt(i)<='Z'||str.charAt(i)=='_'||str.charAt(i)>='0'&&str.charAt(i)<='9'){
						count++;
					}
					else{
						System.out.println("no");
						break;
					}
				}
				if(count==str.length()-1){
					System.out.println("yes");
				}
		}
			else{
				System.out.println("no");
			}
		}		
		}
}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM