当前位置: 移动技术网 > IT编程>开发语言>Java > Java中从键盘输入多个整数的方法

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

例题:求数列的和

分别输入两个整数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.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() 按照指定字符(串)或正则去分割某个字符串 ,结果以字符串数组形式返回

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]); 
        double result=0;
 
        for(int i=0; i<m; i++){
	    	result += n;
	    	n = math.sqrt(n);
        }
        system.out.println(result);
	}
}

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网