java語言的各種輸入情況(ACM常用)

來源:互聯網
上載者:User

標籤:

1.只輸入一組資料:
Scanner s=new Scanner(System.in);
int a=s.nextInt();
int b=s.nextInt();

2.輸入有多組資料,沒有說明輸入幾組資料,每組資料佔一行:
Scanner s=new Scanner(System.in);
while(s.hasnext()){//判斷是否資料結束
int a=s.nextInt();
int b=s.nextInt();
}

3.輸入多組資料,第一行為一個整數N,表示有N組測試資料,後面的接著又N組資料,每組資料佔一行;
int a;
int b;
int n;
System.out.println("請輸入一個整數n:");
Scanner in=new Scanner(System.in);
n=in.nextInt();
for(int i=0;i<n;i++){
System.out.println("請輸入一個整數a和b:");
Scanner s=new Scanner(System.in);
a=s.nextInt();
b=s.nextInt();
System.out.println(a+b);
}
3.讀入字串
輸入資料有多行,第一行是一個整數n,代表測試實數的個數,後面緊跟著n行;
System.out.println("請輸入一個整數n:");
Scanner s=new Scanner(System.in);
int n=s.nextInt();
for(int i=0;i<n;i++){
String str=s.next();
System.out.println(str);
}
或者可以這樣書寫:
System.out.println("請輸入一個整數n");
Scanner s=new Scanner(System.in);
int n=Integer.parseInt(s.nextLine());
for(int i=0;i<n;i++){
String str=s.nextLine();
System.out.println(str);
}
3.輸入字串
如給定一個日期,輸出這個日期是該年的第幾天?
System.out.println("請輸入一個年份");
Scanner s=new Scanner(System.in);
int dd[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
while(s.hasNext()){
int days=0;
String str=s.nextLine();
String[] date=str.split("/");
int y=Integer.parseInt(date[0]);
int m=Integer.parseInt(date[1]);
int d=Integer.parseInt(date[2]);
if((y%400 == 0 || (y%4 == 0 && y%100 !=0)) && m>2) days ++;
days += d;
for(int i=0;i<m;i++){
days += dd[i];
}
System.out.println(days);
}

java語言的各種輸入情況(ACM常用)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.