I am trying to read a txt file that contains strings with integers. I would like to be able to get just the integers from this file and add the value each to create a total.
You have done all the work and stuck with simple addition. Declare a variable total
and add integers(values) to it. In the code block, if(scan.hasNextInt())
add the following statement :
total += scan.nextInt()
.
Do not forget to declare the variable before hand.
Your file name looks incorrect change it to :-
Scanner scan = new Scanner(new File("validtest.txt"));
Then i believe you already have logic just uncomment that adding part in your code.
if (scan.hasNextInt()) {
System.out.println("Found :" + scan.nextInt());
goals = scan.nextInt();
total+= goals;
}
Instead of printing out the integer, you can add them to a list.
List<Integer> goals = new ArrayList<Integer>();
goals.add(scan.nextInt());
And then add them up!
Or if you don't need access to them individually, you can simply,
total = total + scan.nextInt(); //OR total += scan.nextInt();
In your if(scan.hasNextInt())
block
your code doesn't really do what your comments claim it does maybe you want this?
import java.util.regex.Pattern;
public void goalCount(){
int goals=0;// i dont see where this is used
double total=0;
try{
Scanner scan = new Scanner(new File("validtest.txt.txt"));
while (scan.hasNext()) {
String temp=scan.next();
if (isInteger(temp)) {
total+=Integer.ParseInt(temp);
System.out.println("Found :" + temp);
}
else{
System.out.println("Not Found :" + temp);}
}
scan.close();
}
catch(Exception e){
}
System.out.println("Total Goals:"+total);
}
}
public boolean isInteger( String input ) {
Pattern p=Pattern.compile("-?\\d+");
return input.matches(p.pattern());}
}
}
Edit:
You'll have to excuse me, that method will not work. What you need to do is read one line at a time, then split the line by each space, to get an array of words. From there you can identify integers and store the value.
final static String filename = "FILENAME.txt";
public static void main(String[] args) {
Scanner scan = null;
File f = new File(filename);
try {
scan = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
int total = 0;
boolean foundInts = false; //flag to see if there are any integers
while (scan.hasNextLine()) { //Note change
String currentLine = scan.nextLine();
//split into words
String words[] = currentLine.split(" ");
//For each word in the line
for(String str : words) {
try {
int num = Integer.parseInt(str);
total += num;
foundInts = true;
System.out.println("Found: " + num);
}catch(NumberFormatException nfe) { }; //word is not an integer, do nothing
}
} //end while
if(!foundInts)
System.out.println("No numbers found.");
else
System.out.println("Total: " + total);
// close the scanner
scan.close();
}