Reputation:
I have a question about using java.util.Scanner class to read input.
Below is my coding without using java.util.Scanner class to read input:
public class NewTry {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
float[][] a = new float[][] { { 1.513f, 2.321f, 3.421f }, { 4.213f, 5.432f, 6.123f },
{ 7.214f, 8.213f, 9.213f } };
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
Show output without using java.util.Scanner:
run:
1.513 2.321 3.421
4.213 5.432 6.123
7.214 8.213 9.213
BUILD SUCCESSFUL (total time: 3 seconds)
My problem is how to add java.util.Scanner class to read input without default float number in the coding? Is using array run scanner?
Actually I want the sample output same like the below (the float number must key in myself):
run:
Type nine float numbers two-dimensional array of similar type and size with line breaks, end
by"-1":
1.513
2.321
3.421
4.213
5.432
6.123
7.214
8.213
9.213
-1
The result is:
1.513 2.321 3.421
4.213 5.432 6.123
7.214 8.213 9.213
BUILD SUCCESSFUL (total time: 11 second)
Hope someone can guide me or modified my coding to add java.util.Scanner class to read input .Thanks.
Upvotes: 1
Views: 103
Reputation: 1369
Check this out
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println ("Type nine float numbers two-dimensional array of similar type and size with line breaks, end by -1:");
float[][] a = new float[3][3];
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
You should define a new Scanner (sc) and then loop 3 x 3 times until you read all input. If the user enters -1 the loop ends. Note that you do not need to exit when 9 numbers are entered.
Also each user input is read as a line and not as a token, and then is parsed into a Float. If the user enters a String that is not a float number then it throws an Exception.
Sample:
Type nine float numbers two-dimensional array of similar type and size with line breaks, end by -1:
1.1
1.2
1.3
2.1
2.2
2.3
3.1
3.2
3.3
The result is:
1.1 1.2 1.3
2.1 2.2 2.3
3.1 3.2 3.3
Upvotes: 1
Reputation: 156
Scanner scan =new Scanner(System.in);
float[][] a = new float[3][3];
for(int i =0 ;i<3;i++) {
for(int j=0; j<3; i++) {
a[i][j] =scan.Float();
}
}
Upvotes: 0