I have chosen a, b, c, and f but i did not have full points only 10/20 These are
ID: 3831271 • Letter: I
Question
I have chosen a, b, c, and f but i did not have full points only 10/20
These are possible answers:
a. There is no throws FileNotFoundException between main(String[] args) and {
b. The notation int[lines][lines] magicSquare on line 14 is invalid, size is only specified on the right side of the equation.
c. The name of the magic square file does not have quotes.
d. There is no throws FileNotFoundException between public class and {
e. When creating a File object, a variable cannot be passed as an argument - it must be a hard-coded String.
f. The way that rows and columns are accessed (line 20) is backwards. Order is important. Java standardizes the order.
g. The test s.hasNextInt() should be s.hasNextDouble(), and the calls to s.nextInt() should be calls to s.nextDouble()
h. magicSquare[i][j] is not a valid way to access elements of a multidimensional array.
i. The counter variable lines commits an off-by-one error.
1 import java.io. 2 import java.util. 4 public class MagicReader public static void main (String args) String filename magic square.txt Scanner s new Scanner (new File(filename)) int lines 1; while (s.hasNextLine()) H next Line 10 lines 11 12 System. out.print un("Size of magic square lines 13 int[lines]Ilines magic Square new int llines]Ilines] s new Scanner (new File(filename)); 15 for (int i 0; S. hasNextIn i++ 16 int nextNum s.nextInt( intr i/lines 18 19 int C i lines magic Squarelr] [c] nextNum: 20 21 for (int k e: kelines k++) 22 System. out.print un( Arrays .tostring(magicsquarelkl) 23 24 25 26Explanation / Answer
package year_2017.march.secondweek;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class MagicReader {
public static void main(String[] args) throws FileNotFoundException {
String filename = "magicsquare.txt";
Scanner s = new Scanner(new File(filename));
int lines = 0;
while(s.hasNextLine()){
s.nextLine();
lines++;
}
System.out.println("Size of magic square: "+lines);
int[][] magicSquare = new int[lines][lines];
s = new Scanner(new File(filename));
for(int i=0; s.hasNextInt(); i++){
int nextNum = s.nextInt();
int r = i/lines;
int c = i%lines;
magicSquare[r][c] = nextNum;
}
for(int k=0; k<lines; k++){
System.out.println(Arrays.toString(magicSquare[k]));
}
}
}
/*
Ans:
a, b, c, i
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.