I'm trying to write a part of a program that reads a text file and then retrieves an integer from each line in the file and adds them together. I've managed to retrieve the integer, however each line contains more than one integer, leading me to inadvertently pick up other integers that I don't need. Is it possible to skip certain integers?
The format of the text file can be seen in the link underneath.
Text file
The integers that i'm trying to collect are the variables that are 3rd from the left in the text file above, (3, 6 and 4) however i'm also picking up 60, 40 and 40 as they're integers too.
Here's the code that i've got so far.
public static double getAverageItems (String filename, int policyCount) throws IOException {
Scanner input = null;
int itemAmount = 0;
input = new Scanner(new File(filename));
while (input.hasNext()) {
if (input.hasNextInt()) {
itemAmount = itemAmount + input.nextInt();
}
}
return itemAmount;
}
Just add input.nextLine():
if (input.hasNextInt()) {
itemAmount = itemAmount + input.nextInt();
input.nextLine();
}
From the documentation: nextLine advances the scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Another approach would be parsing each line and taking the third column.
BufferedReader r = new BufferedReader(new FileReader(filename));
while (true) {
String line = r.readLine();
if (line==null) break;
String cols[] line.split("\\s+");
itemAmount += Integer.parseInt(cols[2]);
}
r.close();
public static double getAverageItems (String filename, int policyCount) throws IOException {
Scanner input = null;
int itemAmount = 0;
input = new Scanner(new File(filename));
while (input.hasNext()) {
String []var = input.nextLine().split("\\s+");
itemAmount += var[2];
}
return itemAmount;
}
Related
I'm using Scanner to read 3 lines of input, the first two are strings and the last one is int.
I'm having an issue when the first line is empty and I don't know how to get around it. I have to do this:
String operation = sc.nextLine();
String line = sc.nextLine();
int index = sc.nextInt();
encrypt(operation,line,index);
But when the first line is empty I get an error message.
I tried the following to force a loop until I get a non empty next line but it does not work either:
while(sc.nextLine().isEmpty){
operation = sc.nextLine();}
Anybody has a hint please ?
A loop should work, though you must actually call the isEmpty method and scan only once per iteration
String operation = "";
do {
operation = sc.nextLine();
} while(operation.isEmpty());
You could also use sc.hasNextLine() to check if anything is there
Try this:
Scanner scanner = new Scanner(reader);
String firstNotEmptyLine = "";
while (scanner.hasNext() && firstNotEmptyLine.equals("")) {
firstNotEmptyLine = scanner.nextLine();
}
if (!scanner.hasNext()) {
System.err.println("This whole file is filled with empty lines! (or the file is just empty)");
return;
}
System.out.println(firstNotEmptyLine);
Then you can read the other two lines after this firstNotEmptyLine.
Please try this.
Scanner sc = new Scanner(System.in);
String operation = null;
String line = null;
int index = 0;
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
operation = nextLine;
break;
}
}
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
line = nextLine;
break;
}
}
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
index = Integer.parseInt(nextLine);
break;
}
}
System.out.println(operation + " " + line + " " + index);
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String operation = sc.nextLine();
String line = sc.nextLine();
int index = sc.nextInt();
test(operation,line,index);
}
public static void encrypt(String a,String b,int c){
System.out.println("first :"+a+" Second :"+b+" Third :"+c);
}
I don't see any error here. It compiles well.
So I am trying to read a file using a scanner. This file contains data where there are two towns, and the distance between them follows them on each line. So like this:
Ebor,Guyra,90
I am trying to get each town individual, allowing for duplicates. This is what I have so far:
// Create scanner for file for data
Scanner scanner = new Scanner(new File(file)).useDelimiter("(\\p{javaWhitespace}|\\.|,)+");
// First, count total number of elements in data set
int dataCount = 0;
while(scanner.hasNext())
{
System.out.print(scanner.next());
System.out.println();
dataCount++;
}
Right now, the program prints out each piece of information, whether it is a town name, or an integer value. Like so:
Ebor
Guyra
90
How can I make it so I have an output like this for each line:
Ebor
Guyra
Thank you!
Assuming well-formed input, just modify the loop as:
while(scanner.hasNext())
{
System.out.print(scanner.next());
System.out.print(scanner.next());
System.out.println();
scanner.next();
dataCount += 3;
}
Otherwise, if the input is not well-formed, check with hasNext() before each next() call if you need to break the loop there.
Try it that way:
Scanner scanner = new Scanner(new File(file));
int dataCount = 0;
while(scanner.hasNext())
{
String[] line = scanner.nextLine().split(",");
for(String e : line) {
if (!e.matches("-?\\d+")) System.out.println(e);;
}
System.out.println();
dataCount++;
}
}
We will go line by line, split it to array and check with regular expression if it is integer.
-? stays for negative sign, could have none or one
\\d+ stays for one or more digits
Example input:
Ebor,Guyra,90
Warsaw,Paris,1000
Output:
Ebor
Guyra
Warsaw
Paris
I wrote a method called intParsable:
public static boolean intParsable(String str)
{
int n = -1;
try
{
n = Integer.parseInt(str);
}
catch(Exception e) {}
return n != -1;
}
Then in your while loop I would have:
String input = scanner.next();
if(!intParsable(input))
{
System.out.print(input);
System.out.println();
dataCount++;
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
When I use scan.nextLine(), input boxes don't work properly. If it's scan.next() ,works perfectly.But Why? Ain't I supposed to use scan.nextLine() for string?
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
System.out.println("p");
String p = scan.nextLine();
System.out.println("q");
String q = scan.next();
System.out.println("m");
String m = scan.next();
}
}
Before using them, try to check the doc's.
Reason :
Scanner.nextLine : The java.util.Scanner.nextLine() method advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
While, this is not Applicable to Scanner.nextInt
Hence, the Scanner.nextInt method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine.
Basic Solution would be to use blank Scanner.nextLine after Scanner.nextInt just to consume rest of that line including newline.
For Example
int myVal1 = input.nextInt();
input.nextLine();
String myStr1 = input.nextLine();
This is the solution to the problem I'd use. The above comment by Tahir Hussain Mirwould likely be the cause of the problem
import java.util.ArrayList;
import java.util.Scanner;
public class app {
public static void main(String[] args) {
// declare scanner
Scanner scan = new Scanner(System.in);
// what ever number you need, it could be calculated
int numberOfInputLines = 3;
// the list of the lines entered
ArrayList<String[]> list = new<String[]> ArrayList();
// add each line to the list
for (int i = 0; i < numberOfInputLines; i++) {
// get entire line as a single string
String input = scan.nextLine();
// split the line into tokens, and store the array in the array list
String[] result = input.split("\\s");
list.add(result);
}
// iterate through each line
for (int i = 0; i < list.size(); i++) {
// iterate through the line
for (int j = 0; j < list.get(i).length; j++) {
if (isInteger(list.get(i)[j]) == true) {
// do what you want if the input is an int
//to show it works
System.out.println("int: " + list.get(i)[j]);
} else {
// do what you want if a the token inputed is a string
//to show it works
System.out.println("String: " + list.get(i)[j]);
}
}
}
}
// greasy way to check if is an int
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
}
You should use nextLine and then convert it to your expected types.
In above scenario read the line then cast it to an integer, because next and nextInt just read the input before a whitespace occurred. So when you are calling nextInt it will just consume the number and leave the newLine character which will be consumed in nextLine.
From the question, it looks like this is how you are going to read inputs input.
First integer.
Second a string line.
Third line will have two words separated by space.
This is what your code should be.
Scanner scan = new Scanner(System.in);
int x = Integer.parseInt(scan.nextLine()); //read line and then cast to integer
System.out.println("p");
String p = scan.nextLine();
System.out.println("q m");
String[] linesParts = scan.nextLine().split(" "); // read the whole line and then split it.
String q = linesParts[0];
String m = linesParts[1];
I'm writing a program to read data from files with various sports statistics. Each line has information about a particular game, in say, basketball. If a particular line contains an "#" symbol, it means that one of the teams is playing at home. I'm trying to count the lines that contain an "#" and output that to the user as the Number of Games in which either team played at home. The first file has that 9 games were played at home for some team, but my output keeps printing out 0 rather than 9. How can I fix this?
Here's the relevant code:
public static void numGamesWithHomeTeam(String fileName) throws IOException{
File statsFile = new File(fileName);
Scanner input1 = new Scanner(statsFile);
String line = input1.nextLine();
Scanner lineScan = new Scanner(line);
int count = 0;
while(input1.hasNextLine()){
if(line.contains("#")){
count++;
input1.nextLine();
} else{
input1.nextLine();
}
}
System.out.println("Number of games with a home team: " + count);
}
Your line variable always has the first line's value. You should set line in the loop, something like that.
while(input1.hasNextLine()){
if(line.contains("#")){
count++;
line = input1.nextLine();
} else{
line = input1.nextLine();
}
Edit: On the second look your code has other problem: the last line is never checked. You should not initialize line (set to null) and do the check after nextLine():
public static void numGamesWithHomeTeam(String fileName) throws IOException{
File statsFile = new File(fileName);
Scanner input1 = new Scanner(statsFile);
String line = null;
Scanner lineScan = new Scanner(line);
int count = 0;
while(input1.hasNextLine()){
line = input1.nextLine();
if(line.contains("#")){
count++;
}
}
System.out.println("Number of games with a home team: " + count);}
I am trying to search the File for characters in Java language. For that I am using Scanner to scan the file.
Well to check the Heirarchy work, I am using System.out.print("Worked till here!"); so that I can check whether it is executed or not. I was able to execute the code till the last stage, but then I found that the essential boolean variable wasn't altered, which was under the condition to check whether there is a character match or not.
The file contents are as
Ok, here is some text!
Actually this file is created to test the validity of the java application
Java is my favourite programming language.
And I think I can score even more :)
Wish me luck!
However, no matter what I search it always prompts me to be false.
Here is the code I am using
public static void main (String[] args) throws IOException {
// Only write the output here!!!
System.out.print("Write the character to be found in the File: ");
Scanner sc = new Scanner(System.in);
String character = sc.next();
// Find the character
System.out.println("Searching now...");
getCharacterLocation(character);
// Close the resource!
sc.close();
}
The method call executed and the method is as
public static void getCharacterLocation (String character) throws IOException {
System.out.println("File found...");
File file = new File("res/File.txt");
Scanner sc = new Scanner(file);
int lineNumber = 0;
int totalLines = 0;
boolean found = false;
// First get the total number of lines
while(sc.hasNextLine()) {
totalLines++;
sc.nextLine();
System.out.println("Line looping! For Total Lines variable.");
}
int[] lineNumbers = new int[totalLines];
int lineIndex = 0;
System.out.println("Searching in each line...");
while(sc.hasNextLine()) {
// Until the end
/* Get each of the character, I mean string from
* each of the line... */
while(sc.hasNext()) {
// Until the end of line
String characterInLine = sc.next();
if(sc.findInLine(character) != null) {
found = true;
}
}
System.out.print(sc.nextLine() + "\n");
lineNumber++;
sc.nextLine();
}
System.out.println("Searching complete, showing results...");
// All done! Now post that.
if(found) {
// Something found! :D
System.out.print("Something was found!");
} else {
// Nope didn't found a fuck!
System.out.println("Sorry, '" + character +
"' didn't match any character in file.");
}
sc.close();
}
Never mind the extra usage of variables, and arrays. I would use it in further coding if I can get the character and set the value to true.
Here is the output of this program.
Initial Stage
This is the initial stage for that. I wrote Ok in the input field, you can see Ok is the very first character in the File too.
Final Stage
This is the result after the execution.
Any help in this?
You count lines and don't restart the scanner.
boolean found = false;
// First get the total number of lines
while(sc.hasNextLine()) {
totalLines++;
sc.nextLine();
System.out.println("Line looping! For Total Lines variable.");
}
int[] lineNumbers = new int[totalLines];
int lineIndex = 0;
System.out.println("Searching in each line..."); // <------
while(sc.hasNextLine()) {
add e.g.
UPDATED from the comment
sc.close();
sc = new Scanner(file);
before the next while(sc.hasNextLine())
You need to implement a way to string your characters together and check them against your input. It appears that you don't currently have a way to do this in your code.
Try building an array of characters with your scanner, and moving through and doing a check of your input vs the indexes. Or maybe there is a way to implement the tonkenizer class achieve this.
Put remember, what you are looking for is not a character, it is a string, and you need to keep this in mind when writing your code.
When you count your lines you use while(sc.hasNextLine()).
After this loop, your scanner is behind the last line, so when you go to your next loop while(sc.hasNextLine()) { it is never executed.
There are multiple problems with your code:
You Iterated through your scanner here:
while(sc.hasNextLine()) {
totalLines++;
sc.nextLine();
System.out.println("Line looping! For Total Lines variable.");
}
So after this you have to reset it again to read for further processing.
While searching for character you are having two loops:
while(sc.hasNextLine()) {
// Until the end
/* Get each of the character, I mean string from
* each of the line... */
while(sc.hasNext()) {
// Until the end of line
String characterInLine = sc.next();
if(sc.findInLine(character) != null) {
found = true;
}
}
Here you just need a single loop like:
while(sc.hasNextLine()) {
String characterInLine = sc.nextLine();
if(characterInLine.indexOf(character) != -1) {
found = true;
break;
}
}