I have a simple textfile:
type = "hello"
number = 66
type = "hey"
number = 77
I'm basically just checking to see if the string "type" is found in the textfile, if yes, I'd also like to get the values "hello" and "hey" i.e the types. However, my program doesn't work at all in that sense it all always prints no, when checking if "type" is in the file.
public static void main(String[] args) {
if(args.length == 1)
parseText(argv[0]); // call with textfile name
}
public void parseText(String inPath) {
try {
Scanner s = new Scanner(inPath);
while(s.hasNextLine()) {
if("type".equals(s.nextLine().trim()))
System.out.println("Yes");
else {
System.out.println("no");
}
}
}catch (Exception e ) {
System.out.println("\nFILE NOT FOUND");
}
}
Any help would be much appreciated.
if("type".equals(s.nextLine().trim()))
You really want to read the line of data from the file into a String so you can do processing on the string.
You want to know if the line starts with "type":
String line = s.nextLine()
if (line.startsWith("type"))
{
String value = line.substring(8);
System.out.println(value);
}
Check if the line starts with "type" (not is equal to "type").
if("type".equals(s.nextLine().trim()))
should be something like
String line = s.nextLine().trim();
if (line.startsWith("type"))
Related
Before asking this question , i spent around half an hour on google , but since i didn't find a solution i thought i maybe should ask here.
So basically i'm using Java Reader to read a text file and converting each line of information into an Object that i called Nation ( With a constructor of course ) and making an array out of all those objects.
The problem is that a single line on my text file goes to 75 characters. But i get an error telling me that the length is only 68 ! So Here's the part of the code where i read informations from the file :
static int lireRemplir (String nomFichier, Nation[] nations)
throws IOException
{
boolean existeFichier = true;
int n =0;
FileReader fr = null;
try {
fr = new FileReader(nomFichier);
}
catch (java.io.FileNotFoundException erreur) {
System.out.println("Probléme avec l'ouverture du fichier " + nomFichier);
existeFichier = false;
}
if (existeFichier) {
BufferedReader entree = new BufferedReader(fr);
boolean finFichier = false;
while (!finFichier) {
String uneLigne = entree.readLine();
if (uneLigne == null) {
finFichier=true;
}
else {
nations[n] = new Nation(uneLigne.charAt(0),uneLigne.substring(55,63),
uneLigne.substring(64,74),uneLigne.substring(1,15),uneLigne.substring(36,54));
n++;
}
}
entree.close();
}
return n;
}
The Error i get is :
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
begin 64, end 74, length 68
Since i'm new here i tried to post an image of my text but i couldn't, so i'll just try to hand write an exemple:
2ETATS-UNIS WASHINGTON 9629047 291289535
4CHINE PEKIN 9596960 1273111290
3JAPON KYOTO 377835 12761000
There is alot of space between the words it's like an array!
If i change the 74 to 68 i get a result when i try to print my array , but the information is missing.
Here's my constructor:
public Nation(char codeContinent, String superficie, String population, String nom, String capitale) {
this.codeContinent = codeContinent;
this.superficie = superficie;
this.population = population;
this.nom = nom;
this.capitale = capitale;
}
I hope you could help me with this! If you need to know more about my code let me know ! Thank you very much.
To avoid Runtime Exceptions, you need to be careful with your code. In cases where you are dealing with indexes of a String or an array, please check for length of the String to be greater or equal to the maximum index you are using. Enclose you code that is throwing the exception within:
if(uneLigne.length() > 74) {
nations[n] = new Nation(uneLigne.charAt(0),uneLigne.substring(55,63),
uneLigne.substring(64,74),uneLigne.substring(1,15),uneLigne.substring(36,54));
} else {
//your logic to handle the line with less than 74 characters
}
This will ensure your code does not break even if any line is smaller than expected characters.
______________________________________________________________________________
Another approach
Adding the comment as an answer:
The other way would be to use split() method of String class or StringTokenizer class to get the array/tokens if the line is delimited with space or some other character. With this, you need not break the string using substring() method where you need to worry about the lengths and possible Runtime.
Check the below code snippet using split() method, for each line you read from file, you probably have to do this way:
Nation nation = null;
String uneLigne = "2ETATS-UNIS WASHINGTON 9629047 291289535";
String[] strArray = uneLigne.split(" ");
if(strArray.length > 3) {
nation = new Nation(getContinentCodeFromFirstElement(strArray[0]), strArray[1],
strArray[2], strArray[3], strArray[4]);
}
//getContinentCodeFromFirstElement(strArray[0]) is your private method to pick the code from your first token/element.
The simpliest way to solve your problem is to change the 74 by uneLigne.length.
Here's the new code.
nations[n] = new Nation(uneLigne.charAt(0),uneLigne.substring(55,63),
uneLigne.substring(64,uneLigne.length),uneLigne.substring(1,15),uneLigne.substring(36,54));
I am currently working on a Java program that crawls a webpage and prints out some information from it.
There is one part that I can't figure out, and thats when I try to print out one specific String Array with some information in it, all it gives me is " ] " for that line. However, a few lines before, I also try printing out another String array in the exact same way and it prints out fine. When I test what is actually being passed to the "categories" variable, its the correct information and can be printed out there.
public class Crawler {
private Document htmlDocument;
String [] keywords, categories;
public void printData(String urlToCrawl)
{
nextURL=urlToCrawl;
crawl();
//This does what its supposed to do. (Print Statement 1)
System.out.print("Keywords: ");
for (String i :keywords) {System.out.print(i+", ");}
//This doesnt. (Print Statement 2)
System.out.print("Categories: ");
for (String b :categories) {System.out.print(b+", ");}
}
public void crawl()
{
//Gather Data
//open up JSOUP for HTTP parsing.
Connection connection = Jsoup.connect(nextURL).userAgent(USER_AGENT);
Document htmlDocument = connection.get();
this.htmlDocument=htmlDocument;
System.out.println("Recieved Webpage "+ nextURL);
int guacCounter = 0;
for(Element guac : htmlDocument.select("script"))
{
if(guacCounter==5)
{
//String concentratedGuac = guac.toString();
String[] items = guac.toString().split("\\n");
categories = processGuac(items);
break;
}
else if(guacCounter<5) {
guacCounter++;
}
}
}
public String[] processKeywords(String totalKeywords)
{
String [] separatedKeywords = totalKeywords.split(",");
//System.out.println(separatedKeywords.toString());
return separatedKeywords;
}
public String[] processGuac(String[] inputGuac)
{
int categoryIsOnLine = 6;
String categoryData = inputGuac[categoryIsOnLine-1];
categoryData = categoryData.replace(",","");
categoryData = categoryData.replace("'","");
categoryData = categoryData.replace("|",",");
categoryData = categoryData.split(":")[1];
//this prints out the list of categories in string form.(Print Statement 3)
System.out.println("Testing here: " + categoryData.toString());
String [] categoryList=categoryData.split(",");
//This prints out the list of categories in array form correctly.(Print statement 4)
System.out.println("Testing here too: " );
for(String a : categoryList) {System.out.println(a);}
return categoryList;
}
}
I cut out a lot of the irrelevant parts of my code so there might be some missing variables.
Here is what my printouts look like:
PS1:
Keywords: What makes a good friend, making friends, signs of a good friend, supporting friends, conflict management,
PS2:
]
PS3:
Testing here: wellbeing,friends-and-family,friendships
PS4:
Testing here too:
wellbeing
friends-and-family
friendships
I have trouble splitting a name by a space, and I can't seem to figure out why. Could someone please provide me with a solution?
My code is like this:
public void getPlayerNames(int id){
try {
Document root = Jsoup.connect("http://www.altomfotball.no/element.do?cmd=team&teamId=" + id).get();
Element table = root.getElementById("sd_players_table");
Elements names = table.getElementsByTag("a");
for(Element name : names){
getPlayers().add(new Player(name.text()));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
which returns the name of football players as a string. The names are retrieved such as Mario Balotelli, Steven Gerrard, and so on, and I assumed I could use string.split(" "); to get me the first and last names, but whenever I try to access the second space of the string array it gives me an index out of bounds exception. Here is the code trying to fetch me the first name
/**
* Method to get the first name of a player
*/
public static String getFirstName(String name){
String[] nameArray = name.split(" ");
return nameArray[0];
}
Thanks for answers!
Sindre M
EDIT ######
So I got it to work, but thanks for the effort. The problem was that even though I could not see it in a simple sysout statement, the names actually contained a " "; character, so I solved it by running a replaceAll("  ;" , " ") on the names for a better formatting.
If you're trying to write a screen-scraper you need to be more defensive in your code... Definitely test the length of the array first and log any unexpected inputs so you can incorporate them later...
public static String getFirstName(String name) {
String[] nameArray = name.split(" ");
if (nameArray.length >= 1) { // <== check length before you access nameArray[0]
return nameArray[0];
} else {
// log error
}
return null;
}
Additionally java.util.Optional in Java 8 provides a great alternative to returning null...
public static Optional<String> getFirstName(String name) {
String[] nameArray = name.split(" ");
if (nameArray.length >= 1) {
return Optional.of(nameArray[0]);
} else {
// log error
}
return Optional.empty();
}
You might be getting in the actual string as you are retrieving from html page. try to debug and check.
package com.appkart.examples;
public class SplitProgram {
public void firstNameArray(String nameString) {
String strArr[] = nameString.split(",");
for (String name : strArr) {
String playerName = name.trim();
String firstName = playerName.substring(0, playerName.indexOf(" "));
System.out.println(firstName);
}
}
public static void main(String[] args) {
String nameString = "Mario Balotelli, Steven Gerrard";
SplitProgram program = new SplitProgram();
program.firstNameArray(nameString);
}
}
I think that the correct answer should be:
String[] nameArray = name.split("\\s+");
But to be honest, there are couple of answers at stackoverflow.
Eg.
How to split a String by space
How do I split a string with any whitespace chars as delimiters?
First try to replace white space as
string.replace(" ","");
then try to split with [,] as
String strAr[] = string.split(",");
Here I've base String called String baseString = "nullpointer"; if user entered some strings like pointernull, llpointer, internullpo then it should print TRUE else FALSE. How to write the logic for this? please help me.
public class literalString {
public static void main(String[] args) {
String baseString = "nullpointer";
Scanner sc = new Scanner(System.in);
String input = sc.next();
//pointernull, llpointer, internullpo then return TRUE.
// pointerllnu, unpointerll then return FALSE
//what shoul be the logic here?
}
}
Your help will be appreciated.
First check baseString.length==input.lengthif it is fails then it is wrong
if it is true then check using concat and contains
Simple example
String baseString = "nullpointer";
Scanner sc = new Scanner(System.in);
String input = sc.next();
if(baseString.length()!=input.length()){
System.out.println("false");
}
else{
if(baseString.concat(baseString).contains(input)){
System.out.println("true");
}
else{
System.out.println("false");
}
}
Try something like this:
String[] valueList = {"pointernull", "llpointer", "internullpo"};
if(Arrays.asList(valueList).indexOf(input) != -1) {
// User has typed "pointernull", "llpointer" or "internullpo"
}else{
// User has typed something else
}
Simply:
(base.concat(base)).contains(input);
So if your base is nullpointer, then base.concat(base) will yield nullpointernullpointer, and contains will return trueon nullp, pointernull, ointernu, etc.
Could you please share a java code snippet to convert 5 or 9 digit number to US ZIP code format
e.g.
Input -> Expected output
12345 -> 12345
123456789 -> 12345-6789
Below code works but for 5 digit it ends with -. How to remove this using regular expression?
public static void main(String[] args) throws ParseException {
String[] values = new String[]{"1234","12345","123456897"};
MaskFormatter f = new MaskFormatter("#####-####");
f.setValueContainsLiteralCharacters(false);
for(String value:values){
System.out.println(f.valueToString(value));
//System.out.println(String.format("%5s-%04s", value,value));
}
}
Output is:
234 -
12345-
12345-6897
Try,
String[] values = new String[]{"1234","12345","123456897"};
MaskFormatter f = new MaskFormatter("#####-####");
f.setValueContainsLiteralCharacters(false);
for(String value:values){
String output=f.valueToString(value).trim();
if(output.endsWith("-")){
output=output.substring(0,output.length()-1);
}
System.out.println(output);
//System.out.println(String.format("%5s-%04s", value,value));
}
Output:
1234
12345
12345-6897
public static String convertZip(String unconverted) {
if (unconverted.length() > 5) {
return unconverted.substring(0, 5) + "-" + unconverted.substring(5);
}
else {
return unconverted;
}
}
you can convert your number(any number of digit) to String and then validate the length and consider only length = 5 and length =9. Then you can take value as it is if length is 5. if length is 9 use substring() in Java and divide your String 0-5 and 5-9 then add - between two part. Now it is your zip code.
Just create two formatters and use the appropriate one based on the length of the value.
public static void main(String... args) throws ParseException {
String[] values = new String[] { "1234", "12345", "123456897" };
MaskFormatter f5 = new MaskFormatter("#####");
f5.setValueContainsLiteralCharacters(false);
MaskFormatter f9 = new MaskFormatter("#####-####");
f9.setValueContainsLiteralCharacters(false);
for (String value : values) {
System.out.println(value.length() > 5 ? f9.valueToString(value) : f5.valueToString(value));
}
}
Personally, I think I'd go in a different direction:
public static void main(String... args) throws ParseException {
String[] values = new String[] { "1234", "12345", "123456897" };
for (String value : values) {
System.out.println(value.length() > 5 ? new StringBuilder(value).insert(5, "-").toString() : value);
}
}
Try this,
var reformat = "123456789".replace(/(\d{5})/g, function(match){
return match + "-";
});
console.log(reformat.replace(/\-$/, ""));