Searching a string from a line - java

After parsing a webpage i have found this line
"JANATAMF 7.30  -0.20    -2.67% 1STBSRS 80.00  -3.60    -4.31% 1STPRIMFMF 12.90  -0.80    -5.84% 6THICB 40.60  -2.50    -5.80% 8THICB 50.00  -1.30    -2.53% ABB1STMF 9.90  0.30    3.13% ACI   188.00     -5.90    -3.04% ACIFORMULA 82.70  0.50    0.61%"
now i want to find the corresponding integer value for any input such as
if i enter an input JANATAMF it will individually print 7.30 -0.20 -2.67%
i ve written a code but it does not look good..
public void stringfinder(String linktext,String input) throws NumberFormatException
{
try
{
if(linktext!=null)
{
String finalstr=linktext;
//System.out.print(finalstr);
int inplen=input.length();
if(finalstr.contains(input)) //CHECK THE USER INPUT IS IN STRING OR NOT WHICH RETURN BOOLEAN
{
//System.out.println("found");
int index=finalstr.indexOf(input); //FIND THE INDEX OR STARTING POINT OF THE STRING
//System.out.print(index);
int stpr=index+inplen+1; //AS WE VE TO PRINT THE NEXT STRING FROM THE INPUT STRING
//WE ADD THE STARTING POINT OF THE INPUT STRING AND THE LENGTH
//OF THE INPUT STRING
//int first=0;
int i=0;
String x="" ;
String ary[]=new String[10];
while(finalstr.charAt(stpr)!=' ' ) //PRINT UNTIL FIND A GAP
{
//System.out.print(finalstr.charAt(stpr));
Character c=new Character(finalstr.charAt(stpr));
String s=c.toString(c);
ary[i]=s;
x=x+ary[i];
i++;
stpr++;
//first++;
}
//System.out.print(x);
String yo=x;
System.out.print(yo);
//double d = Double.valueOf(yo.trim()).doubleValue();
/*int secstpr=stpr+1;
int second=0;
while(finalstr.charAt(secstpr)!=' ')
{
System.out.print(finalstr.charAt(secstpr));
secstpr++;
second++;
}*/
//System.out.print(second);
}
}
}
so plz help...

This is what #kev was referring to:
public String stringfinder(String linktext, String input) {
String [] inputSplits = input.split("\\s+");
for (int i = 0; i < inputSplits.length; i += 4) {
if (inputSplits[i].equals(linktext) {
return inputSplits[i + 1] + " " + inputSplits[i + 2]
+ " " + inputSplits[i + 3];
}
}
return "";
}
This will return the string you were searching for. Still I would suggest that instead you concatenate the strings here: return inputSplits[i + 1] + " " + inputSplits[i + 2] + " " + inputSplits[i + 3]; you interpret them more cleverly (e.g. construct numbers).

Related

How can I generated a list of data then query into the list?

I am new to Java and I am trying to build a Java command-line program, which generates random dataset (as in getData()) and query into the generated dataset. But I don't know how to pass the generated data from getData() function to the main function so that I can find the oldest person in my generated data.
public class Data {
public String first;
public String last;
public int age;
public int id;
public String country;
public Data(String first, String last, int age, int id, String country) {
this.first = first;
this.last = last;
this.age = age;
this.id = id;
this.country = country;
}
public String toString() {
return "{" +
" 'firstName': " + first + "," +
" 'lastName': " + last + "," +
" 'age': " + age + "," +
" 'id': " + id + "," +
" 'country': " + country +
" }";
}
public static ArrayList<Data> getData(int numRows) {
ArrayList<Data> generator = new ArrayList<>();
String[] names = {"James", "Matt", "Olivia", "Liam", "Charlotte", "Amelia", "Evelyn", "Taeyeon", "Sooyoung", "Tiffany", "Yoona", "Hayley"};
String[] lastName = {"Novak", "Forbis", "Corner", "Broadbet", "Kim", "Young", "Hwang", "Choi", "McDonalds", "Kentucky", "Holmes", "Shinichi"};
String[] country = {"New Zealand", "Vietnam", "Korea", "French", "Japan", "Switzerland", "Italy", "Spain", "Thailand", "Singapore", "Malaysia", "USA"};
String data = "";
Random ran = new Random();
int namesLength = numRows; // passing length to names_len
int lastNameLength = lastName.length; // passing length to lastname_len
int countryLength = country.length; // passing length to lastname_len
for (int i = 0; i < numRows; i++) { // for loop to iterate upto names.length
int x = ran.nextInt(namesLength); // generating random integer
int y = ran.nextInt(lastNameLength); // generating random integer
int z = ran.nextInt(countryLength);
int a = ran.nextInt(40);
int exampleId = ran.nextInt(1000);
// below for loop is to remove that element form names array
for (int j = x; j < (namesLength - 1); j++) {
names[j] = names[j + 1]; // this moves elements to one step back
}
// below for loop is to remove that element form Lastnames array
for (int j = y; j < (lastNameLength - 1); j++) {
lastName[j] = lastName[j + 1]; // this moves elements to one step back
}
for (int j = z; j < (countryLength - 1); j++) {
country[j] = country[j + 1]; // this moves elements to one step back
}
namesLength = namesLength - 1; // reducing len of names_len by 1
lastNameLength = lastNameLength - 1; // reducing len of lastname_len by 1
countryLength = countryLength - 1; // reducing len of lastname_len by 1
// Output data in NDJSON format
data = "{" +
" 'firstName': " + names[x] + "," +
" 'lastName': " + lastName[y] + "," +
" 'age': " + a + "," +
" 'id': " + exampleId + "," +
" 'country': " + country[z] +
" }";
System.out.println(data);
// How can I add data to the generator list, the generator.add(data) does not work
}
// return a list of data
return generator;
}
public static void main(String[] args) {
// Generate random data
int rows = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows (maximum 12) you want to generate: ");
rows = sc.nextInt();
while (rows >= 13 || rows <= 0) {
System.out.println("Rows must be in range of 1 and 12");
System.out.print("Please reenter the number of rows: ");
rows = sc.nextInt();
}
System.out.println("Data is now generated");
ArrayList<Data> generatedData = getData(rows);
String[] base_options = {
"1 - Find the oldest person",
"2 - Group by country and return count",
"3 - Choose a country and group by age range",
"4 - Find the youngest person",
};
System.out.println(base_options);
// Task 2
// TODO: PASTE GENERATED DATA INTO THIS
// Find oldest
Data oldest = generatedData.stream().max((a,b) -> a.age - b.age).get();
System.out.println(String.format("The oldest person is %s %s", oldest.first, oldest.last));
generator.add(new Data(names[x], lastName[y], a, exampleId, country[z])); works for me just fine
You can parse your generated data in string to Data and get the max valud like this:
public static void main(String[] args) {
// Generate random data
int rows = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows (maximum 12) you want to generate: ");
rows = sc.nextInt();
while (rows >= 13 || rows <= 0) {
System.out.println("Rows must be in range of 1 and 12");
System.out.print("Please reenter the number of rows: ");
rows = sc.nextInt();
}
System.out.println("Data is now generated");
ArrayList<String> generatedData = getData(rows);
// Find oldest
Data oldest = generatedData
.stream()
.map(it -> extractData(it))
.max(Comparator.comparingInt(a -> a.age))
.get();
System.out.println(String.format("The oldest person is %s %s", oldest.first, oldest.last));
}
private static Data extractData(String str) {
return new Data(
extractProperty(str, "firstName"),
extractProperty(str, "lastName"),
Integer.parseInt(extractProperty(str, "age")),
Integer.parseInt(extractProperty(str, "id")),
extractProperty(str, "country")
);
}
private static String extractProperty(String str, String keyName) {
String key = "'" + keyName + "': ";
int startIndex = str.indexOf(key) + key.length();
if (startIndex < 0) {
return "";
}
StringBuilder value = new StringBuilder();
for (int i = startIndex ; i < str.length() ; ++i) {
char ch = str.charAt(i);
if (ch == ',') {
break;
}
value.append(ch);
}
return value.toString();
}

Why does my code keep throwing a StringIndexOutOfBoundsException?

I have been trying to fix this for a while now and I just can't seem to get it. I'm trying to get the phone number from the user so I can display it but when I get all the users info the error occurs. Any help would be appreciated. Thank you.
Here is the code:
import java.util.Scanner;
public class Event
{
public static double pricePerGuestHigh = 35.00;
public static double pricePerGuestLow = 32.00;
public static final int LARGE_EVENT_MAX = 50;
public String phone = "";
public String eventNumber;
private int guests;
private double pricePerEvent;
public void setPhone()
{
Scanner input = new Scanner(System.in);
int count = 0;
System.out.println("Enter your phone number: ");
String phone = input.nextLine();
int len = phone.length();
for(int i=0; i<1; i++)
{
char c = phone.charAt(i);
if(Character.isDigit(c))
{
count++;
String ss = Character.toString(c);
phone = phone.concat(ss);
}
}
if(count != 10)
{
phone = "0000000000";
}
}
public String getPhone()
{
// The error occurs in this method
String ret = "(" + this.phone.charAt(0) + "" + this.phone.charAt(1)
+ "" + this.phone.charAt(2) + ")" + this.phone.charAt(3)
+ "" + this.phone.charAt(4) + "" + this.phone.charAt(5)
+ "" + this.phone.charAt(6) + "" + this.phone.charAt(7)
+ "" + this.phone.charAt(8) + "" + this.phone.charAt(9);
return ret;
}
public void setEventNumber()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the event number: ");
eventNumber = input.nextLine();
}
public void setGuests(int guests)
{
this.guests=guests;
if(isLargeEvent())
pricePerEvent = pricePerGuestHigh;
else
pricePerEvent = pricePerGuestLow;
}
public int getGuestsCount()
{
return guests;
}
public boolean isLargeEvent()
{
if(guests >= LARGE_EVENT_MAX)
{
return true;
}
else if(guests < LARGE_EVENT_MAX)
{
return false;
}
return isLargeEvent();
}
public String getEventNumber()
{
String ret1 = "Event Number: " + this.eventNumber;
return ret1;
}
public int getGuests(boolean largeEvent)
{
return guests;
}
}
The code where the error occurs has been marked with a comment.
The error means that you are trying to access the phone's character at an index that does not exists.
Precisely, your phone field is never set inside your code so it's an empty String.
Anyway, you should also fix the for loop by using the len variable:
int len = phone.length();
for(int i = 0; i < len; i++)
{
...
}
By doing that, you cannot concern about StringIndexOutOfBoundsException because now the for automatically traverse only the chars present in the String.
The StringOutOfBoundsException is thrown whenever you're attempting to access a character in the string that doesn't exist at the given index.
From the code you've provided it seems as though you're accessing an empty string in the method getPhone().
You can fix this by first checking if the string is empty with phone.isEmpty().
public String getPhone() {
if (phone == null || /*this.*/phone.isEmpty()) {
// Handle the error accordingly.
return null; // example
}
String ret = "(" + this.phone.charAt(0) + "" + this.phone.charAt(1)
+ "" + this.phone.charAt(2) + ")" + this.phone.charAt(3)
+ "" + this.phone.charAt(4) + "" + this.phone.charAt(5)
+ "" + this.phone.charAt(6) + "" + this.phone.charAt(7)
+ "" + this.phone.charAt(8) + "" + this.phone.charAt(9);
return ret;
}
While we're at it, I'd recommend not using string concatenation, as this will produce a large amount of overhead.
Instead, use Java's string formatting.
This will not only increase the readability of your code, but it will (as mentioned before) reduce overhead, because strings in Java are immutable.
To make your code work you should make new local var (for example inputPhone) and than change phone var of Event object. Also you should change condition in for loop.
public void setPhone()
{
Scanner input = new Scanner(System.in);
int count = 0;
System.out.println("Enter your phone number: ");
String inputPhone = input.nextLine();
int len = inputPhone.length();
for(int i=0; i<len; i++)
{
char c = inputPhone.charAt(i);
if(Character.isDigit(c))
{
count++;
String ss = Character.toString(c);
phone = phone.concat(ss);
}
}
if(count != 10)
{
phone = "0000000000";
}
}

Java Method is broken

I am trying to get it to return a compressed word. For example, reaction should be #act$. But it is getting returned as react$. I feel like my issue is not including the original word in the return statement. Can anyone help? Thanks!
public static String compress (String word) {
String newWord = "";
int the = word.indexOf("the");
if (the >= 0) {
newWord = word.substring(0,the) + "&" + word.substring(the+3);
}
int ion = newWord.indexOf("ion");
if (ion >= 0) {
newWord = newWord.substring(0,ion) + "$" + word.substring(ion+3);
}
int ing = newWord.indexOf("ing");
if (ing >= 0) {
newWord = newWord.substring(0,ing) + "~" + word.substring(ing+3);
}
int an = newWord.indexOf("an");
if (an >= 0) {
newWord = newWord.substring(0,an) + "#" + word.substring(an+2);
}
int re = newWord.indexOf("re");
if (re >= 0) {
newWord = newWord.substring(0,re) + "#" + word.substring(re+2);
}
int con = newWord.indexOf("con");
if (con >= 0) {
newWord = newWord.substring(0,con) + "%" + word.substring(con+3);
}
return newWord;
}
A compressed version also:
public static String compress(String word) {
word = word.replace("the", "&");
word = word.replace("ion", "$");
word = word.replace("ing", "~");
word = word.replace("an", "#");
word = word.replace("re","#");
word = word.replace("con","%");
return word;
}
You're mixing up your uses of newWord and word in a confusing way. If the first if clause doesn't fire, newWord will still be an empty string and none of the other conditions will fire. On the other hand, if newWord does get set to something, you still go on using word substrings, in ways that don't make any sense.
You would be better off just using one variable through the whole method.
public static String compress(String word) {
int the = word.indexOf("the");
if (the >= 0) {
word = word.substring(0,the) + "&" + word.substring(the+3);
}
int ion = word.indexOf("ion");
if (ion >= 0) {
word = word.substring(0,ion) + "$" + word.substring(ion+3);
}
int ing = word.indexOf("ing");
if (ing >= 0) {
word = word.substring(0,ing) + "~" + word.substring(ing+3);
}
int an = word.indexOf("an");
if (an >= 0) {
word = word.substring(0,an) + "#" + word.substring(an+2);
}
int re = word.indexOf("re");
if (re >= 0) {
word = word.substring(0,re) + "#" + word.substring(re+2);
}
int con = word.indexOf("con");
if (con >= 0) {
word = word.substring(0,con) + "%" + word.substring(con+3);
}
return word;
}
Note also that, written this way, you can only use each replacement once per word: if you have "thethe" you will compress it to "&the", not "&&". If you want use replacements multiple times, you would have to use a loop. Or, easier still, use String.replace.

Array wont work with small sentences

If I change the text to two words the program wont output anything. Not a clue on how to fix this, thanks in advance.
public class test {
public static void main(String args[]) {
String text = "The cat sat on the mat!"; //Change the string to "Hello there!"
int wordLengthCount [] = new int [20];
String wordCountText = "";
String sentence[] = text.split("[,\\-:\\?\\!\\ ]");
for (int i = 0; i < sentence.length; i++)
{
wordLengthCount[sentence[i].length()]++;
}
for(int wordLength=0; wordLength<sentence.length; wordLength++)
{
if (wordLengthCount[wordLength] != 0){
wordCountText += wordLengthCount[wordLength] + " with length of " + wordLength + "\n";
}
}
System.out.println(wordCountText);
}
}
You need to iterate over all wordLengthCount
Quick fix:
for (int wordLength = 0; wordLength < wordLengthCount.length; wordLength++) {
if (wordLengthCount[wordLength] != 0) {
wordCountText += wordLengthCount[wordLength] + " with length of " + wordLength + "\n";
}
}
Live demo

Counting Letters Between the First and Last - Java

OK, so I'm doing this project that requires that I have the first and last setters of a string appear with the number of letters in between them counted, and output. I've tried repurposing some reverse a string code I had handy, but I cannot get the output to appear in my IDE.
Can anyone look over my code, and make some suggestions?
public static void main(String[] args) {
String countWord;
countWord = JOptionPane.showInputDialog(null,
"Enter the string you wish to have formatted:");
}
static String countMe(String countWord) {
int count = 1;
char first = countWord.charAt (0);
char last = countWord.charAt(-1);
StringBuilder word = new StringBuilder();
for(int i = countWord.length() - 1; i >= 0; --i)
if (countWord.charAt(i) != first ) {
if (countWord.charAt(i) != last) {
count++;
}
}
return countWord + first + count + last;
}
}
Just build it using charAt():
return "" + str.charAt(0) + (str.length() - 2) + str.charAt(str.length() - 1);
The "" at the front causes the numeric values that follow to be concatenated as Strings (instead of added arithmetically).
A slightly more terse alternative is:
return countWord.replaceAll("(.).*(.)", "$1" + (str.length() - 2) + "$2")
Once you determined the first and last chars, it is no need for unnecessary conditions. Just try this:
static String countMe(String countWord) {
char first = countWord.charAt(0);
char last = countWord.charAt(countWord.length()-1);
int count=0;
for (int i = 1; i < countWord.length()-1; i++)
{
count++;
}
return first + String.valueOf(count) + last;
}
Or, if it is not mandatory to use for loop, you can make it simple as this
static String countMe(String countWord) {
char first = countWord.charAt(0);
char last = countWord.charAt(countWord.length()-1);
int count = countWord.substring(1, countWord.length()-1).length();
return first + String.valueOf(count) + last;
}
You could use the string.length() method to obtain the total length of the string. Your code would be something like:
int totalLength = countWord.length();
int betweenLength = totalLength - 2; // This gives the count of characters between first and last letters
char first = countWord.charAt(0);
char last = countWord.charAt(str.length() - 1);
String answer = first + betweenLength + last;
import javax.swing.JOptionPane;
public class Main{
public static void main(String[] args) {
String countWord;
countWord = JOptionPane.showInputDialog(null,
"Enter the word you wish to have formatted:");
JOptionPane.showMessageDialog(null, countMe(countWord));
}
static String countMe(String countWord) {
int count = 0;
String first = String.valueOf(countWord.charAt(0));
String last = String.valueOf(countWord.charAt(countWord.length() - 1));
for(int i = 1; i < countWord.length() - 1; i++) {
if (String.valueOf(countWord.charAt(i)) != first ) {
count++;
}
}
return first + count + last;
}
}

Categories