Java URL method not filling properly with recursion - java

import java.util.Scanner;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
public class Main {
// takes user input and validates
public static URL URLPrompt() throws MalformedURLException {
URL pageLocation = null;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a webpage URL to find all it's links: ");
try {
pageLocation = new URL(in.nextLine());
} catch (MalformedURLException exception) {
System.out.println("Invalid URL");
URLPrompt();
}
return pageLocation;
}
public static void main(String[] args) throws MalformedURLException, IOException {
Scanner in = new Scanner(System.in);
URL pageLocation = URLPrompt();
Scanner scan = new Scanner(pageLocation.openStream());
while (scan.hasNext()) {
String webFile = scan.nextLine();
// Searches for all hyperlinks in <a href=> </a> form
if (webFile.contains("<a href=") && webFile.contains("</a>")) {
int x = webFile.indexOf("<a href=");
int y = webFile.indexOf("</a>");
String link = webFile.substring(x, y + 4);
System.out.printf("%s\n", link);
}
}
scan.close();
in.close();
}
}
So this program is supposed to take a user inputted url link and print out all of the hyperlinks in html form, "a href" to the closing "a" tag. This code does just that if the url is valid initially. However, if an invalid url is input the system catches it and the Urlprompt method calls itself, when the method calls itself after an invalid input and then a valid URL is input during recursion I get a nullpointer exception on line 24... How can I get the URLPrompt method to accurately fill the variable pageLocation during recursion?

The recursive call should be return URLPrompt().
BTW: I wouldn't use recursion for this purpose (it's just a waste of stack frames), just a simple while loop.

Related

How to display asterisk (*) when user input their password, and after that store the password as String in Java

Can I ask that is there any method to display asterisk (*) when user input their password, and store the password entered as String value in Java ? Thanks
import java.util.*;
public class Log_in_form {
Scanner scan=new Scanner(System.in);
public static void main(String[] args) {
String username="rosas";
String password="sandy";
System.out.println("Enter username");
String user=scan.next();
System.out.println("Enter password");
String pass=scan.next();
if(user.equals(username)&&(pass.equals(password))){
System.out.println("Log in success");
}
else{
System.out.println("log in failed");
}
}
}
The java.io.Console.readPassword() method reads a password from the console with echoing disabled.
Declaration
Following is the declaration for java.io.Console.readPassword() method −
public char[] readPassword()
Parameters
N/A
Return Value
This method returns a character array containing the password read from the console, not including the line termination character, or null if an end of stream has been reached.
Exception
IOError − If an I/O error occurs.
Example
The following example shows the usage of java.io.Console.readPassword() method.
import java.io.Console;
public class ConsoleDemo {
public static void main(String[] args) {
Console cnsl = null;
String alpha = null;
try {
// creates a console object
cnsl = System.console();
// if console is not null
if (cnsl != null) {
// read line from the user input
alpha = cnsl.readLine("Name: ");
// prints
System.out.println("Name is: " + alpha);
// read password into the char array
char[] pwd = cnsl.readPassword("Password: ");
// prints
System.out.println("Password is: "+pwd);
}
} catch(Exception ex) {
// if any error occurs
ex.printStackTrace();
}
}
}
For more details go through
How to use Scanner to read silently from STDIN in Java?

Use Scanner on csv, iterate every time method is called

I am trying to parse a text document that has release notes and grab specific ones. To do that I have a csv with the desired release note keys. I want to scan the csv and use each key to find the matching section of the release note, and print the description that follows.
I would like to use the Scanner class for this to practice with it.
The csv looks like:
foobar-123,foobar-127,foobar-129
The release note text doc looks like:
foobar-123: ewkjhlq kghlhrekgh
foobar-124: lkjhfgrelgkj nberg
foobar-127: ljdfgl kjwneglkjn fdg
foobar-129: lguwlrkguj gwrlekgj werlktj
The issue I am running into is iterating through the csv. I seem to keep grabbing the first string in the csv. I am trying to figure out how to save my place in the csv, so every time the method is called, it goes to the next string.
I'm thinking I could create a variable that saves the last found string, and then use scanner to find that and then grab the next string. But that would require scanning through the csv each time I want to progress and which does not seem efficient. What would be the best way to iterate through the csv using the Scanner class?
Here is the code I have so far:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class ReleaseNotesScan {
public static void main(String[] args) {
//Open csv file with issue keys
Scanner getIssueKeys = null;
try {
getIssueKeys = new Scanner(new FileReader("resources/Issues.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Open release notes
Scanner releaseNotes = null;
try {
releaseNotes = new Scanner(new FileReader("resources/Release notes text.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Get issue key from csv
String issueKey = Finders.issueKey(getIssueKeys);
//The below three lines are just for testing if I am iterating through the csv
System.out.println(issueKey);
Finders.issueKey(getIssueKeys);
System.out.println(issueKey);
//Get issue key and description
String description = Finders.sectionContent(releaseNotes, issueKey);
System.out.println(issueKey + ": " + description);
//Close csv
getIssueKeys.close();
//Close release notes
releaseNotes.close();
}
}
My Finders class:
import java.util.Scanner;
public class Finders {
//parse csv
public static String issueKey(Scanner findIssues) {
findIssues.useDelimiter(",");
String issue = findIssues.next();
return issue;
}
public static String sectionContent(Scanner releaseNotes, String heading) {
while (releaseNotes.hasNextLine()){
String found = releaseNotes.findInLine(heading);
if (found != null){
releaseNotes.findInLine(": ");
String grabIt = releaseNotes.nextLine();
return grabIt;
}
releaseNotes.nextLine();
}
releaseNotes.close();
return "Not found";
}
}
Here is some example code to demonstrate how the application can be structured. I made some assumptions that the input file "issues" as a string (instead of a file, for brevity). The issues are stored in an array and release notes in HashMap collection. The release notes are read from the file, tokenized (split with ":" as delimiter) as the issue and its release-note text. The issue is the key and the release-note is the value in the map.
Finally, iterate each issue and get the corresponding release-note from the map.
Example Code:
import java.util.*;
import java.io.*;
public class MatchIssues {
private static String [] issues;
private static Map<String,String> releseNotes = new HashMap<>();
public static void main(String [] args)
throws IOException {
getIssues();
getReleaseNotes();
for(String issue : issues) {
// Match release notes for the issue
System.out.println(releseNotes.get(issue));
}
}
private static void getIssues() {
String s = "foobar-123,foobar-127,foobar-129"; // use string for demo
issues = s.split(",");
System.out.println(Arrays.toString(issues));
}
private static void getReleaseNotes()
throws IOException {
BufferedReader reader =
new BufferedReader(new FileReader("release_notes.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
String [] tokens = line.split(":");
releseNotes.put(tokens[0].trim(), tokens[1].trim());
}
System.out.println(releseNotes);
}
}
release_notes.txt:
foobar-123: aa ewk jhlq kghlhrekgh aa
foobar-124: bb lkjh fgrelgkj nberg bb
foobar-127: yy ljdfgl kjw neglkjn fdg yy
foobar-129: zz lgu wlrkguj gw rlekgj werlktj zz

NoSuchElementExcpetion when using Java scanner to compare two files

I am trying to see the possibilities of automating localization testing of web application(L10N). Firstly, we decided to see if without opening an application, if we can gather HTML plain text(native language)in a file & compare this with the glossary we have.
I am able to get plain text using jsoup. Now I am trying to compare these two files with below code:
import java.io.*;
import java.util.*;
class CompareFiles{
public static void main(String args[]) throws Exception{
Scanner kb = new Scanner(System.in);
String name;
String curr;
java.io.File dictionary = new java.io.File("./src/main/resources/Google_JP.txt");
Scanner dictScanner = new Scanner(dictionary);
java.io.File list = new java.io.File("./src/main/resources/Google_JP_HTML.txt");
Scanner listScanner = new Scanner(list);
try
{
while(dictScanner.hasNextLine()){
System.out.println("inside dictonary scanner");
curr=dictScanner.next();
while(listScanner.hasNextLine()){
System.out.println("inside list scanner");
name=listScanner.next();
if(curr.contains(name)) System.out.println(name);
}
}
}
catch(NoSuchElementException e)
{
e.printStackTrace();
}
}
}
Now problem with above code is, since I was getting NoSuchElementException on name=listScanner.next(); I tried to handle exception and close the scanner. With this, it is only comparing the first word of html file. How I should make it work, so that it will display all matching words?
Also I am not sure if I am following the right approach to meet the requirement.
looks to me as if you would need to reinitialize the scanner on every loop iteration as you exhaust it on the first iteration
what happens seems to be:
curr is the first line from dictScanner
loop over nameScanner
curr compared with all names
name scanner is now empty
curr is set to second line
loop over nameScanner which is already exhausted
proposed change:
import java.io.*;
import java.util.*;
class CompareFiles{
public static void main(String args[]) throws Exception{
Scanner kb = new Scanner(System.in);
String name;
String curr;
java.io.File dictionary = new java.io.File("./src/main/resources/Google_JP.txt");
Scanner dictScanner = new Scanner(dictionary);
java.io.File list = new java.io.File("./src/main/resources/Google_JP_HTML.txt");
//Scanner listScanner = new Scanner(list);
try
{
while(dictScanner.hasNextLine()){
System.out.println("inside dictonary scanner");
curr=dictScanner.next();
try (Scanner listScanner = new Scanner(list);){
while(listScanner.hasNextLine()){
System.out.println("inside list scanner");
name=listScanner.next();
if(curr.contains(name)) System.out.println(name);
}
}
}
} catch(NoSuchElementException e) {
e.printStackTrace();
}
}
}

Simultaneous searching of multiple words in an external file(Java)

The program that I am trying to create is a program that takes words from a user defined file, saves those words as variables and then searches a different user defined file for those words, outputting there location.
The program works up to and including the point where the program takes the words and saves them as variables. The problem with the program is that the search method returns a null result. My main suspicions are that the code in the search method is incompatible with the code in the read method, or that the 2 methods aren't running simultaneously.
The search method is in the searching class and the read method is in the reading class.
Here is my code (Containing all 3 of my classes), please excuse all of the imports.
This is the first class:
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Combination{
public static void main(String[] args) throws FileNotFoundException{
Scanner userInput = new Scanner(System.in);
Reading ReadingObject = new Reading();
System.out.println("Please enter the file that you wish to open");
String temp = userInput.nextLine();
ReadingObject.setFileName(temp);
ReadingObject.read();
Scanner searchForWord = new Scanner(System.in);
Searching SearchingObject = new Searching();
System.out.println("Please enter the file that you would like to search for these words in");
String temp1 = searchForWord.nextLine();
SearchingObject.setFileName(temp1);
SearchingObject.search();
}
}
This is the second class:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
class Reading {
private String file;
public void setFileName(String fileName){
file = fileName;
}
public String getFileName(){
return file;
}
public void read(){
try{
//Choosing the file to open
FileInputStream fstream = new FileInputStream(getFileName());
//Get the object of datainputstream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
//Read the file line by line
while((strLine = br.readLine()) != null){
// \\s+ means any number of whitespaces between tokens
String [] tokens = strLine.split("\\s+");
String [] words = tokens;
for(String word : words){
System.out.print(word);
System.out.print(" ");
Searching SearchingObject = new Searching();
SearchingObject.setWord(word);
}
System.out.print("\n");
}
in.close();
}
catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
This is the third class:
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Searching {
private String file1;
public void setFileName(String fileName){
file1 = fileName;
}
public String getFileName(){
return file1;
}
private String word1;
public void setWord(String wordName){
word1 = wordName;
}
public String getWord(){
return word1;
}
public void search() throws FileNotFoundException{
try{
//Choosing the file to open
FileInputStream fstream = new FileInputStream(getFileName());
//Get the object of datainputstream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
while((strLine = br.readLine()) != null){
Pattern p = Pattern.compile(getWord());
Matcher m = p.matcher(strLine);
int start = 0;
while (m.find(start)) {
System.out.printf("Word found: %s at index %d to %d.%n", m.group(), m.start(), m.end());
start = m.end();
}
}
}
catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
Any help will be greatly appreciated.
Regards
Your code is hard to read. Your reading class does not only read; it also searches. You should call it something that reflects its intended use. However, it forgets to tell its searching object where to search, and does not pass the reference to this object to anyone else. In this snippet
for (String word : words) {
System.out.print(word);
System.out.print(" ");
searching searchingObject = new searching();
searchingObject.setWord(word);
}
you are essentially not doing anything. The reference to searchingObject is lost forever.
Your reading class should keep an ArrayList of words to be searched for in the searching, instead of instancing searching objects.
Your searching class should take, as a constructor parameter, one of these ArrayLists -- and convert it into a single regex, which is much more efficient than reading the file once per word to search for. You can search for "a", "b" and "c" using the single regular expression "a|b|c". Works with longer words, too. Escape them first to avoid problems.
Oh, and please, please follow naming guidelines. Call your reading a TokenReader, and your searching a WordListSearcher...

problem in reading text file

I have a text file where i have names and passwords separated by :.
user1:pwd1
user2:pwd2
In the login page if the user gives the correct username and password it will lead you to the welcome page. But I am not getting this properly. The output which i get is
user1
pwd1
inside try
user1
pwd1
true
welcome user1
user2
pwd2
false
not equal
My code is below.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.regex.*;
import com.sun.org.apache.xalan.internal.xsltc.compiler.Pattern;
public class TextFile {
/**
* #param args
*/
public void getNamePwd(String name, String pwd) {
// TODO Auto-generated method stub
System.out.println(name);
System.out.println(pwd);
String[] splitVals=null;
try{
System.out.println("inside try");
String strLine;
BufferedReader br = new BufferedReader(new FileReader("D:\\test\\text.txt"));
while((strLine=br.readLine())!=null){
splitVals=strLine.split(":");
for(int i=0;i<splitVals.length;i=i+2){
System.out.println(splitVals[i].toString());
System.out.println(splitVals[i].toString());
String nameUser=splitVals[i].toString();
String passWord=splitVals[i+1].toString();
System.out.println(name.equals(nameUser));
if((name.equals(nameUser))&&(pwd.equals(passWord))){
System.out.println("welcome"+name);
}
else{
System.out.println("not equal");
}
}
}
}catch(Exception e){
}
}
}
please help me..
I suspect that you want to stop looking for username/password matches after you've found one... To do this you have to break the loop upon a match. To do this you do the following:
readLoop:
while((strLine=br.readLine())!=null){
// ...
String[] splitVals = strLine.split(":");
if((name.equals(nameUser))&&(pwd.equals(passWord))){
System.out.println("welcome"+name);
break readLoop;
}
// ...
}
Besides, I don't know why you need this loop:
for(int i=0;i<splitVals.length;i=i+2)
Recall that you read the file line by line. That is, the splitted array will contain the username and password of the current line.
To print the username / password you could do something like this:
System.out.printf("Username: %s, Password: %s%n", splitVals[0], splitVals[1]);
I would probably solve it using a Scanner. Something like this:
import java.io.*;
import java.util.Scanner;
public class TextFile {
public static void main(String[] args) throws FileNotFoundException {
if (userPassOk("hello", "world"))
System.out.println("Welcome");
else
System.out.println("Get out!");
}
private static boolean userPassOk(String user, String pass)
throws FileNotFoundException {
Scanner s = new Scanner(new File("test.txt"));
while (s.hasNextLine()) {
String[] userPass = s.nextLine().split(":");
if (userPass[0].equals(user) && userPass[1].equals(pass))
return true;
}
return false;
}
}
Try resetting the value of nameUser and passWord at the end of the try()
as in
nameUser="";
passWord="";
Your print statements are wrong. That's why you can't debug this properly.
What you are printing does not match what you are using for the name and password. Fix this and try printing it out again.
for(int i=0;i<splitVals.length;i=i+2){
System.out.println(splitVals[i].toString());
System.out.println(splitVals[i].toString());
String nameUser=splitVals[i].toString();
String passWord=splitVals[i+1].toString();
However, you don't need this loop. You can just use:
String nameUser=splitVals[0];
String passWord=splitVals[1];
put break if your condition is satisfied.Don't allowed continue the loop.If you put the brak here.you got your expected output.
if((name.equals(nameUser))&&(pwd.equals(passWord))){
System.out.println("welcome"+name);
break;
}

Categories