
February 9th, 2013, 07:27 PM
|
|
Contributing User
|
|
Join Date: Oct 2011
Posts: 43
Time spent in forums: 10 h 31 m 45 sec
Reputation Power: 2
|
|
|
Need help parsing (NoSuchElementException)?
This is a program that uses brute force to check if a equation is 2-sat or not. My problem however is with the parsing of the file. I get NoSuchElementException when I read this
int numV = input.nextInt();
Also, the main method was already given (except the last part where I call the brute method). The text file looks like this:
5
-1 4
-4 1
-1 -4
-3 -2
Code:
public class BruteForce {
// Reads input from stdin or a specified file. Accepts an optional command-line argument,
// a flag to indicate whether to use a simple brute-force solution
// or not.
public static void main(String[] args) {
Scanner intScan;
boolean bruteForce = true;
Scanner inp = new Scanner(System.in);
for (int i=0;i<args.length;i++) {
if (args[i].equals("-nobrute"))
bruteForce = false; // don't use brute force, use clever algorithm
else {
try {
inp = new Scanner(new File(args[i]));
} catch(FileNotFoundException e) {
System.out.println("File not found: "+args[i]);
System.exit(1);
}
}
}
intScan = new Scanner(inp.nextLine());
// then read in each disjunction
while (inp.hasNextLine()) {
String s = inp.nextLine();
intScan = new Scanner(s);
// read in a disjunction: (a \/ b) represented by 2 integers separated by whitespace
// each variable is represented by a number in the range 1..numV, or -numV..-1
// (negative numbers represent logically negated values)
int a = intScan.nextInt();
int b = intScan.nextInt();
//System.out.println("Read "+a+" and "+b);
}
boolean is2SAT = brute(intScan);
if(is2SAT){
System.out.println("This is a 2-SAT equation!");
}
}
public static boolean brute(Scanner input) {
boolean evaluatable = true;
//ERROR HAPPENS HERE
// first read in number of vars involved
int numV = input.nextInt();
for (int j = 0; j < numV; j++) {
String binaryRepresentation = Integer.toBinaryString(j);
for (int i = 0; i < numV && evaluatable; i++) {
int iFirst = input.nextInt();
int iSecond = input.nextInt();
// Assigns correct sign according to j:
// 10011 means true-false-false-true-true
if (binaryRepresentation.charAt(Math.abs(iFirst)-1) == '0') {
iFirst *= -1;
}
if (binaryRepresentation.charAt(Math.abs(iSecond)-1) == '0') {
iFirst *= -1;
}
evaluatable = evaluateAnd(iFirst, iSecond) && evaluateOr(iFirst, iSecond);
}
if (evaluatable) {
return true;
}
}
return false;
}
public static boolean evaluateOr(int a, int b) {
return a > 0 || b > 0;
}
public static boolean evaluateAnd(int a, int b) {
return a > 0 && b > 0;
}
}
|