欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-21 12:12:40
例题:求数列的和 分别输入两个整数n,m,中间以空格隔断,n 为数列第一项,后面各项均为前一项的开根号,求前m项的和。 第一种从键盘输入并读取的方式:sc.hasne...

例题:求数列的和

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