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

2025-05-29 0 21

例题:求数列的和

分别输入两个整数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中从键盘输入多个整数的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java中从键盘输入多个整数的方法 https://www.kuaiidc.com/111447.html

相关文章

发表评论
暂无评论