[英]How to print the first elements of an array according to an int?
I have an array of chars, I need to print in the console its first chars according to an int, so if the int is equal to 3, it should print args[0], args[1], args[2]. 我有一个字符数组,我需要根据一个int在控制台中打印其第一个字符,因此,如果int等于3,则应打印args [0],args [1],args [2]。 If the int is 7 it should print the first seven args.
如果int为7,则应打印前七个args。
Scanner scanner = new Scanner(System. in);
char[] arguments = scanner.nextLine().toCharArray();
scanner.close();
int i1 = 0;
while (i1 <= arguments.length) {
System.out.println("???");
i1 = i1++;
}
The int can be every number, so I can't just do a switch statement because it would be too long. 整数可以是每个数字,所以我不能只做一个switch语句,因为它太长了。 And the elements must be in the same line.
并且元素必须在同一行。 Input should be like "ABCDEF"/"ABC".
输入应类似于“ ABCDEF” /“ ABC”。
public static void main(String[] args) {
Scanner scanner = new Scanner(System. in);
// array of characters given by user
char[] arguments = scanner.nextLine().toCharArray();
// the value of int given by user i.e how many characters need to print
int intNumber = scanner.nextInt();
// closing the connection for scanner
scanner.close();
//for loop that execute till the given value of int
for(int i=0; i<intNumber; i++) {
//condition check to avoid ArrayIndexOutOfBoundsException
if(i < arguments.length)
// For printing characters in single line
System.out.print(arguments[i]);
}
//Index provided by user
int index = input.nextInt();
//For loop which iterates over the array from the beginning to the input index
for (int currentIndex = 0; currentIndex < index; currentIndex++) {
//Printing the current array character
System.out.print(arr[currentIndex]);
}
//Printing line when loop has finished traversing
System.out.println();
IntStream.range(0, num).forEach(x -> System.out.print(charArray[x]));
如果您更喜欢Java8,则此代码段将帮助您解决该问题。
If you don't want top use Streams, why not: 如果您不希望使用Streams,请为什么:
String s = scanner.nextLine();
int end = Math.min(n,s.length());
System.out.println( s.substring(0,end) );
where n is the number of characters? 其中n是字符数?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.