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);}
Related
In this program, I am supposed to check if each word in the file "Paper" is in the file "dictionary". If the word is not in the file dictionary, it prints out ("Line #" "the word"). The problem in this code is the loop. I don't know to make the loop reset.
EX: a dictionary file has two words big and small
a paper file has a sentence his foot is small
The program will print
Line: 1: his
Line: 1: foot
Line: 1: is
import java.util.Scanner;
import java.io.*;
public class SpellCheck{
public static void main(String[] arg) throws FileNotFoundException{
Scanner readfile = new Scanner(new File("paper"));
String word = "";
int count = 0;
while(readfile.hasNextLine()){
String line = readfile.nextLine();
Scanner linescan = new Scanner(line);
String Scannedword = linescan.next();
word = Scannedword;
count++;
}
Scanner openDictionary = new Scanner(new File("Dictionary"));
String wordInDictionary = openDictionary.next();
if(word.equals(wordInDictionary)){
}else{
System.out.println("Line " + count + ": " + word);
openDictionary.close();
}
}
}
I would rather preprocess dictionary file.
while(readfile.hasNextLine()){
String line = readfile.nextLine();
Scanner linescan = new Scanner(line);
String Scannedword = linescan.next();
word = Scannedword;
count++;
}
Just like you have written here, make a hashset or whatever the container you'd like and copy over words in dictionary file. And, using another loop to do your task (check if the container contains the word you just read.) In this way, two loop are not nested so it will run O(n).
I am trying to copy the contents of a .txt file to an array and print it to the console.
The code requires a main method with two scanners (one to read input from the user, and the second to read the file), a method to make the array, and a method to print the array.
I have successfully managed to make an array and print it, but the output is not ideal. It is scattered and difficult to read. Can someone help me to improve my output so it reads more like a list?
Here is my code:
public class CutupSongCreator {
// Creates two Scanner objects; one reads input from console, the other scans a file
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in); // SCANNER ONE (reads input)
System.out.print("What is the input filename? ");
String filename = console.next();
File f = new File(filename);
while (!f.exists()) {
System.out.print("That file does not exist. Try again: ");
filename = console.next();
f = new File(filename);
}
Scanner input = new Scanner(f); // SCANNER TWO (reads file)
SongLine[] arr = makeArray(input);
printArray(arr);
// Sort by genre
// System.out.print("What genre are you looking for: ");
// String genretype = console.next();
// if (genretype == input.next()) {
// System.out.print("You can't just make up a genre. Try again: ");
// genretype = console.next();
// }
// listLinesByGenre(arr, genretype);
}
// Creates an array of SongLines from a set of lines
public static SongLine[] makeArray(Scanner reader) {
int total = reader.nextInt(); // First int = # of lines
SongLine[] arr = new SongLine[total]; // New array to hold the length of the file
for(int i = 0;i < total; i++) {
String genre = reader.next();
int lineNumber = reader.nextInt();
String words = reader.nextLine();
SongLine temp = new SongLine(genre, lineNumber, words);
arr[i] = temp;
}
reader.close();
return arr;
}
// Prints out the elements of an array
public static void printArray(SongLine[] songs) {
System.out.println(Arrays.toString(songs));
}
}
My code makes use of a constructor class, which I could post if needed, but I think I just do not understand how to read or use the constructor file. Below are the current and desired output. The desired shows the genre, lineNumber, and script, and I would like to print it looking as so.
Current Output
Desired Output
Thank you.
I have a file that I am importing and what I want do is ask for the user's input and use that as the basis for finding the right line to examine. I have it set up like this:
public class ReadLines {
public static void main(String[] args) throws FileNotFoundException
{
File fileNames = new File("file.txt");
Scanner scnr = new Scanner(fileNames);
Scanner in = new Scanner(System.in);
int count = 0;
int lineNumber = 1;
System.out.print("Please enter a name to look up: ");
String newName = in.next();
while(scnr.hasNextLine()){
if(scnr.equals(newName))
{
String line = scnr.nextLine();
System.out.print(line);
}
}
}
Right now, I am just trying to get it to print out to see that I have captured it, but that's not working. Does anyone have any ideas? Also, if it matters, I can't use try and catch or arrays.
Thanks a lot!
You need to cache the line in a local variable so you can print it out later. Something like this should do the trick:
while(scnr.hasNextLine()){
String temp = scnr.nextLine(); //Cache variable
if (temp.startsWith(newName)){ //Check if it matches
System.out.println(temp); //Print if match
}
}
Hope this helps!
I'd do something in the lines of:
Scanner in = new Scanner(System.in);
System.out.print("Please enter a name to look up: ");
String name = in.next();
List<String> lines = Files.readAllLineS(new File("file.txt").toPath(), StandardCharsets.UTF_8);
Optional<String> firstResult = lines.stream().filter(s -> s.startsWith(name)).findFirst();
if (firstResult.isPresent) {
System.out.print("Line: " + firstResult.get());
} else {
System.out.print("Nothing found");
}
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;
}
}
I'm trying to alternate a file but keeping some lines intact based on a user input. (Details below code)
public class RemoveLines {
public static void main(String[] args)
throws FileNotFoundException {
// prompt for input file name
Scanner console = new Scanner(System.in);
System.out.print("Type first file name to use: ");
String filename1 = console.nextLine();
System.out.print("Type second file name to use: ");
String filename2 = console.nextLine();
System.out.println("enter an integer: ");
int n = console.nextInt();
Scanner input = new Scanner(new File(filename1)); //put the first file as input
PrintStream output = new PrintStream(new File(filename2)); //put the second file as output
int count =0;
while(input.hasNextLine()){
count ++;
while(n<=count){
output.println(); // this is where i don't know what to place
}
}
}
}
the program should prompt the user to enter 2 file names and an integer n.
it should create a second file that contains the first n lines of the first file, while keeping it intact. If the first file contains less than n lines then the second file will contain all the lines of the first file.
i've started writing the while loop, but i am not sure what command i should include in order to have the desired output.
thank you.
Have a try with the following code:
int count = 0;
while (count < n) {
if (input.hasNextLine()) {
output.println(input.nextLine()); // this is where i don't know what to place
count++;
}else
{
break;
}
}
/**
* Close scanner
*/
input.close();
console.close();
output.close();
while(input.hasNextLine()){
count ++;
while(n<=count){
output.println(input.nextLine());
} else {
break;
}
}
You should also check the the input file exists.
And also you should close your input and output. I will not matter in this trivial case but it's something you should do in more complex applications.
You should open PrintStream with the append option set to true (which is false by default) -
PrintStream output = new PrintStream(new File(filename2, **true**));
Then you can do something like below -
String inputLine = scanner.readLine();
output.append(inputLine);