I have a simple Java program that seems to work well until uploaded to my school's grading system, "WebCat", which I'm assuming is just running JUnit. The error it kicks back is:
Forked Java VM exited abnormally. Please note the time in the report does not reflect the >time until the VM exit.
I've researched this issue and and the main first troubleshooting step seems to be to look at the dump log. Unfortunately I cannot do that in this case. I am really at a loss on how to begin to troubleshoot this considering the lack of feedback from the grading system and the lack of compile or run-time errors.
Here is the code if anyone is familiar with this error or can at least give me some direction of where to begin troubleshooting. Much appreciated!
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.io.IOException;
class PlayerApp {
public static void showMenu()
{
System.out.println("Player App Menu");
System.out.println("P - Print Report");
System.out.println("A - Add Score");
System.out.println("D - Delete Score");
System.out.println("L - Find Lowest Score");
System.out.println("H - Find Highest Score");
System.out.println("Q - Quit");
}
public static void main(String[] args) throws IOException
{
if (args.length == 0)
{
System.out.println("File name was expected as a run argument.");
System.out.println("Program ending.");
System.exit(0);
}
String fileName = args[0];
Scanner sc = new Scanner(System.in);
String stnew = "";
boolean exit = false;
Player p = null;
double[] scoreList;
File dbFile = new File(fileName);
FileInputStream fis = new FileInputStream(fileName);
InputStreamReader inStream = new InputStreamReader(fis);
BufferedReader stdin = new BufferedReader(inStream);
String name = stdin.readLine();
stnew = stdin.readLine();
int numScore = Integer.parseInt(stnew);
scoreList = new double[numScore];
for (int i = 0; i < numScore; i++)
{
stnew = stdin.readLine();
scoreList[i] = Double.parseDouble(stnew);
}
p = new Player(name, numScore, scoreList);
stdin.close();
System.out.println("File read in and Player object created.");
showMenu();
while (exit == false)
{
System.out.print("\nEnter Code [P, A, D, L, H, or Q]:");
String choice = sc.nextLine().toLowerCase();
if (choice.equals("p"))
{
System.out.println(p.toString());
}
else if (choice.equals("a"))
{
System.out.print(" Score to add: ");
stnew = sc.nextLine();
double scoreIn = Double.parseDouble(stnew);
p.addScore(scoreIn);
}
else if (choice.equals("d"))
{
System.out.print(" Score to delete: ");
stnew = sc.nextLine();
double scoreIn = Double.parseDouble(stnew);
p.deleteScore(scoreIn);
System.out.println(" Score removed.");
}
else if (choice.equals("l"))
{
System.out.println(" Lowest score: " + p.findLowestScore());
}
else if (choice.equals("h"))
{
System.out.println(" Highest score: " + p.findHighestScore());
}
else if (choice.equals("q"))
{
exit = true;
}
}
}
}
break
import java.text.DecimalFormat;
public class Player {
//Variables
private String name;
private int numOfScores;
private double[] scores = new double[numOfScores];
//Constructor
public Player(String nameIn, int numOfScoresIn, double[] scoresIn) {
name = nameIn;
numOfScores = numOfScoresIn;
scores = scoresIn;
}
//Methods
public String getName() {
return name;
}
public double[] getScores() {
return scores;
}
public int getNumScores() {
return numOfScores;
}
public String toString() {
String res = "";
DecimalFormat twoDForm = new DecimalFormat("#,###.0#");
DecimalFormat twoEForm = new DecimalFormat("0.0");
res += " Player Name: " + name + "\n Scores: ";
for (int i = 0; i < numOfScores; i++)
{
res += twoDForm.format(scores[i]) + " ";
}
res += "\n Average Score: ";
res += twoEForm.format(this.computeAvgScore());
return res;
}
public void addScore(double scoreIn) {
double newScores[] = new double[numOfScores +1 ];
for (int i = 0; i < numOfScores; i++)
{
newScores[i] = scores[i];
}
scores = new double[numOfScores + 1];
for(int i = 0; i < numOfScores; i++)
{
scores[i] = newScores[i];
}
scores[numOfScores] = scoreIn;
numOfScores++;
}
public boolean deleteScore(double scoreIn) {
boolean found = false;
int index = 0;
for (int i = 0; i < numOfScores; i++)
{
if (scores[i] == scoreIn)
{
found = true;
index = i;
}
}
if (found == true)
{
double newScores[] = new double[numOfScores -1 ];
for (int i = 0; i < index; i++)
{
newScores[i] = scores[i];
}
for (int i = index + 1; i < numOfScores; i++)
{
newScores[i - 1] = scores[i];
}
scores = new double[numOfScores - 1];
numOfScores--;
for (int i = 0; i < numOfScores; i++)
{
scores[i] = newScores[i];
}
return true;
}
else
{
return false;
}
}
public void increaseScoresCapacity()
{
scores = new double[numOfScores + 1];
numOfScores++;
}
public double findLowestScore() {
double res = 100.0;
for (int i = 0; i < numOfScores; i++)
{
if (scores[i] < res)
{
res = scores[i];
}
}
return res;
}
public double findHighestScore() {
double res = 0.0;
for (int i = 0; i < numOfScores; i++)
{
if (scores[i] > res)
{
res = scores[i];
}
}
return res;
}
public double computeAvgScore() {
double res = 0.0;
if (numOfScores > 0) {
for (int i = 0; i < numOfScores; i++)
{
res += scores[i];
}
return res / (double)(numOfScores);
}
else {
//res = 0.0;
return res;
}
}
}
Your program is calling System.exit(0) for certain inputs. Don't do that! That's exactly what the message is telling you: that the JVM exited in the middle of the text, before the scoring code could finish up. Instead of calling exit(), just use return to return from main() early.
The library System Rules has a JUnit rule called ExpectedSystemExit. With this rule you are able to test code, that calls System.exit(...).
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I am getting an error that says Index 4 out of bounds for length 4 and i'm not sure what that means. I someone could please tell me what and where the error is it would be greatly appreciated.
The error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
My code:
package HW8;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class GradeBookDemo {
public static void main(String[] args) throws IOException {
GradeBook gradebook = new GradeBook();
File file = new File("StudentInfo.txt");
Scanner inputfile = new Scanner(file);
// read the student information
while (inputfile.hasNextLine()) {
for (int index = 0; index < 5; index++) {
String name = inputfile.nextLine();
gradebook.setName(index, name);
double[] scores = new double[4];
for (int i = 0; i < 4; i++) {
scores[index] = inputfile.nextDouble();
}
gradebook.setScore(index, scores);
inputfile.nextLine();
}
for (int index = 0; index < 5; index++) {
System.out.println("Student name: " + gradebook.getName(index));
System.out.println("Student average: " + gradebook.getAverage(index));
System.out.println("Student grade: " + gradebook.getLetterGrade(index));
System.out.println("");
}
}
}
}
My other code:
package HW8;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
public class GradeBook {
private int NUM_STUDENT = 5;
private int NUM_TESTS = 4;
private String[] names = new String[5]; // Array to hold student names
private char[] grades = new char[5]; // Array to hold student grades
// Create arrays of scores, one for each student
private double[] scores1 = new double[NUM_TESTS];
private double[] scores2 = new double[NUM_TESTS];
private double[] scores3 = new double[NUM_TESTS];
private double[] scores4 = new double[NUM_TESTS];
private double[] scores5 = new double[NUM_TESTS];
// Create setName and setScore methods
public void setName(int studentNumber, String name) {
names[NUM_STUDENT - 1] = name;
}
public void setScore(int studentNumber, double[] scores) {
if (studentNumber == 1) {
copyArray(scores1, scores);
} else if (studentNumber == 2) {
copyArray(scores2, scores);
} else if (studentNumber == 3) {
copyArray(scores3, scores);
} else if (studentNumber == 4) {
copyArray(scores4, scores);
}
if (studentNumber == 5) {
copyArray(scores5, scores);
}
}
public String getName(int studentNum) // create getName method
{
return names[studentNum - 1];
}
public double getAverage(int studentNum) { // create getAverage method
if (studentNum == 1) {
return calcAverage(scores1);
} else if (studentNum == 2) {
return calcAverage(scores2);
} else if (studentNum == 3) {
return calcAverage(scores3);
} else if (studentNum == 4) {
return calcAverage(scores4);
}
if (studentNum == 5) {
return calcAverage(scores5);
}
return studentNum;
}
public char getLetterGrade(int studentNum) {
assignGrade(studentNum);
return grades[studentNum - 1];
}
private void copyArray(double[] to, double[] from) {
for (int i = 0; i < NUM_TESTS; i++) {
to[i] = from[i];
}
}
private double calcAverage(double[] scores) {
double total = 0;
for (int i = 0; i < scores.length; i++) {
total += scores[i];
}
double average = total / NUM_TESTS;
return average;
}
private void assignGrade(int studentNum) {
double average = getAverage(studentNum);
grades[studentNum - 1] = determineGrade(average);
}
private char determineGrade(double average) {
if (average >= 90.0) {
return 'A';
} else if (average >= 80.0) {
return 'B';
} else if (average >= 70.0) {
return 'C';
} else {
return 'D';
}
}
}
The exception means that you have only 4 elements in the list/array and you are trying to reach the 5th. Counting starts at 0.
I'm creating an UNO project and am a bit confused about how to assign the drivers to my DiscardPile class.
Thank you in advance for any answers you may give.
Sincerely,
Jayda M
I've asked my fellow students for assistance and have scoured the internet for anything that could be helpful with no luck. My professor isn't helpful at all haha
This is the full code for the Driver.java file. If you need me to give you any of the others I have no problem doing so.
package unoGame;
import java.util.Random;
//import java.util.Collections;
public class Driver {
public static unoDeck theDeck = new unoDeck();
public static PlayerHand[] thePlayers;
public static DiscardPile dp = new DiscardPile();
public static int nextPlayer;
public static Random getRandom = new Random();
public static void main(String[] args) {
// TODO Auto-generated method stub
thePlayers = new PlayerHand[3];
thePlayers[0] = new PlayerHand("name 1");
thePlayers[1] = new PlayerHand("name 2");
thePlayers[2] = new PlayerHand("name 3");
theDeck.shuffle();
System.out.println("Here is the Deck: " + theDeck);
System.out.println(" Welcome to UNO! ");
if (dp.isEmpty()) {
System.out.println(" Discard is Empty ");
}
else {
System.out.println(" Not Empty ");
}
for (int i = 0; i < 7; i++) {
for (int j = 0; j < thePlayers.length; j++) {
thePlayers[j].addCard(theDeck.deal());
}
}
nextPlayer = 0;
showPlayers();
dp.addCard(theDeck.deal());
while (checkForWin() == false) {
findNextPlayer();
if (theDeck.isEmpty()) {
theDeck.replenish(dp.clear());
}
playerTurn();
}
System.out.println(thePlayers[nextPlayer], getName() + " Wins!")
}
public static void showPlayers() {
for (PlayerHand p : thePlayers)
System.out.println(p);
}
public static boolean checkForWin() {
if (p.isWin()) {
win = true;
}
return win;
}
public static void findNextPlayer() {
nextPlayer++;
nextPlayer = nextPlayer % thePlayers.length;
if(dp.getTopCard().getValue()=="SK") {
nextPlayer++;
nextPlayer = nextPlayer % thePlayers.length;
}
if(dp.getTopCard().getValue() == "D2") {
for(int i = 0; i <= 1; i++) {
thePlayers[nextPlayer].addCard(theDeck.deal());
}
}
if(dp.getTopCard().getValue() == "W4") {
for(int i = 0; i <= 3; i++) {
thePlayers[nextPlayer].addCard(theDeck.deal());
}
}
if(dp.getTopCard().getValue() == "RV") {
for(int i = 0; i < thePlayers.length / 2; i++) {
PlayerHand rev = thePlayers[i];
thePlayers[i] = thePlayers[thePlayers.length - i -1];
rev = thePlayers[thePlayers.length - i -1];
if(nextPlayer == 0) {
nextPlayer = 0;
}
if(nextPlayer == 2) {
nextPlayer = 1;
}
}
nextPlayer++;
}
}
public static void playerTurn() {
if (thePlayers[nextPlayer].hasMatch(dp.getTopCard())) {
System.out.println(thePlayers[nextPlayer].getName() + " has a match!");
unoCard c = thePlayers[nextPlayer].playCard(dp.getTopCard());
dp.addCard(c);
if(c.getValue().equals("W")) {
c.setColor(theDeck.newColor());
}
if(c.getValue().equals("W4")) {
c.setColor(theDeck.newColor());
}
System.out.println(thePlayers[nextPlayer].getName() + " played a: " dp.getTopCard());
System.out.println(thePlayers[nextPlayer]);
}
else {
unoCard c = theDeck.deal();
thePlayers[nextPlayer]c.addCard(c);
System.out.println(thePlayers[nextPlayer].getName() + " drew a: " + c);
}
}
}
There are errors are on these lines of code: 46, 50, 57, 58, 60, 106 and 111. Most of them are saying they're undefined, and I'm unsure of where to do so amongst my files. I'm expecting the Driver to run the game as a whole, so because it's gone wack I can't run the build properly. If you need more information to work with, I'll gladly give it to you!
EDIT:
The lines and/or words where the errors are taking place have asterisks around them
The error descriptions with their corresponding lines
The printed console error after running Driver. Hopefully this works for the Reproducible Example required :)
Here is your Driver class with compilation problems fixed. I suggest you compare it with your current code in order to see what I changed.
I also needed to add method replenish() in class unoDeck because it didn't exist and is called from class Driver. Right now that method does nothing. As I said, I only added it in order to fix the compilation error.
package unoGame;
import java.util.Random;
public class Driver {
public static unoDeck theDeck = new unoDeck();
public static PlayerHand[] thePlayers;
public static DiscardPile dp = new DiscardPile();
public static int nextPlayer;
public static Random getRandom = new Random();
public static void main(String[] args) {
thePlayers = new PlayerHand[3];
thePlayers[0] = new PlayerHand("name 1");
thePlayers[1] = new PlayerHand("name 2");
thePlayers[2] = new PlayerHand("name 3");
theDeck.shuffle();
System.out.println("Here is the Deck: " + theDeck);
System.out.println(" Welcome to UNO! ");
if (dp.isEmpty()) {
System.out.println(" Discard is Empty ");
}
else {
System.out.println(" Not Empty ");
}
for (int i = 0; i < 7; i++) {
for (int j = 0; j < thePlayers.length; j++) {
thePlayers[j].addCard(theDeck.deal());
}
}
nextPlayer = 0;
showPlayers();
dp.addCard(theDeck.deal());
while (checkForWin() == false) {
findNextPlayer();
if (theDeck.isEmpty()) {
theDeck.replenish(dp.clear());
}
playerTurn();
}
System.out.println(thePlayers[nextPlayer].getName() + " Wins!");
}
public static void showPlayers() {
for (PlayerHand p : thePlayers)
System.out.println(p);
}
public static boolean checkForWin() {
boolean win = false;
if (thePlayers[nextPlayer].isWin()) {
win = true;
}
return win;
}
public static void findNextPlayer() {
nextPlayer++;
nextPlayer = nextPlayer % thePlayers.length;
if (dp.getTopCard().getValue() == "SK") {
nextPlayer++;
nextPlayer = nextPlayer % thePlayers.length;
}
if (dp.getTopCard().getValue() == "D2") {
for (int i = 0; i <= 1; i++) {
thePlayers[nextPlayer].addCard(theDeck.deal());
}
}
if (dp.getTopCard().getValue() == "W4") {
for (int i = 0; i <= 3; i++) {
thePlayers[nextPlayer].addCard(theDeck.deal());
}
}
if (dp.getTopCard().getValue() == "RV") {
for (int i = 0; i < thePlayers.length / 2; i++) {
PlayerHand rev = thePlayers[i];
thePlayers[i] = thePlayers[thePlayers.length - i - 1];
rev = thePlayers[thePlayers.length - i - 1];
if (nextPlayer == 0) {
nextPlayer = 0;
}
if (nextPlayer == 2) {
nextPlayer = 1;
}
}
nextPlayer++;
}
}
public static void playerTurn() {
if (thePlayers[nextPlayer].hasMatch(dp.getTopCard())) {
System.out.println(thePlayers[nextPlayer].getName() + " has a match!");
unoCard c = thePlayers[nextPlayer].playCard(dp.getTopCard());
dp.addCard(c);
if(c.getValue().equals("W")) {
c.setColor(theDeck.newColor());
}
if(c.getValue().equals("W4")) {
c.setColor(theDeck.newColor());
}
System.out.println(thePlayers[nextPlayer].getName() + " played a: " + dp.getTopCard());
System.out.println(thePlayers[nextPlayer]);
}
else {
unoCard c = theDeck.deal();
thePlayers[nextPlayer].addCard(c);
System.out.println(thePlayers[nextPlayer].getName() + " drew a: " + c);
}
}
}
I'm trying to solve the Popular Vote problem, but I get runtime error and have no idea why, I really appreciate the help. Basically my solution is to get the total of votes, if all candidates have the same amount of votes; then there's no winner, otherwise I calculate the percentage of votes the winner gets in order to know if he's majority or minority winner.
import java.util.Scanner;
class popular {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, suma, mayoria;
int casos=s.nextInt();
int cont=0;
int ganador=0;
float num=0;
while(cont!=casos){
n=s.nextInt();
int votos[]= new int[n];
for (int i = 0; i < n; i++) {
votos[i] = s.nextInt();
}
suma=sumar(votos);
if(suma==-1){
System.out.println("no winner");
}
else{
ganador=ganador(votos, suma);
num=(float)votos[ganador]/(float)suma;
if( num> 0.5){
System.out.println("majority winner "+(ganador+1));
}
else{
System.out.println("minority winner "+(ganador+1));
}
}
cont++;
ganador=0;
}
}
public static int sumar(int arreglo[]){
int resp1=-1, resp=0;
int temp=arreglo[0];
boolean sol=true;
for (int i = 0; i < arreglo.length; i++) {
resp=resp+arreglo[i];
if(temp!=arreglo[i]){
sol=false;
}
}
if(sol==false){
return resp;
}
return resp1;
}
public static int ganador(int arreglo[], int suma){
int mayor=0;
int ganador=0;
for (int i = 0; i < arreglo.length; i++) {
if(arreglo[i]>mayor){
mayor=arreglo[i];
ganador=i;
}
}
return ganador;
}
}
I submitted your code to the OJ, but I didn't get a runtime error, but I got Compilation error. I have to figure out there are some problems in your code. First of all, if you want to submit a java code to OJ, you need to name the public class as Main instead of popular or something else. Second, your code logic is not correct. Suppose a test case:
4
1
1
2
2
Your program will print "minority winner 3" but it's should be "no winner".
Here is a modified source code from yours (you can get accepted with this code):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, suma, mayoria;
int casos = s.nextInt();
int cont = 0;
int ganador = 0;
float num = 0;
while (cont != casos) {
n = s.nextInt();
int votos[] = new int[n];
for (int i = 0; i < n; i++) {
votos[i] = s.nextInt();
}
ganador = findMaximum(votos);
if (getMaximumCount(votos, votos[ganador]) > 1) {
System.out.println("no winner");
} else {
suma = sumOf(votos);
if (votos[ganador] * 2 > suma) {
System.out.println("majority winner " + (ganador + 1));
} else {
System.out.println("minority winner " + (ganador + 1));
}
}
cont++;
ganador = 0;
}
}
private static int sumOf(int[] arreglo) {
int sum = 0;
for (int x : arreglo) {
sum += x;
}
return sum;
}
private static int getMaximumCount(int[] arreglo, int maximum) {
// Check if there are more than one items have the maximum value
int count = 0;
for (int x : arreglo) {
if (x == maximum) {
count++;
}
}
return count;
}
private static int findMaximum(int[] arreglo) {
int x = 0, pos = 0;
for (int i = 0; i < arreglo.length; i++) {
if (x < arreglo[i]) {
x = arreglo[i];
pos = i;
}
}
return pos;
}
}
Hope it could help you!
Can you give me a hint on what I'm doing wrong with my average in the average method? I'm trying to call the method in the read scores.I'm trying to get the average of the scores I have in my input.txt file.
import java.io.*;
import java.util.*;
public class FindGrade {
public static final int NUM_SCORE_TYPES = 5;
public static void main(String[] args) {
Scanner scan = null;
int[] quizArray = null;
int[] labArray = null;
int[] attendance = null;
int[] midterms = null;
int quizgrade =0;
int labgrade=0;
int attendance_1=0;
int midterms_1 =0;
String name;
try {
scan = new Scanner(new File("input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
// each iteration is for single exam type (ie: Quizzes is the 1st one)
for (int i = 0; i < NUM_SCORE_TYPES; i++) {
name = scan.next();
int numScores = scan.nextInt();
int maxGrade = scan.nextInt();
if (name.equals("Quizzes")) {
quizArray = new int[numScores];
readScores(quizArray, numScores, scan);
}
else if (name.equals("Labs")) {
labArray = new int[numScores];
readScores(labArray, numScores, scan);
}
else if (name.equals("Lab_attendance")) {
attendance = new int[numScores];
readScores(attendance, numScores, scan);
}
else if (name.equals("Midterms")) {
midterms = new int[numScores];
readScores(midterms, numScores, scan);
}
}
}
public static void readScores(int[] scoreArray, int numScores, Scanner scan) {
for (int i = 0; i < numScores; i++) {
scoreArray[i] = scan.nextInt();
}
}
public static void average(double [] scoreArray, int numScores){
double sum=0;
for(int i=0; i< scoreArray.length; i++){
sum += scoreArray[i];
}
double average = sum/numScores;
System.out.println(sum + " " + average);
}
In any case, you can't directly call it with the arrays that you are creating there. Because the arrays are of type int, but the average-method requires a double array. When you change this, you can call the method like this...
public static void readScores(int[] scoreArray, int numScores, Scanner scan) {
for (int i = 0; i < numScores; i++) {
scoreArray[i] = scan.nextInt();
}
average(scoreArray, numScores); // <----- Call it here
}
public static void average(int[] scoreArray, int numScores){
double sum=0;
for(int i=0; i< scoreArray.length; i++){
sum += scoreArray[i];
}
double average = sum/numScores;
System.out.println(sum + " " + average);
}
My code at the moment:
import java.util.*;
import java.io.*;
public class Percolation {
// given an N-by-N matrix of open sites, return an N-by-N matrix
// of sites reachable from the top via a vertical path of open sites
private static Scanner scan = null;
public static boolean[][] readOpenFromFile() {
final File f = new File("file.txt");
try {
scan = new Scanner(f);
}
catch(FileNotFoundException ex) {
System.exit(0);
}
final int m = scan.nextInt();
final int n = scan.nextInt();
final boolean[][] grid = new boolean[m][n];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
grid[i][j] = readBoolean();
}
}
return grid;
}
public static boolean readBoolean() {
final String s = scan.next();
if(s.equalsIgnoreCase("true")) {
return true;
}
if(s.equalsIgnoreCase("false")) {
return false;
}
if(s.equals("1")) {
return true;
}
if(s.equals("0")) {
return false;
}
throw new java.util.InputMismatchException();
}
public static boolean[][] flow(final boolean[][] open) {
final int n = open.length;
final boolean[][] full = new boolean[n][n];
for(int j = 0; j < n; j++) {
flow(open, full, 0, j);
}
return full;
}
public static void flow(final boolean[][] open, final boolean[][] full, final int i, final int j) {
final int n = open.length;
// base cases
if(( i < 0) ||( i >= n)) {
return; // invalid row
}
if(( j < 0) ||( j >= n)) {
return; // invalid column
}
if(!open[i][j]) {
return; // not an open site
}
if(full[i][j]) {
return; // already marked as full
}
// mark i-j as full
full[i][j] = true;
flow(open, full, i + 1, j); // down
flow(open, full, i, j + 1); // right
flow(open, full, i, j - 1); // left
flow(open, full, i - 1, j); // up
}
// does the system percolate?
public static boolean percolates(final boolean[][] open) {
final int n = open.length;
final boolean[][] full = flow(open);
for(int j = 0; j < n; j++) {
if(full[n - 1][j]) {
System.out.println("percolates");
return true;
}
}
System.out.println("does not percolate");
return false;
}
public static void print(final boolean[][] grid) {
final int m = grid.length;
final int n = grid[0].length;
System.out.println(m + " " + n);
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j]) {
System.out.print("1 ");
} else {
System.out.print("0 ");
}
}
System.out.println("");
}
}
public static void main(String[] args) {
final boolean[][] open = readOpenFromFile();
print(flow(open));
System.out.println(percolates(open));
}
}
It can be seen that this program works by grabbing input from the file.txt file. However, how could I modify this code so as to request require a file name (perhaps at the command-line) each time the program is run, and use that as input?
I would think to add a String as an argument, then change that String into a file name. But this is easier said than done. Suggestions?
You can take it as an argument and modify code to -
public static void main(String[] args) {
// args[0] - Full path of the file
final boolean[][] open = readOpenFromFile(args[0]);
print(flow(open));
System.out.println(percolates(open));
}
public static boolean[][] readOpenFromFile(String filepath) {
final File f = new File(filepath);
try {
scan = new Scanner(f);
}
catch(FileNotFoundException ex) {
System.exit(0);
}
final int m = scan.nextInt();
final int n = scan.nextInt();
final boolean[][] grid = new boolean[m][n];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
grid[i][j] = readBoolean();
}
}
return grid;
}
You can use this code:
public static boolean[][] readOpenFromFile(String file) {
final File f = new File( file );
// same code ...
}
public static void main(String[] args) {
if(args != null && args.length == 1) {
String file = args[0];
final boolean[][] open = readOpenFromFile(file);
print(flow(open));
System.out.println(percolates(open));
}
}
You need something like this, but you have to add checking file name:
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
while (!(CurLine.equals("quit"))){
CurLine = in.readLine();
if (!(CurLine.equals("quit"))){
System.out.println("You typed: " + CurLine);
}
}
Link to site where you can find it