慕課網-安卓工程師初養成-5-3 編程練習最佳化

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   java   ar   for   div   

來源:http://www.imooc.com/video/1626

使用Scanner工具類來擷取使用者輸入的成績資訊

Scanner類位於java.util包中,使用時需要匯入此包

步驟:

1.匯入java.util.Scanner

2.建立Scanner對象

3.接收並儲存使用者輸入的值

原來的代碼:

 1 package com.imooc; 2  3 public class HelloWorld { 4     public static void main(String[] args) { 5         // 變數儲存成績 6         int score = 53;  7          8         // 變數儲存加分次數 9         int count = 0;10 11         //列印輸出加分前成績 12         System.out.println("加分前成績: "+score);13         14         // 只要成績小於60,就迴圈執行加分操作,並統計加分次數15         for (; score + count < 60; count++) {16             17         }18                 19         //列印輸出加分後成績,以及加分次數20         System.out.println("加分後成績: "+(score + count));21         System.out.println("總共加了"+count+"次!");22         System.out.println();23     }24 }

需要改成讓使用者輸入成績,改成如下

 1 package com.imooc; 2 import java.util.Scanner;    //寫在package後面 3  4 public class HelloWorld { 5     public static void main(String[] args) { 6         Scanner input=new Scanner(System.in);     //建立Scanner對象 7         System.out.println("請輸入考試成績資訊: "); 8          9         int score = input.nextInt();     // 擷取使用者輸入的成績並儲存在變數中10         11         // 變數儲存加分次數12         int count = 0;13 14         //列印輸出加分前成績 15         System.out.println("加分前成績: "+score);16         17         // 只要成績小於60,就迴圈執行加分操作,並統計加分次數18         for (; score + count < 60; count++) {19             20         }21                 22         //列印輸出加分後成績,以及加分次數23         System.out.println("加分後成績: "+(score + count));24         System.out.println("總共加了"+count+"次!");25         System.out.println();26     }27 }

結果為(輸入的是47):

請輸入考試成績資訊: 47加分前成績: 47加分後成績: 60總共加了13次!

從以上可知,提示資訊"請輸入考試成績資訊:"和使用者輸入不在同一行
如果修改才能在同一行呢?

可以把System.out.println("請輸入考試成績資訊: "); 中的 println 改成 print

兩者區別在於,println輸出帶換行,而print不帶換行

結果如下:

請輸入考試成績資訊: 53加分前成績: 53加分後成績: 60總共加了7次!

 

慕課網-安卓工程師初養成-5-3 編程練習最佳化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.