Ok so i have inputted a number of records to a text file and i can both write to and read from this file, but i am now attempting to search through this textfile and have encountered a problem.
package assignmentnew;
// Import io so we can use file objects
import java.io.*;
import java.util.Scanner;
public class SearchProp {
public void Search() throws FileNotFoundException {
try {
String details, input, id, line;
int count;
Scanner user = new Scanner(System.in);
System.out.println();
System.out.println();
System.out.println("Please enter your housenumber: ");
input = user.next();
Scanner housenumber = new Scanner(new File("writeto.txt"));
while (housenumber.hasNext())
{
id = housenumber.next();
line = housenumber.nextLine();
if (input.equals(id))
{
System.out.println("House number is: " + id + "and" + line);
break;
}
if(!housenumber.hasNext()) {
System.out.println("no house with this number");
}
}
}
catch(IOException e)
{
System.out.print("File failure");
}
}
}
No matter what value i enter i am told that the house number is not present in the file, but obviously it is, any ideas?
Addendum:
File Structure in textfile.
27,Abbey View,Hexham,NE46 1EQ,4,150000,Terraced
34,Peth Head,Hexham,NE46 1DB,3,146000,Semi Detached
10,Downing Street,London,sw19,9,1000000,Terraced
The default delimiter for a scanner is white-space, and not ,.
You have to use housenumber.useDelimiter(","); and the code will work.
EDIT:
Set it before the while.
And that is what I get for example for 27.
Please enter your housenumber:
27
House number is: 27 and ,Abbey View,Hexham,NE46 1EQ,4,150000,Terraced
Related
https://courses.cs.washington.edu/courses/cse142/15sp/homework/6/spec.pdf
EDIT* Input Files are here:(sorry i'm new to stack overflow, hopefully this works)
I've also tried console.next() but it gives different errors than console.nextLine() in the rePlaceholder method. **
tarzan.txt - https://pastebin.com/XDxnXYsM
output for tarzan should look like this: https://courses.cs.washington.edu/courses/cse142/17au/homework/madlibs/expected_output_1.txt
simple.txt https://pastebin.com/Djc2R0Vz
clothes.txt https://pastebin.com/SQB8Q7Y8
this code should print to an output file you name.
Hello, I have a question about scanners because I don't understand why the code
is skipping the user input on the first iteration but works fine on the rest.
I'm writing a code to create a madlib program and the link will provide the explanation to the program but pretty much you have these placeholders in a text file and when you see one, you prompt for user input to replace it with your own words. However, my program always go through TWO placeholders first and only ask the user input for one, completely skipping the first placeholder. What is wrong with my code??? Also, how do you fix this? Everything else is running perfectly fine, only that the first line is consuming two placeholders so I'm always off by one.
Welcome to the game of Mad Libs.
I will ask you to provide various words
and phrases to fill in a story.
The result will be written to an output file.
(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c
Input file name: tarzan.txt
Output file name: test.txt
Please type an adjective: Please type a plural noun: DD DDDD <--- why is it like this
Please type a noun: DDDD
Please type an adjective: DD
Please type a place:
========================================================================
package MadLibs;
import java.util.*;
import java.io.*;
public class MadLibs2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
intro();
boolean isTrue = true;
while(isTrue) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String choice = console.next();
if (choice.equalsIgnoreCase("c")) {
create(console);
}
else if (choice.equalsIgnoreCase("v")) {
view(console);
}
else if (choice.equalsIgnoreCase("q")) {
System.exit(0);
}
}
}
public static void view(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String viewFile = console.next();
File existingMadLib = new File(viewFile);
Scanner printText = new Scanner(existingMadLib);
while(printText.hasNextLine()) {
System.out.println(printText.nextLine());
}
}
public static void create(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String inputFile = console.next();
File newMadLib = new File(inputFile);
while(!newMadLib.exists()) {
System.out.print("File not found. Try again: ");
inputFile = console.next();
newMadLib = new File(inputFile);
}
System.out.print("Output file name: ");
String outputFile = console.next();
System.out.println();
PrintStream output = new PrintStream(new File(outputFile));
Scanner input = new Scanner(newMadLib);
while(input.hasNextLine()) {
String line = input.nextLine();
outputLines(line, output, console);
}
}
public static void outputLines(String line, PrintStream output, Scanner console) throws FileNotFoundException{
String s = "";
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()){
s = lineScan.next();
if(s.startsWith("<") || s.endsWith(">")) {
s = rePlaceholder(console, lineScan, s);
}
output.print(s + " ");
}
output.println();
}
public static String rePlaceholder(Scanner console, Scanner input, String token) {
String placeholder = token;
placeholder = placeholder.replace("<", "").replace(">", "").replace("-", " ");
if (placeholder.startsWith("a") || placeholder.startsWith("e") || placeholder.startsWith("i")
|| placeholder.startsWith("o") || placeholder.startsWith("u")) {
System.out.print("Please type an " + placeholder + ": ");
} else {
System.out.print("Please type a " + placeholder + ": ");
}
String change = console.nextLine();
return change;
}
public static void intro() {
System.out.println("Welcome to the game of Mad Libs.");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
}
}
in your rePlaceholder, change this line:
String change = console.nextLine();
Into this
String change = console.next();
Your problem is that nextLine doesn't wait for your output, just reads what it has in the console, waiting for a new line.
This is from the documentation to be a bit more precise on the explanation:
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.
UPDATE
After reading the comment, the previous solution will not work for multiple words.
After reading the output file, you are using next().
You need to make another call to nextLine() to clean the buffer of any newlines.
System.out.print("Output file name: ");
String outputFile = console.next();
console.nextLine(); // dummy call
System.out.println();
I need to do a payroll report. You have to type the file that has the text information. The Program checks if the file exist or not. Then you make a output file of the program. The programs prints the names, hours, and rates of workers in a text file. I program only runs the last set of numbers.
import java.text.NumberFormat;
import javax.swing.JTextArea;
import java.awt.Font;
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.io.*;
public class Homework {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
String answer, filename;
filename = JOptionPane.showInputDialog("Enter the Input File Path:");
File input = new File(filename);
if (!input.exists()) {
JOptionPane.showMessageDialog(null, "The input file:\n" + filename + "\ndoes not exist!");
System.exit(0);
}
filename = JOptionPane.showInputDialog("Enter the Output File Path:");
File output = new File(filename);
if (output.exists()) {
answer = JOptionPane.showInputDialog("The output file alaready exist!\nDo you want to overwrite it?");
if (!answer.toLowerCase().equals("yes")) {
System.exit(0);
}
}
PrintWriter outFile = new PrintWriter(filename);
Scanner in = new Scanner(input);
double numberWords = 0, countNumber = 0;
double value;
String num, words, message;
String amtStr, line = "";
String alphaRegex = ".*[A-Za-z].*";
String numRegex = ".*[0-9].*";
while (in.hasNext()) {
words = in.next();
if (words.matches(alphaRegex)) {
numberWords++;
message = "The name is "+words+"\n"; //The Line is but leave +line+
JOptionPane.showMessageDialog (null, message);
} else if (words.matches(numRegex)) {
countNumber++;
num = in.next();
message = "The number is "+num+"\n"; //The Line is but leave +line+
JOptionPane.showMessageDialog (null, message);
}
}
}
}
It was not your regular expression that was causing the problem. It was the if statement in the while loop. When the word matches numRegex, than you asign in.next() to num, causing the scanner to skip the current word and chossing the next one, that in your case happens to be a num as well.
Replace the while loop with this and it will work (I have tested the code):
while (in.hasNext()) {
words = in.next();
if (words.matches(alphaRegex)) {
numberWords++;
message = "The name is "+words+"\n";
JOptionPane.showMessageDialog (null, message);
} else if (words.matches(numRegex)) {
countNumber++;
num = words; // instead of num = in.next()
message = "The number is "+num+"\n";
JOptionPane.showMessageDialog (null, message);
}
}
I'm assuming that you're looking for a regex to identify floating point numbers in text. If that's the case, here's one:
"(\\.\\d+)|(\\d+(\\.\\d+)?)"
This matches any lone decimal followed by one or more digits or any sequence of digits followed by an optional decimal with one or more digits following it. Note that this does not address leading zeros, if that's an issue.
This website is a fantastic resource for building and testing regular expressions:
http://www.regexr.com/
To be fair, I'm not getting these exceptions but merely trying to find a away to cover these exceptions. The exceptions are NosuchElementException and NumberFormatException.
Note: This programs works perfectly because the txt file is fine. However, introduce anything that is not a number and it will fail.
Here is the main class where the problem could occur:
BankReader.java
package bankreader;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class BankReader
{
public static void main(String[] args)
{
BankReader reader = new BankReader();
Scanner scan = new Scanner(System.in);
String fileName = "";
boolean finished = false;
while(!finished)
{
try
{
System.out.print("Enter the name of the file: ");
fileName = scan.nextLine();
scan = reader.checkFile(fileName, scan);
reader.readFile(scan);
finished = true;
}
catch(IOException ex)
{
System.out.print("\nThis file does not exist or had");
System.out.println(" characters that were not numbers. Please enter a different file.\n");
}
}
scan.close();
}
public Scanner checkFile(String fileName, Scanner scan) throws IOException
{
File file = new File(fileName);
scan = new Scanner(file);
return scan;
}
public void readFile(Scanner scan)
{
String accountNumber = "";
double accountBalance = -1;
Bank bank = new Bank();
while(scan.hasNext())
{
accountNumber = scan.next();
accountBalance = Double.parseDouble(scan.next());
BankAccount bankAccount = new BankAccount(accountNumber, accountBalance);
bank.addAccount(bankAccount);
}
if (bank.numberOfAccounts() > 0)
{
BankAccount maxBalance = bank.getHighestBalance();
System.out.println(maxBalance.getAccountNumber() + ": " + "$" + maxBalance.getBalance());
}
else
System.out.println("\nThe file had no accounts to compare.");
}
}
Here is the txt file I'm working with:
346583155444415 10000.50
379611594300656 5000.37
378237817391487 7500.15
378188243444731 2500.89
374722872163487 25000.10
374479622218034 15000.59
342947150643707 100000.77
So even though this is my own txt file, what if I was accessing a text file that a character that wasn't a number or had an account number but no balance and vice versa. I would like to know how I can deal with these exceptions.
What I've tried:
I've tried to do scan.nextLine() to move away from the exception but it just introduces another exception.
I've also tried to use a method that uses regex to check if the string is a number. The problem is I'm using a variable that is not a string and I would rather not create more checks.
It seems to me that no more what I do, I can't recover my scanner after an exception has occurred.
before parsing you can test if it is a double with scan.hasNextDouble and parse or read the number only then else you set default value and move next by reading the incorrect value and dont do anything with it
So I am trying to search through a text file and if the user input is found, it returns the entire sentence including white spaces.But apparently I only get the first string and nothing pass the first string in the sentence. For example if i have a text file called "data.txt" and the contents in the first line is " I am a legend". after user enters "I am a legend" the output after the file is searched is "I". Any help would be appreciated.
public static void Findstr() { // This function searches the text for the string
File file = new File("data.txt");
Scanner kb = new Scanner(System.in);
System.out.println(" enter the content you looking for");
String name = kb.next();
Scanner scanner;
try {
scanner = new Scanner(file).useDelimiter( ",");
while (scanner.hasNext()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(name)) {
// a match!
System.out.println("I found " + name);
break;
}
}
} catch (IOException e) {
System.out.println(" cannot write to file " + file.toString());
}
package com.example;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileSearch {
public void parseFile(String fileName,String searchStr) throws FileNotFoundException{
Scanner scan = new Scanner(new File(fileName));
while(scan.hasNext()){
String line = scan.nextLine().toLowerCase().toString();
if(line.contains(searchStr)){
System.out.println(line);
}
}
}
public static void main(String[] args) throws FileNotFoundException{
FileSearch fileSearch = new FileSearch();
fileSearch.parseFile("src/main/resources/test.txt", "am");
}
}
test.txt contains:
I am a legend
Hello World
I am Ironman
Output:
i am a legend
i am ironman
The above code does case insensitive search. You should use nextLine() to get the complete line. next() breaks on whitespaces.
Reference:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()
Scanner.next(); returns the next caracter instead use Scanner.readLine();
Edit:
Belive Scanners use .nextLine(); not .readLine();
When you are scanning your input..
Scanner kb = new Scanner(System.in);
System.out.println(" enter the content you looking for");
String name = kb.next();
You are accepting only one token. You should accept whole line to be searched as your token using kb.nextLine()
I'm sorry if this is a silly question but I am fairly new to coding and so for my assignment I was given this code:
package webservice;
import webservice.Weather;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the zip code : ");
java.lang.String zipCode = scan.nextLine();
try{
webservice.Weather service = new webservice.Weather();
webservice.WeatherSoap port = service.getWeatherSoap();
webservice.WeatherReturn result = port.getCityWeatherByZIP(zipCode);
System.out.print(result.getCity()+ " ");
System.out.println (result.getState());
System.out.println("Zip code " + zipCode);
System.out.println ("Current Temperature is " + result.getTemperature());
}
catch (Exception ex){
System.out.println("Error");
}
}//end main
}//end class
The code runs perfectly fine but I have to have it loop until i enter "0" for the zip code.
I'm fairly new to coding and I tried to review my previous works to try to incorporate a loop but I was never successful. Which loop would be the most efficient to have the code loop until the user enters "0" as the zip code?
Simply try this:
Scanner scan = new Scanner (System.in);
int zipCode;
while(scan.nextInt()!=0){
System.out.print ("Enter the zip code : ");
zipCode = scan.nextInt();
}
Use a while loop to verify your condition and use .nextInt() to get an int from the scanner.
Also there's a typo:
If you use :
import webservice.Weather;
You don't have to do this:
webservice.Weather service = new webservice.Weather();
It's simply:
Weather service = new Weather();
Take a look at Using Package Members for further information.
How about while loop?
String zipCode;
while(!"0".equals(zipCode = scan.nextLine())) {
//to do rest
}
Sample code:
import java.util.Scanner;
class Ideone
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String zipCode;
while(!"0".equals(zipCode = sc.nextLine())) {
System.out.printf("zip code: %s\n", zipCode);
}
System.out.printf("last zip code: %s\n", zipCode);
}
}
I/P:
123
456
789
0
O/P:
zip code: 123
zip code: 456
zip code: 789
last zip code: 0
while loop would do your trick.
This is because while loop checks the condition first and then iterates over if the condition is found to be true. And in your case we need to check if the user has entered the correct value or not. If he has entered 0 we do not need to proceed further.