I'm working on simple code that is to read input where:
- The first line is a number of cases to consider.
- The next lines are integers separated by a space that will be tested lately.
Possible input:
2
3 4
4 5
Possible output (just some multiplication example):
12
20
Questions:
- I would like to know if there are 'better' ways to handle this kind of input.
What could be done to make this code more universal? For example, there is a variable
int lineLength=3
and I have to modify It for other similar input (wherelineLength
is bigger):2 3 4 5 4 5 6
What validation should be implemented (if someone gives bad input, maybe it could be done in X ways (the handling))?
- Do I break any good-programming rules? (I intended to write this only in class
Main
)
import java.io.IOException;
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
/** Reading number of tests (NO VALIDATION) **/
/** nextInt() doesnt read the last newline character of input **/
Scanner read = new Scanner(System.in);
int numberOfTests = read.nextInt();
/** Consuming newline character**/
read.nextLine();
String line[] = new String[numberOfTests];
/** Reading line excluding line separator at the end (NO VALIDATION) **/
for (int i = 0; i < numberOfTests; i++)
line[i] = read.nextLine();
/** Printing array of String(lines) **/
System.out.print(Arrays.toString(line));
/** Creating the array of ints (NO VALIDATION) **/
int lineLength = 3;
int num[][] = new int[numberOfTests][lineLength];
/** Extracting integers from line **/
for (int i = 0; i < numberOfTests; i++) {
int k = 0;
for (int j = 0; j < lineLength; j++) {
if (Character.isSpaceChar((line[i].charAt(j))) != true) {
num[i][k++] = Character.getNumericValue(line[i].charAt(j));
}
}
}
/** Printing array of integers to test **/
int numToTests = 2;
for (int i = 0; i < numberOfTests; i++) {
System.out.println();
for (int j = 0; j < numToTests; j++) {
System.out.print(num[i][j]+" ");
}
}
}
}