I have a .txt file that has information sorted as
information field; information field; information field; information field and so on. All fields are Strings.How do I make a method that gets next information field?
More information:
I exported the .txt file from Microsoft access with ";" as the delimiter. if my Scanner is named sc, how can I do an sc.nextField() kind of method? What I had originally done was have a while loop going through each word with sc.next() and adding the word to a String until it encounters a ";" but that method ignored my new lines inside fields.
private static String grabField(Scanner sc) {
String wordInFloat;
String wordsToPass = "";
while (true) {
wordInFloat = sc.next();
if (wordInFloat.endsWith(";"))
break;
else
wordsToPass += wordInFloat + " ";
}
return wordsToPass;
}
You can use the built in function sc.useDelimiter(";") and then go in a while loop to extract the information, such as:
while (sc.hasNext()) {
wordsToPass += sc.next(); // edited to change sc.nextLine() to sc.next()
}
Side Note: if you want to get rid of any leading and trailing space from a String, before adding it to wordsToPass you can use something like sc.nextLine().trim()
Edit: my answer was not quite right, use sc.next() instead of sc.nextLine().
Related
EDIT: I figured it out! I got rid of the try-catch block because it just didn't work the way I wanted it to. The code below is my final one. Thank you to everyone who responded to this question.
I am trying to code a to-do list program. One function of this program is to search for the entries inside the string array. The user should only input a ONE WORD keyword so if the user inputs more than one word or none, a prompt should show telling the user to try again. The code I've written so far is inside a try-catch statement. Using next() scanner only takes the first word and disregards the rest when inputting a multiple-word keyword, instead of producing an Exception. Here is my code for it:
case 2:
String searchKeyword;
int success = 0;
while(success==0) {
System.out.print(">> Enter 1 keyword: ");
searchKeyword = sc.nextLine();
String splitSearchKeyword[] = searchKeyword.split(" ");
if (splitSearchKeyword.length == 1) {
if(Quinones_Exer2.searchToDoList(searchKeyword, todoList)==-1) {
System.out.println(">> No item found with that keyword!");
System.out.println();
}
else {
System.out.println(">> Found one item!");
System.out.println("("+(Quinones_Exer2.searchToDoList(searchKeyword, todoList)+1)+")"+" "+todoList[Quinones_Exer2.searchToDoList(searchKeyword, todoList)]);
System.out.println();
}
success++;
}
else {
System.out.println(">> Please input a single word keyword!");
System.out.println();
}
}
break;
}```
Use Scanner.nextLine() then split the supplied string. If the length of array is greater than 1 or the supplied string is empty then issue an invalid entry message and have the User enter the string over again:
while(tries2 == 0) {
searchKeyword = "";
while (searchKeyword.isEmpty()) {
System.out.println("Enter 1 keyword: ");
searchKeyword = sc.nextLine().trim();
if (searchKeyword.isEmpty() || searchKeyword.split("\\s+").length > 1) {
System.out.println("Invalid Entry! {" + searchKeyword
+ "You must supply a single Key Word!");
searchKeyword = "";
}
}
tries2++;
// ... The rest of your code ...
}
From the docs of Scanner.next():
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
You would need to call next() again to get the the rest of the input.
Much simpler would be to use Scanner.nextLine() to get entire line and then use String.split() with whatever delimiter you are using to get an array of all inputted keywords.
Edit: Scanner.next(pattern) may do what you are looking for. It throws InputMismatchException if the input does not match provided pattern(regex). Example:
scanner.next("^[a-zA-Z]+$")
This requires the entire line to consist of lower and/or upper case letters and nothing else.
I'd like to just see an example with some explanation.
What string functions do I use to compare the objects and does it compare each character or the actual word without any additional letters to it?
Thanks
I tried doing something very similar to this question for a project awhile ago. There are numerous ways to do this in Java, but I used the Scanner class and the File class.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //Just a normal scanner
System.out.println("Please enter in the pathname to the file you want to view.");
String pathname = input.nextLine(); //Pathname to text file
File book = new File(pathname); //Creating a new file using the pathname
if(book.canRead() == false) //If Java cant read the file, this will pop up
{
System.out.println("Your file cannot be read");
}
else if(book.canRead() == true) //If Java can read the file, then this asks for the word to search for
{
System.out.println("Please enter in the word you wish to search for.");
wordToSearchFor = input.nextLine();
wordCounter(book); //Calls the method
}
System.out.println(wordToSearchFor.toLowerCase() + " appeared " + numOfOccurrences + " times in " + pathname);
}
This is the main method where you use the File class to create a file based off of a pathname that you give it EX - C:\Users\alex\Downloads\mobydick.txt
I then check to see if you can read the file, and if you can, then I call a method to analyze the book itself
import java.io.*;
import java.util.Scanner;
public class TextReader
{
private static int numOfOccurrences; //Counter to keep track of the number of occurances
private static String wordToSearchFor; //String field so both methods can access it
/*
* This method takes in the file of the book so the scanner can look at it
* and then does all of the calculating to see if the desired word appears,
* and how many times it does appear if it does appear
*/
public static void wordCounter(File bookInput)
{
try
{
Scanner bookAnalyzer = new Scanner(bookInput); //Scanner for the book
while(bookAnalyzer.hasNext()) //While the scanner has something to look at next
{
String wordInLine = bookAnalyzer.next(); //Create a string for the next word
wordInLine = wordInLine.toLowerCase(); //Make it lowercase
String wordToSearchForLowerCase = wordToSearchFor.toLowerCase();
String wordToSearchForLowerCasePeriod = wordToSearchForLowerCase + ".";
if(wordInLine.indexOf(wordToSearchForLowerCase) != -1 && wordInLine.length() == wordToSearchFor.length())
{
numOfOccurrences++;
}
else if(wordInLine.indexOf(wordToSearchForLowerCasePeriod) != -1 && wordInLine.length() == wordToSearchForLowerCasePeriod.length())
{
numOfOccurrences++;
}
}
}
catch(FileNotFoundException e) //Self explanitory
{
System.out.println("The error is FileNotFoundException - " + e);
System.out.println("This should be impossible to get to because error checking is done before this step.");
}
}
Scanners in Java can be take a File object to analyze, which is the fist thing I do in this method. I then use a while loop and ask the Scanner if there is a word that follows the current word. As long as there is a word, this will continue to run. I then create a String of the current word that the scanner is on to use as a reference to compare against. I then use a method that comes with the String class to make everything lowercase because uppercase and lowercase letters matter.
The first if statement in this method checks if the current word that the scanner has matches what you are searching for using the indexOf method from the String class, which takes some string and looks to see if it exists in another string. The if statement comparison also makes sure that the desired word length is the same as the word length in the book in case you are looking up "the" and it doesnt mark "then" as a word since it contains "the". The second if statement does the same thing, just with your desired word with a period at the end. If you wanted to go the extra mile, you could also check for exclamation points, question marks, commas, and so forth, but I decided to just check for periods.
Every time one of these if statements is correct, I increment a variable by one, and after the scanner runs out of words to search for, I print out the total number of times that certain word appears in a text file.
I am trying to write a string input to a text file using the Scanner object.
The string input is a film name. If the file name has two words, though, the scanner object only takes the first word.
I need it to take both words. Here is my code:-
Scanner new_dvd_info = new Scanner(System.in);
System.out.println("Enter name of new film");`
String film_name = new_dvd_info.next();
Can anybody shed any light please?
Replace new_dvd_info.next() with new_dvd_info.nextLine() to grab the entire line.
Documentation of Scanner.next() method says
Finds and returns the next complete token from this scanner.
A complete token is preceded and followed by input that matches
the delimiter pattern. This method may block while waiting for input
to scan, even if a previous invocation of {#link #hasNext} returned
<code>true</code>.
So it would just pick up until it finds " " as delimiter in your case. You could use next line method on scanner to get whole string new_dvd_info.nextLine() alternatively you could just loop over like:
while(scanner.hasNext) {
//append to string using scanner.next();
}
The problem here is that you are using new_dvd_info.next() which returns the first complete token. If any delimiter such as space is encountered it considers the next word as a separate token.
Scanner sc=new Scanner(System.in);
String s=sc.next();
System.out.println(s);
In the above code if you give the name of the movie as Age of Ultron it will return you just the tokenAge as there is a delimiter after the token age.
In case you want the complete String separated by delimiter you should use
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
System.out.println(s);
This will give you the desired output i.e. Age of Ultron
So I have a .txt file with only this as the contents:
pizza 4
bowling 2
sleepover 1
What I'm trying to do is, for example in the first line, ignore the "pizza" part but save the 4 as an integer.
Here is the little bit of code I have so far.
public static void addToNumber() {
PrintWriter writer;
Int pizzaVotes, bowlingVotes, sleepOverVotes;
try {
writer = new PrintWriter(new FileWriter("TotalValue.txt"));
}
catch (IOException error) {
return;
}
// something like if (stringFound)
// ignore it, skip to after the space, then put the number
// into a variable of type int
// for the first line the int could be called pizzaVotes
// pizzaVotes++;
// then replace the number 4 in the txt file with pizzaVote's value
// which is now 5.
// writer.print(pizzaVotes); but this just overwrites the whole file.
// All this will also be done for the other two lines, with bowlingVotes
// and sleepoverVotes.
writer.close();
} // end of method
I am a beginner. As you can see my actual, functioning code is very short and I don't know to proceed. If anyone would be so kind as to point me in the right direction, even if you just give me a link to a site, it would be extremely helpful...
EDIT: I stupidly thought PrintWriter could read a file
It's pretty simple actually. All you need is a Scanner, and it's function nextInt()
// The name of the file which we will read from
String filename = "TotalValue.txt";
// Prepare to read from the file, using a Scanner object
File file = new File(filename);
Scanner in = new Scanner(file);
int value = 0;
while(in.hasNextLine()){
in.next();
value = in.nextInt();
//Do something with the value here, maybe store it into an ArrayList.
}
I have not tested this code, but it should work, but the value in the while loop is going to be the current value of the current line.
I don't fully understand your question, so comment if you want some clearer advice
Here is a common pattern you'll use in Java:
Scanner sc=new Scanner(new File(.....));
while(sc.hasNextLine(){
String[] line=sc.nextLine().split("\\s");//split the string up by writespace
//....parse tokens
}
// now do something
In your case, it seems like you want to do something like:
Scanner sc=new Scanner(new File(.....));
FrequencyCloud<String> votesPerActivity=new FrequencyCloud<String>()
while(sc.hasNextLine(){
String[] line=sc.nextLine().split("\\s");//split the string up by writespace
//if you know the second token is a number, 1st is a category you can do
String activity=line[0];
int votes=Integer.parseInt(line[1]);
while(votes>0){
votesPerActivity.incremendCloud(activity);//no function in the FrequencyCloud for mass insert, yet
votes--;
}
}
///...do whatever you wanted to do,
//votesPerActivity.getCount(activity) gets the # of votes for the activity
/// for(String activity:votesPerActivity.keySet()) may be a useful line too
FrequencyCloud: http://jdmaguire.ca/Code/JDMUtil/FrequencyCloud.java
String num = input.replaceAll("[^0-9]", " ").trim();
For sake of diversity this uses regular expressions.
I have an array with types and numbers and when printing this is the outcome:
car:1 car:2 car:3 boat:1 boat:2 boat:3 plane:1 plane:2 plane:3
I am looking for a way to determine when the type changes, and then make a new line. which means to print a "\n" after car:3 (and boat:3) so all the vehicles are on their own row.
I am printing all these items with a for-loop like this:
for(Types filename: TypeTable)
{
Scanner s;
s = new Scanner(filename.toString());
while (s.hasNext())
{
System.out.print(s.nextLine()+ " ");
}
and I guess I am in need for some local loop and to save the first type in some temp variable and in a loop print a newline when it changes, but I am kinda stuck.
edit2:
after taking a break and then coming back i managed to fix the problem, and even without having a blank line in beginning. the problem was that i had to define oldTransport in main-class :) ofc you couldnt have known how my structure was. thank you hovercraft of eel :)
Rather than printing the line via System.out.print(...) get the line and put it into a variable. Split it via the String#split(...) method, and compare the first part obtained (the String in the [0] spot of the array obtained from split) with the previous String's first part (that was also saved to a variable). If different, make a new line before printing the line out.
Also, if you are going to extract a nextLine() from the scanner, check for a hasNextLine(), not hasNext().
In pseudocode
String oldTransportation gets assigned ""
while the scanner has a next line
String variable line gets scanner's next line
String array called tokens gets this line split on ":"
String newTransportation gets the [0] item in the tokens array
Check if newTransportation equals(...) oldTransportation,
if different, call System.out.println().
print the line variable String
oldTransportation gets assigned newTransportation
end while scanner...
Lets keep track of the previous type.
String lastTypeName = "";
for(Types filename: TypeTable) {
if(!lastTypeName.equals(filename.toString()) {
lastTypeName = filename.toString();
System.out.println();
}
Scanner s = new Scanner(filename.toString());
while (s.hasNext()) {
System.out.print(s.nextLine()+ " ");
}
s.close();
}
A line break will get printed before the first line, but maybe that is not a problem.