好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java中从键盘输入多个整数的方法

例题:求数列的和

分别 输入 两个 整数 n,m,中间以空格隔断,n 为数列第一项,后面各项均为前一项的开根号,求前m项的和。

第一种从键盘输入并读取的方式:sc.hasnextint() 函数和sc.nextint()函数

hasnextint() 判断当前输入的是否是整数

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

import java.util.scanner;

import java.lang.math.*;

 

class test1{

     public static void main(string [] args){

      scanner sc= new scanner(system.in);

      int m;

      double n,result;

 

      while (sc.hasnextint()){

         n=sc.nextint();

         m=sc.nextint();

         result= 0 ;

 

         for ( int i= 0 ; i<m; i++){

             result += n;

             n = math.sqrt(n);

           }

       system.out.printf( "%.2f" ,result);

 

      }

     }

 

}

第二种方式:sc.trim()函数 和sc.split()函数

sc.trim() 去掉字符串首尾空格

sc.split() 按照指定字符(串)或正则去分割某个字符串 ,结果以字符串数组形式返回

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import java.util.scanner;

import java.lang.math.*;

 

class test{

     public static void main(){

         scanner sc= new scanner(system.in);

         string input=sc.nextline();

         input=input.trim(); //去掉字符串首尾空格

         string[] temp=input.split( " " ); //按照指定字符串分割某个字符串并以字符串数组形式返回

         double n=integer.parsedouble(temp[ 0 ]);

         int m=integer.parseint(temp[ 1 ]);

         double result= 0 ;

 

         for ( int i= 0 ; i<m; i++){

             result += n;

             n = math.sqrt(n);

         }

         system.out.println(result);

     }

}

以上这篇java中从键盘输入多个整数的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/hujiajie0131/article/details/78023521

查看更多关于Java中从键盘输入多个整数的方法的详细内容...

  阅读:43次