I have program that reads this text file:
N
How many parameters does a copy constructor accept?
1
S
What standard Java class do all classes inherit from?
Object
m
What is "computer".substring(3, 5)?
- mpute
+ pu
- put
N
What is the value of pi?
3.141592653
And needs to store only these lines (start with + or -) into the array list:
- mpute
+ pu
- put
So far I have this:
import java.io.*;
import java.util.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class Quiz {
public static void test() {
ArrayList<String> choices = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.println("What quiz are you taking? ");
String name = input.next();
File file = new File(name);
Scanner s = new Scanner(name);
while (s.hasNext()) {
choices.add(s.next());
}
}
}
How will I store only those lines into the array list instead of all the lines?
I suggest you format your question better, because there are a lot of gibberish unrelated to the question but let me answer the question in the subject.
A simple way to do this is to use this
List<String> lines = Files.readAllLines(Paths.get("C:/YourFile.txt"));
This will put all of lines in your file and you can take it from there.
Related
I am attempting to write a program for school that counts the frequency of tokens (words in this case) in a given file. The driver program should use a list structure to get each word in the same format from the file. Then, a FreqCount object is created and will eventually use the hashmap to count token frequency. I got the driver to read the file and get it into an ArrayList, but now the issue is either (a) the code to input the list is not working, so it is empty (b) the print function is not working properly (unlikely since I ripped it straight off of w3schools to test). I have thought about this for a while and can't figure out why it won't work.
Driver:
package threetenProg3;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import threetenProg3.FreqCount;
public class Driver {
public static void main(String[] args) throws FileNotFoundException{
File in = new File("test.txt");
Scanner scanFile = new Scanner(in);
ArrayList<String> parsed = new ArrayList<String>();
FreqCount fc = new FreqCount(parsed);
while(scanFile.hasNext()) { //if this ends up cutting off bottom line, make it a do while loop
parsed.add(scanFile.next().toLowerCase());
}
System.out.println("ArrayList: \n");
for(int i = parsed.size()-1; i>=0; i--) { //prints arraylist backwards
System.out.println(parsed.get(i));
}
System.out.println("\n Hashmap: \n");
fc.printMap();
scanFile.close();
}
}
FreqCount:
package threetenProg3;
import java.util.HashMap;
import java.util.ArrayList;
public class FreqCount {
HashMap<String, Integer> map = new HashMap<String, Integer>();
FreqCount(ArrayList<String> plist){
for(int i = plist.size()-1; i>=0; i--) { //puts list into hashmap
map.put(plist.get(i), 1);
}
}
//methods
public void printMap() {
for (String i : map.keySet()) {
System.out.println("key: " + i + " value: " + map.get(i));
}
}
}
The only thing I could think of was changing the List to an ArrayList, but that had no effect.
Edit: I realized I forgot a bunch of important stuff here.
Text file:
ONE TWO ThReE FoUR fIve
six seven
EIGHT
NINE
TEN ELEVEN
which outputs:
eleven
ten
nine
eight
seven
six
five
four
three
two
one
When printing the arraylist, it works perfectly. The issue is when it comes to printing the hashmap. Currently, the output for printing the hashmap is blank (as in nothing shows up after "Hashmap: ".
Thanks to anyone who can help, quick feedback is greatly appreciated :)
This line:
FreqCount fc = new FreqCount(parsed);
does not magically "bind" the array list parsed to the map. It just adds what's currently in parsed into fc.map. If you examine your code, you'll see that parsed is empty at the time the above line executes. So you are adding nothing to the map.
You should move that line to after you have added to the array list. For example, just before you print "Hashmap:":
FreqCount fc = new FreqCount(parsed);
System.out.println("\n Hashmap: \n");
fc.printMap();
you have to create a frequency counter after reading the list because you are inserting values into the map in the constructor.
And since the list is still empty when you created the FreqCount you don't see any output.
package threetenProg3;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import threetenProg3.FreqCount;
public class Driver {
public static void main(String[] args) throws FileNotFoundException{
File in = new File("test.txt");
Scanner scanFile = new Scanner(in);
ArrayList<String> parsed = new ArrayList<String>();
while(scanFile.hasNext()) { //if this ends up cutting off bottom line, make it a do while loop
parsed.add(scanFile.next().toLowerCase());
}
System.out.println("ArrayList: \n");
for(int i = parsed.size()-1; i>=0; i--) { //prints arraylist backwards
System.out.println(parsed.get(i));
}
System.out.println("\n Hashmap: \n");
FreqCount fc = new FreqCount(parsed); // Moved fc here
fc.printMap();
scanFile.close();
}
}
My Code so far. (Keep in mind this is my first programming class and While loops are still hard and new to me.
import java.util.ArrayList;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class InsultGenerator extends Application
{
ArrayList<String> adjectives1;
ArrayList<String> adjectives2;
ArrayList<String> nouns;
public void start(Stage primaryStage) throws FileNotFoundException
{
File file = new File("insultData.txt");
Scanner inFile = new Scanner(file);
while (inFile.hasNext())
{
}
}
}
So I have a project for my school that requires me to take a text file with 3 columns of text. I have to read the text file and store each column in 3 different ArrayLists. Here is the exact statement that described what is wanted.
Use a Scanner object to read the input file. Remember to add a throws FileNotFoundException clause to the start method header.
At the class level (so they can be used in other methods), declare and create three ArrayList objects called adjectives1, adjectives2, and nouns. All three lists should hold String objects.
When reading the input file, use a while loop to check to see if the input file still has data to read:
while (inFile.hasNext())
{
// read and store data
}
Each iteration of the while loop should read one line of data. Store the first adjective on the line in the adjectives1 list, the second in the adjectives2 list, and the noun in the nouns list. Use the next method of the Scanner to read each word. You may assume that each line will have all three values.
Note that you don't have to know how many lines of input data there will be. An ArrayList doesn't have a fixed capacity and expands and contracts as needed.
In the while loop, first read the next line of text to a String. Then, split the String into an array. Finally, push each element of the array to each array list.
String line = inFilw.nextLine();
String[] words = line.split(" ");
adjectives1.add(words[0]);
adjectives2.add(words[1]);
nouns.add(words[2]);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner line = new Scanner(System.in);
int counter = 1;
while (line.hasNextLine()) {
String line = line.nextLine();
System.out.println(counter + " " + line);
counter++;
}
}
}
Task: Each line will contain a non-empty string. Read until EOF.
For each line, print the line number followed by a single space and the line content.
Sample Input:
Hello world
I am a file
Read me until end-of-file.
Sample Output:
1 Hello world
2 I am a file
3 Read me until end-of-file.
If you'd like to scan from a file, you can use the below code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(new File("input.txt"));
int counter = 1;
while (scan.hasNextLine()) {
String line = scan.nextLine();
System.out.println(counter + " " + line);
counter++;
}
}
}
Scanner line = new Scanner(); // <-- YOUR ERROR - there is no constructor for the Scanner object that takes 0 arguments.
// You need to specify the environment in which you wish to 'scan'. Is it the IDE? A file? You need to specify that.
Since you said EOF, I'm assuming there is a File associated with this task.
Create a File object, toss that into the Scanner constructor.
File readFile = new File(PATH_TO_FILE); // where PATH_TO_FILE is the String path to the location of the file
// Set Scanner to readFile
Scanner scanner = new Scanner(readFile);
You also have a duplicate local variable named: line
I suggest you do more reading to get a grasp of how variables and objects work rather than guess or be spoonfed code you don't understand. That's how you become a strong programmer.
Documentation states that you need to pass Source to Scanner, so that it can scan from it.
To get user input then you need to use Scanner(InputStream source) constructor.
Scanner line = new Scanner(System.in);
public static void main(String[] args) {
Scanner line = new Scanner(System.in); // Added source parameter in constructor.
int counter = 1; // Initialization of counter is done outside while loop, otherwise it will always get initialized by 1 in while loop
while (line.hasNextLine()) {
String lineStr = line.nextLine(); // changed variable name to lineStr, because 2 variable can't be declared with the same name in a method.
System.out.println(counter + " " + lineStr);
counter++;
}
}
Note: Make sure you break your while loop, otherwise it will go into infinite loop.
You can't have multiple variable without the same name. You must rename one of your line variables.
When creating a scanner, you need to send in the input stream you want it to read from. System.in can server as this stream and it will read from your console. Your question though seems to indicate that you want to read from a file. If you indeed want to read from a file, you need to create the file you want to read from and send that file into the scanner to allow the scanner to read from that file.
Try:
public class Solution {
public static void main(String[] args) {
//create the File
File file = new File(filename);
//send the file into Scanner so it can read from the file
Scanner scanner = new Scanner(file);
//initialize the counter variable
int counter = 1;
//read in the file line by line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(counter +" "+ line);
counter++;
}
}
}
To read user input, you need to use System.in in your declaration of the line object in your code:
Scanner line = new Scanner(System.in);
int counter = 0; // Initialized out of loop.
while (line.hasNextLine()) {
String ln = line.nextLine();
System.out.println(counter +" "+ln);
counter++;
}
In my program, it reads a file called datafile.txt... inside the datafile.txt is a random 3 lines of words. What my program does is reads the file the user types in and then they can type in a Line # and Word # and it will tell them the word that is in that location.. for example..
What is the file to read from?
datafile.txt
Please enter the line number and word number (the first line is 1).
2 2
The word is: the
My problem is that my program reads the 3 lines in the txt doc as 0, 1 ,2 and the words start from 0. So to read the first word in the first line they would have to type 0,0 instead of 1,1. What I am trying to do is make it work so they can type 1,1 instead of 0,0. Not sure what my problem is right now, here is my code....
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class readingFile {
/**
* #param args
* #throws IOException
* #throws validException
*/
public static void main(String[] args) throws IOException, checkException
{
System.out.println("Enter file name: " );
Scanner keyboard = new Scanner(System.in);
BufferedReader inputStream = null;
ArrayList<String> file = new ArrayList<String>();
String fileName = keyboard.next();
System.out.println ("The file " + fileName +
" has the following lines below: ");
System.out.println();
try
{
inputStream = new BufferedReader(new FileReader(fileName));
ArrayList<String> lines = new ArrayList<String>();
while(true)
{
String line = inputStream.readLine();
if(line ==null)
{
break;
}
Scanner itemnize = new Scanner(line);
while(itemnize.hasNext())
{
lines.add(itemnize.next());
}
lines.addAll(lines);
System.out.println(lines+"\n");
}
System.out.println("Please enter the line number and word number");
int index1 = keyboard.nextInt();
int index = keyboard.nextInt();
System.out.println("The word is: "+ lines.get(index));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName);
}
inputStream.close();
}
private static void checkValid(ArrayList<String> items, int index) throws checkException
{
throw new checkException("Not Found");
}
}
The obvious solution to adapt 1-based user input to 0-based internal representation is to subtract one at some point. Seeing that you don't even use index1, writing
lines.get(index - 1)
isn't going to solve your problem completely. But I guess you can take it from there, and do something similar for the word index.
As I assume you are just learning to program I will point out 3 areas of improvement
Much like how mathematics has BIDMAS which determines the order of evaluation of an expression Java and other program languages evaluate statements in a particulate way. This means within the Parentheses of a function you may include a statment instead of a variable or constant. This will be evaluated with the result (or return) been passed into the called function. This is why MvG says you can do lines.get(index - 1)
Not all exceptions you should consider and plan around will the compiler inform you about. For example in your code an invalid input for line number or word number is entered you will get a Runtime Exception (array index out of bound)
Naming of variables should be useful, you have index and index1. What's the difference? I assume from reading your code one should be the user selected index of the line number and the second should be the index of the word on said line. May I suggest requestedLineIndex and requestedWordIndex.
On a final note this is not a usual StackOverflow question hence why your question has been 'voted down'. If you are learning as part of a course is there a course forum or Virtual Learning Environment (VLE) you can post questions on? The support of your peers at the same level of learning tends to help with exploring the basics of a language.
I'm having a problem with my hangman program. I really think what I need to do is beyond what I understand about java. Here's my code
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Random;
public class HangmanProject
{
public static void main(String[] args) throws FileNotFoundException
{
String scoreKeeper; // to keep track of score
int guessesLeft; // to keep track of guesses remaining
String[] wordList = new String[25];
final Random generator = new Random();
Scanner keyboard = new Scanner(System.in); // to read user's input
System.out.println("Welcome to Nick Carfagno's Hangman Project!");
// Create a scanner to read the secret words file
Scanner wordScan = null;
try
{
wordScan = new Scanner(new BufferedReader(new FileReader("words.txt")));
while (wordScan.hasNext())
{
}
}
finally
{
if (wordScan != null)
{
wordScan.close();
}
}
// get random word from array
class pickRand
{
public String get(String[] wordList)
{
int rnd = generator.nextInt(wordList.length);
return wordList[rnd];
}
}
System.out.println(wordList);
}
}
I was able to get the program to read a file and then print to screen, but I can't figure out how to store the words from file into an array. I not advanced at all, so please try and be as thorough as possible.
1) What you've got so far looks pretty good :)
2) Since you don't know exactly how many or few words you'll have, you don't want an "array". You're probably better off with an "ArrayList". Arrays are "fixed". Lists are "variable".
3) For each "word" you read, just ".add()" it to your arraylist
Voila! Done.
Here's a complete example:
http://www.daniweb.com/software-development/java/threads/311569/readingwriting-arraylist-fromto-file#
You need to save the read line in a String object and assign it to a certain field of the array. For example:
wordList[0] = myString;
This would assign the value of myString to the first field of your array.