I’ve a problem finding the proper regex to read a ppm file dimensions. I don’t know if it’s because my regex is wrong or if I misuse the Pattern.compile method, but I get a java.util.NoSuchElementException. Below my regex and the code along to it. It reads the whole file since my regex always return null.
Thanks.
package projet;
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
public class Ppm extends File{
private Dimensions d;
private Color[][] p;
public Ppm(String pathname) {
super(pathname);
}
public void read(){
try {
Scanner s=new Scanner(new FileReader(this.getPath()));
while(s.findInLine(Pattern.compile("/^\\d* \\d*\\s$/")) == null && s.hasNext()){
System.out.println(s.nextLine());
}
s.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Ppm.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Check filepath.");
}
}
}
Here's my sample file : https://www.dropbox.com/s/z35dvi90zdfkws0/carte1.ppm?dl=0
EDIT :
I tried with a matcher, but it still doesn't work, following the corrected regex. Here's my code, it never matches the pattern...
public class Ppm extends File{
private Dimensions d;
private Color[][] p;
public Ppm(String pathname) {
super(pathname);
d=new Dimensions(0, 0);
}
public void read(){
try {
Scanner s=new Scanner(new FileReader(this.getPath()));
Pattern p=Pattern.compile("^\\d+ \\d+\\s$");
Matcher m;
while(s.hasNext()){
m=p.matcher(s.nextLine());
if(m.matches()){
System.out.println("Found");
}
}
//System.out.println("W : "+d.getWidth()+" H: "+d.getHeight());
} catch (FileNotFoundException ex) {
Logger.getLogger(Ppm.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Check filepath.");
}
}
}
Your regex can never match.
Pattern.compile("/^\\d* \\d*\\s$/")
asks for a text has a slash before the beginning of the string and after the end of the string. Unlike PHP, Java doesn't use regex delimiters. Try
Pattern.compile("^\\d* \\d*\\s$")
(and be aware that this also matches strings like " 1 " or "1 " or even " ").
Related
The purpose of this program is to take the graphics constants from a separate Java source code file and write an updated file with the graphics constants in that same Java program either scaled up or down.
However, I'm not sure how to only change numbers in certain lines and ignore others. For example, I don't want to change the numbers for the RGB values so the colors would remain the same.
So how would I exclude certain lines from changing the number values?
import java.io.File;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;
import java.util.Arrays;
public class ScaleUpOrDown {
public static void main() {
File myFile = new File("SampleGraphics2.java");
try {
Scanner filereader = new Scanner(myFile);
do {
BufferedWriter OutputF = new BufferedWriter(new FileWriter("OutputForDouble.txt", true));
String line = filereader.nextLine();
int nu = 0;
String[] diffArray;
String sp[] = line.split(" ");
Pattern patternP = Pattern.compile("-?\\d+");
for (int i = 0; i < sp.length; i++) {
Matcher matchN = patternP.matcher(sp[i]);
while (matchN.find()) {
sp[i] = String.valueOf(Integer.parseInt(matchN.group()) * 2);
}
}
Arrays.stream(sp).forEach(string -> extraFunction(string));
OutputF.append("\n");
OutputF.close();
} while (filereader.hasNextLine());
filereader.close();
} catch (IOException e) {
System.out.println("Error, file not found!");
}
}
public static void extraFunction(String Bigstring) {
try {
BufferedWriter writingT = new BufferedWriter(new FileWriter("OutputForDouble.txt", true));
writingT.append(Bigstring + " ");
writingT.close();
System.out.print(Bigstring);
} catch (IOException e) {
System.out.println("Unable to write to file.");
}
}
}
Hоw to convert website to .txt file for finding in this file some word (ex. "Абрамов Николай Викторович")? My code read only html. In other words I want to re-check website every second. If my word appears ( by the author of the website), then my code print "Yes".
And how can I make a computer application to test any other word?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class web {
public static void main(String[] args) {
for (;;) {
try {
// Create a URL for the desired page
URL url = new URL("http://abit.itmo.ru/page/195");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str = null;
while (in.readLine() != null) {
str = in.readLine().toString();
System.out.println(str);
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
Pattern p = Pattern.compile("Абрамов Николай Викторович");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println("Yes");
System.exit(0);
}
} catch (IOException ignored) {
}
}
}
}
You don't need to convert it to TXT.
If you want just to search for the word you can check it directly . But be careful it can appears as DDOS attack if the period is too short and you may be blocked
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Main {
public static String wordToFind = "30 Day";
public static String siteURL = "https://stackoverflow.com/";
public static void checkSite()
{
try {
URL google = new URL(siteURL);
BufferedReader in = new BufferedReader(new InputStreamReader(google.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) { // Process each line.
if (inputLine.contains( wordToFind)) // System.out.println(inputLine);
{
System.out.println( "Yes" );
return;
}
}
in.close();
} catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
System.out.println(ioe);
}
}
public static void main(String[] args) {
Integer initalDelay = 0;
Integer period = 10; //number of seconds to repeat
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
checkSite();
// do stuff
}
}, initalDelay, period, TimeUnit.SECONDS);
}
}
I'm having a few issues with my zip code validator which reads a text file with UK postcodes then returns true or false after validation.
Below is the section of code I'm having issues with particularly (ZipCodeValidator) which is public and should be declared in a file called ZipCodeValidator.java. And then (Zip) which cannot find symbol.
public class ZipCodeValidator {
private static String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
private static Pattern pattern = Pattern.compile(regex);
public boolean isValid(String zipCode) {
Matcher matcher = pattern.matcher(zip);
return matcher.matches();
}
}
And below here is the entire program for reference. Any help is appreciated.
package postcodesort;
import java.util.*;
import java.util.Random;
import java.util.Queue;
import java.util.TreeSet;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.StringTokenizer;
import java.util.zip.ZipFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PostCodeSort
{
Queue<String> postcodeStack = new LinkedList<String>();
public static void main(String[] args) throws IOException
{
FileReader fileReader = null;
ZipCodeValidator zipCodeValidator = new ZipCodeValidator();
// Create the FileReader object
try {
fileReader = new FileReader("postcodes1.txt");
BufferedReader br = new BufferedReader(fileReader);
String str;
while((str = br.readLine()) != null)
{
if(zipCodeValidator.isValid(str)){
System.out.println(str + " is valid");
}
else{
System.out.println(str + " is not valid");
}
}
}
catch (IOException ex)
{
// handle exception;
}
finally
{
fileReader.close();
}
}
}
public class ZipCodeValidator {
private static String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
private static Pattern pattern = Pattern.compile(regex);
public boolean isValid(String zipCode) {
Matcher matcher = pattern.matcher(zip);
return matcher.matches();
}
}
Possibly a copy+paste issue, but Matcher matcher = pattern.matcher(zip); doesn't match the method parameter zipCode. Do you have zip defined somewhere else, and possibly validating against that?
It's when I added the read file code thats when the problems arose like the ones I specified above
Make sure you clean up the String before you pass it in. To remove any leading or trailing whitespace characters use
if(zipCodeValidator.isValid(str.strip())){
lastly, your regex only matches upper case. Make sure you allow all cases by using
str.strip().toUpperCase()
or changing your Regex:
private static Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
I've written two separate pieces of code. Now I want to merge both pieces of code. Now one part opens a text file and displays the contents of the text file and the second piece of code validates manually entered postcodes. Now I want to read a text file and then automatically validate postcodes within the text file. Not sure how I can merge them. Any questions please ask as I'm stuck.
package postcodesort;
import java.util.*;
import java.util.Random;
import java.util.Queue;
import java.util.TreeSet;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class PostCodeSort
{
Queue<String> postcodeStack = new LinkedList<String>();
public static void main(String[] args) throws IOException
{
FileReader fileReader = null;
// Create the FileReader object
try {
fileReader = new FileReader("postcodes1.txt");
BufferedReader br = new BufferedReader(fileReader);
String str;
while((str = br.readLine()) != null)
{
System.out.println(str + "");
}
}
catch (IOException ex)
{
// handle exception;
}
finally
{
fileReader.close();
}
// Close the input
}
}
Second part that manually validates postcodes:
List<String> zips = new ArrayList<String>();
//Valid ZIP codes
zips.add("SW1W 0NY");
zips.add("PO16 7GZ");
zips.add("GU16 7HF");
zips.add("L1 8JQ");
//Invalid ZIP codes
zips.add("Z1A 0B1");
zips.add("A1A 0B11");
String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
Pattern pattern = Pattern.compile(regex);
for (String zip : zips)
{
Matcher matcher = pattern.matcher(zip);
System.out.println(matcher.matches());
}
You should create a class called something like ZipCodeValidator that contains the functionality of your second snippet. It will look something like this
public class ZipCodeValidator {
private static String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
private static Pattern pattern = Pattern.compile(regex);
public boolean isValid(String zipCode) {
Matcher matcher = pattern.matcher(zip);
return matcher.matches();
}
}
Then you can create an instance of this class
ZipCodeValidator zipCodeValidator = new ZipCodeValidator();
and then use it in your main method
boolean valid = zipCodeValidator.isValid(zipCode);
Merging your question and the answer by #hiflyer I posted this answer, this makes an assumption that the file postcodes1.txt has all the zip codes in separate lines.
package postcodesort;
import java.util.*;
import java.util.Random;
import java.util.Queue;
import java.util.TreeSet;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class PostCodeSort
{
Queue<String> postcodeStack = new LinkedList<String>();
public static void main(String[] args) throws IOException
{
FileReader fileReader = null;
ZipCodeValidator zipCodeValidator = new ZipCodeValidator();
// Create the FileReader object
try {
fileReader = new FileReader("postcodes1.txt");
BufferedReader br = new BufferedReader(fileReader);
String str;
while((str = br.readLine()) != null)
{
if(zipCodeValidator.isValid(str)){
System.out.println(str + " is valid");
}
else{
System.out.println(str + " is not valid");
}
}
}
catch (IOException ex)
{
// handle exception;
}
finally
{
fileReader.close();
}
}
}
public class ZipCodeValidator {
private static String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
private static Pattern pattern = Pattern.compile(regex);
public boolean isValid(String zipCode) {
Matcher matcher = pattern.matcher(zip);
return matcher.matches();
}
}
In a part of my university project I have to get a text with some lines then saving it in a string or a string array.My problem is that in scanner class using methods gets only one line of the input. So I cannot get the other lines.please help me.
public class Main {
public static void main(String[] args) {
java.util.Scanner a = new java.util.Scanner(System.in);
String b = "";
while (a.hasNextLine()) {
b += a.nextLine();
}
}
}
You can try to use isEmpty to detect an enter-only input.
UPDATED:
If your input also contain a blank line, then you may specify another terminator character(s); instead of only an empty string.
public class Main {
public static void main(String[] args) {
//for example ",,"; then the scanner will stop when you input ",,"
String TERMINATOR_STRING = ",,"
java.util.Scanner a = new java.util.Scanner(System.in);
StringBuilder b = new StringBuilder();
String strLine;
while (!(strLine = a.nextLine()).equals(TERMINATOR_STRING)) {
b.append(strLine);
}
}
}
If you are building your program from command line, then there's something called "input redirection" which you can use. Here's how it works:
Let's suppose your program is:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ScanningMultiline
{
public static void main (String[] args)
{
List<String> lines = new ArrayList<> ();
try (Scanner scanner = new Scanner (System.in))
{
while (scanner.hasNextLine ())
{
lines.add (scanner.nextLine ());
}
}
System.out.println ("Total lines: " + lines.size ());
}
}
Now suppose you have input for your program prepared in a file.
To compile the program you'd change the current directory of terminal/command prompt to the program directory and then write:
javac ScanningMultiline.java
And then to run, use input redirection like:
java ScanningMultiline < InputFile.txt
If your InputFile.txt is in another directory, just put its complete path instead like:
java ScanningMultiline < "/Users/Xyz/Desktop/InputFile.txt"
Another Approach
You can try reading your input directly from a file. Here's how that program would be written:
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ScanningMultiline
{
public static void main (String[] args)
{
final String inputFile = "/Users/Xyz/Desktop/InputFile.txt";
List<String> lines = new ArrayList<> ();
try (Scanner scanner = new Scanner (Paths.get (inputFile)))
{
while (scanner.hasNextLine ())
{
lines.add (scanner.nextLine ());
}
}
catch (IOException e)
{
e.printStackTrace ();
}
System.out.println ("Total lines: " + lines.size ());
}
}
This approach reads directly from a file and puts the lines from the file in a list of String.
Another Approach
You can read the lines from a file and store them in a list in a single line as well, as the following snippet demonstrates:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class ScanningMultiline
{
public static void main (String[] args) throws IOException
{
final String inputFile = "/Users/Xyz/Desktop/InputFile.txt";
List<String> lines = Files.readAllLines (Paths.get (inputFile));
}
}
Yohanes Khosiawan has answered a different approach so I'm not writing that one here.