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]. If the int is 7 it should print the first seven 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. And the elements must be in the same line. Input should be like "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:
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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.