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

网友投稿 255 2023-01-25


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

例题:求数列的和

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

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

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

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.http://nextInt();

result=0;

for(int i=0; i

resuhttp://lt += n;

n = Math.sqrt(n);

}

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

}

}

}

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

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

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

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.spilt(" "); //按照指定字符串分割某个字符串并以字符串数组形式返回

double n=Integer.parseDouble(temp[0]);

int m=Integer.parseInt(temp[1])StAKchJG;

double result=0;

for(int i=0; i

result += n;

n = Math.sqrt(n);

}

System.out.println(result);

}

}

resuhttp://lt += n;

n = Math.sqrt(n);

}

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

}

}

}

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

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

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

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.spilt(" "); //按照指定字符串分割某个字符串并以字符串数组形式返回

double n=Integer.parseDouble(temp[0]);

int m=Integer.parseInt(temp[1])StAKchJG;

double result=0;

for(int i=0; i

result += n;

n = Math.sqrt(n);

}

System.out.println(result);

}

}

result += n;

n = Math.sqrt(n);

}

System.out.println(result);

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:全套接口自动化测试视频(自动化接口测试平台)
下一篇:SpringBoot入门之集成Druid的方法示例
相关文章

 发表评论

暂时没有评论,来抢沙发吧~