控制台输入
以下输入方法用于在控制台中进行输入,当输入当个换行符时,结束输入。但不适合在做算法题目是使用,可能是因为算法题目中用的是流的方式进行输入,最后不会输入多一个换行符,因而无法正确的结束输入而导致答案错误。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
import java.util.scanner;
public class main {
public static void main(string[] args) {
inputstr(); input int eger(); inputintinline();
} //每行输入一个数值,输入多个数值 public static void inputinteger() { scanner scanner = new scanner(system.in); string nextline = scanner.nextline(); int sum = 0 ;
while (nextline != null && !nextline.equals( "" )) { sum += integer.parseint(nextline); system.out.println(sum); nextline = scanner.nextline(); }
system.out.println( "end of input integer" ); } // 每行输入一个 字符串 ,输入多个字符串 public static void inputstr() { scanner scanner = new scanner(system.in); string nextline = scanner.nextline(); while (nextline != null && !nextline.equals( "" )) { system.out.println(nextline); nextline = scanner.nextline(); }
system.out.println( "end of input string" ); } //输入多个数值,用空格隔开 public static void inputintinline() { scanner scanner = new scanner(system.in); string str = scanner.nextline(); string[] numstr = str.split( " " ); int [] nums = new int [numstr.length]; for ( int i = 0 ; i < numstr.length; i ++) { nums[i] = integer.parseint(numstr[i]); } for ( int n: nums) { system.out.println(n); } system.out.println( "end of input int in a line" );
} } |
做算法题目时用的输入
以下方法在做算法题目时能够正确的结束输入。
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.scanner;
public class main{ public static void main(string[] args){ scanner in = new scanner(system.in); // while(in.hasnextline()){ while (in.hasnext()){ string str = in.nextline(); system.out.println(str); } } } |
以上这篇java 输入多行字符串或者多个int数值的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
原文链接:https://blog.csdn.net/DoneSpeak/article/details/77800632
查看更多关于Java 输入多行字符串或者多个int数值的方法的详细内容...