All words having the given length wordLength in the string sentence must be replaced with the word myWord. All parameters come from user input and may vary. I have tried this way but it only returns the initial string with the initial words.
Here is my source code:
package main;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
String sentence = "";
int wordLength = 0;
String myWord = "";
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader bis = new BufferedReader(is);
System.out.println("Text input: ");
sentence = bis.readLine();
System.out.println("Word lenth to replace");
wordLength = Integer.parseInt(bis.readLine());
System.out.println("Word to replace to");
myWord = bis.readLine();
Text myText = new Text(myWord, sentence, wordLength);
myText.changeSentence();
System.out.println("New string" + myText.getSentence());
}
}
class Text {
private String mySentence;
private int charNumber;
private String wordToChange;
private String newSentence = "1.";
public Text(String wordToChange, String mySentece, int charNumber) {
this.mySentence = mySentece;
this.wordToChange = wordToChange;
this.charNumber = charNumber;
}
public String getSentence() {
return newSentence;
}
public void changeSentence() {
int firstPos = 0;
int i;
for (i = 0; i < mySentence.length(); i++) {
if (mySentence.charAt(i) == ' ') {
if (i - firstPos == charNumber) {
newSentence = newSentence.concat(wordToChange + " ");
firstPos = i + 1;
} else {
newSentence = newSentence.concat(mySentence.substring(firstPos, i + 1));
firstPos = i + 1;
}
} else if (i == mySentence.length() - 1) {
if (i - firstPos == charNumber) {
newSentence = newSentence.concat(wordToChange + " ");
firstPos = i + 1;
} else {
newSentence = newSentence.concat(mySentence.substring(firstPos, i + 1));
firstPos = i + 1;
}
}
}
}
}
I changed your code a little bit:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
String sentence = "";
int wordLenght = 0;
String myWord = "";
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader bis = new BufferedReader(is);
try {
System.out.println("Text input: ");
sentence = bis.readLine();
System.out.println("Word lenth to replace");
wordLenght = Integer.parseInt(bis.readLine());
System.out.println("Word to replace to");
myWord = bis.readLine();
} catch (IOException e) {
e.printStackTrace();
}
Text myText = new Text(myWord, sentence, wordLenght);
System.out.println(myText.getChangeSentence());
}
}
class Text {
private String mySentence;
private int charNumber;
private String wordToChange;
private String newSentence = "1.";
public Text(String wordToChange, String mySentece, int charNumber) {
this.mySentence = mySentece;
this.wordToChange = wordToChange;
this.charNumber = charNumber;
}
public String getChangeSentence() {
String[] words = mySentence.split(" ");
for(int i = 0 ; i < words.length ; i++) {
if(words[i].length() == charNumber) {
words[i] = wordToChange;
}
}
for (String word : words) {
newSentence += word + " ";
}
return newSentence;
}
}
Input : This is a test
word length : 2
word to replace : ii
output: This ii a test
As I can see the only separator of words that is currently considered to appear in the input text is a single white space " ". If that's true, then the changeSentence method can be quite short. There is no need to do parse the sentence character by characted. Having in mind that the white space is a separator, you can simply split the sentence by the characted " " and collect them as words. After that you can just iterate through words and replace ones that lenght matches given input characters number. After that, you can just join words together with the previously used separator and that's it.
Examples if you want to try with loops
public void changeSentence() {
final String[] words = mySentence.split(" ");
for (int i = 0; i < words.length; i++) {
if (words[i].length() == charNumber) {
words[i] = wordToChange;
}
}
newSentence = String.join(" ", words);
}
or with regular expressions
public void changeSentence() {
String regex = "\\b\\w{" + charNumber+ "}\\b";
newSentence = mySentence.replaceAll(regex, wordToChange);
}
or with the stream API
public void changeSentence() {
newSentence = Arrays.stream(mySentence.split(" "))
.map(s -> s.length() == charNumber ? wordToChange : s)
.collect(Collectors.joining(" "));
}
Related
I created a class object array and but now when I try to print it using printf method then it doesn't print those values, I tried checking if the values are correct using println and it works fine with it. One more thing which was weird is that when I pass the end index of the array then it prints them. for example class object array is of size 20 (0-19), when I pass 19th index to the method which prints it then it is working but for 0-18 it is not working.
package com.insurance.company;
import java.util.List;
/**
*
* #author Lenovo
*/
public class InsuranceCompany {
private String companyName;
private String telephone;
private String webAddress;
private double brokerPercentage;
private String description;
private List<String> insuranceTypes;
public InsuranceCompany(){}
public InsuranceCompany(String companyName, String telephone, String webAddress, double brokerPercentage, String description, List<String> insuranceTypes) {
this.companyName = companyName;
this.telephone = telephone;
this.webAddress = webAddress;
this.brokerPercentage = brokerPercentage;
this.description = description;
this.insuranceTypes = insuranceTypes;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(companyName);
sb.append(" " + telephone);
sb.append(" " + webAddress);
for(int i = 0; i < insuranceTypes.size(); i++){
sb.append(" " + insuranceTypes.get(i));
}
sb.append(" " + brokerPercentage);
sb.append(" " + description);
return sb.toString();
}
public String getCompanyName() {
return companyName;
}
public String getTelephone() {
return telephone;
}
public String getWebAddress() {
return webAddress;
}
public double getBrokerPercentage() {
return brokerPercentage;
}
public String getDescription() {
return description;
}
public List<String> getInsuranceTypes() {
return insuranceTypes;
}
}
package com.insurance.company;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class InsurancePortal {
//function to load data from file
private static String loadDataFromFile(String path)throws Exception{
String data;
data = new String(Files.readAllBytes(Paths.get(path)));
return data;
}
//function to list all insurance companies
private static void listInuranceCompanies(InsuranceCompany[] company){
System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------");
System.out.printf("| %3s | %-20s | %-111s |%n", "ID", "Company Name", "Cover Types");
//System.out.flush();
System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------");
for(int j = 0; j < company.length; j++){
System.out.printf("| %3d | %-20s |", j+1, company[j].getCompanyName());
for(int i = 0; i < 7; i++){
if(i < company[j].getInsuranceTypes().size()){
System.out.printf(" %15S", company[j].getInsuranceTypes().get(i));
}else{
System.out.printf(" %15s", " ");
}
}
System.out.print(" |\n");
System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------");
}
}
//function to search cover
public static void listSingleCompanyDetails(InsuranceCompany selectedCompany){
System.out.println(selectedCompany.getCompanyName()+"\n--------------------------------------------------");
//System.out.flush();
System.out.printf("| %-18S | %-28S |%n", selectedCompany.getCompanyName(), selectedCompany.getDescription());
//System.out.flush();
System.out.println("--------------------------------------------------");
System.out.println("--------------------------------------------------");
System.out.println("--------------------------------------------------");
System.out.println("--------------------------------------------------");
System.out.println("--------------------------------------------------");
}
public static void main(String arge[]) throws Exception{
String dataFile = System.getProperty("user.dir") + File.separator + "insurance-data.txt";
String[] data = loadDataFromFile(dataFile).split("\n");
/*for(String str: data){
System.out.println(str);
}*/
int rows = data.length;
InsuranceCompany[] company = new InsuranceCompany[rows];
//Initialising objects for every row of data in the file
for(int j = 0; j < rows; j++){
String row = data[j];
//System.out.println(row);
String companyName, telephone, webAddress, description;
double brokerPercentage;
List<String> insuranceTypes = new ArrayList<>();
//Splitting for Company Name
String[] splittedArray = row.split(":", 2);
companyName = splittedArray[0];
row = splittedArray[1];
//Splitting for telephone
splittedArray = row.split(":", 2);
telephone = splittedArray[0];
row = splittedArray[1];
//splitting for web address
splittedArray = row.split(":", 2);
webAddress = splittedArray[0];
row = splittedArray[1];
//splitiing for insurance types
splittedArray = row.split(":", 2);
String[] insuranceTypeList = splittedArray[0].split(",");
for(String str : insuranceTypeList){
insuranceTypes.add(str);
}
row = splittedArray[1];
//splitting for broker percentage
splittedArray = row.split(":", 2);
brokerPercentage = Double.parseDouble(splittedArray[0]);
row = splittedArray[1];
//splitting for description
splittedArray = row.split(":", 2);
description = splittedArray[0];
//System.out.println(companyName+ " " + telephone + " " +webAddress + " " + brokerPercentage + " " + description);
/*for(int i = 0; i < insuranceTypes.size(); i++){
System.out.print(insuranceTypes.get(i)+" ");
}*/
company[j] = new InsuranceCompany(companyName, telephone, webAddress, brokerPercentage, description, insuranceTypes);
//System.out.println(company[j].getCompanyName());
}
boolean run = true;
while(run){
int choice;
Scanner sc = new Scanner(System.in);
System.out.print("\nList insurance companies.......1\n"
+ "Select insurance company.......2\n"
+ "Search cover...................3\n"
+ "Exit...........................0\n"
+ "\nEnter choice:> ");
choice = sc.nextInt();
switch(choice){
case 1 :
listInuranceCompanies(company);
break;
case 2 :
System.out.print("Enter company ID from list [1 - "+(company.length)+"] :> ");
int selectedCompany;
selectedCompany = sc.nextInt();
listSingleCompanyDetails(company[selectedCompany-1]);
break;
case 0 :
System.exit(0);
break;
default: System.out.println("Invalid choice!, please try again.");
}
}
}
}
I wrote a code for hangman, and i want to pass the randomly guessed word(randomly guessed from a text file), to be passed to a function hangman() where i can get the length of the word. a random word will be guessed from the getRandomWord(String path) function and I have passed value obtained to function() But cannot seem to pass the and get the result.
public class Main {
public static void main(String[] args) throws IOException {
Main ma = new Main();
String stm= null;
loadWords();
//hangman(w);
function();
}
public static String[] loadWords() {
System.out.println("Loading words from file :");
try {
File myObj = new File("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNext()) {
String data = myReader.nextLine().toLowerCase();
String[] spl = data.split(" ");
System.out.println(spl.length + " words loaded");
return spl;
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return null;
// TODO: Fill in your code here
}
public static String getRandomWord(String path) throws IOException {
List<String> words = new ArrayList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
String line;
while ((line = reader.readLine()) != null) {
String[] wordline = line.split("\\s+");
for (String word : wordline) {
words.add(word);
}
}
}
Random rand = new Random();
return words.get(rand.nextInt(words.size()));
}
public static List< String> getRemainingLetters(ArrayList< String> lettersGuessed) {
String alpha = "abcdefghijklmnopqrstuvwxyz";
String[] alpha1 = alpha.split("");
ArrayList< String> alpha2 = new ArrayList<>(Arrays.asList(alpha1));
for (int i = 0; i < lettersGuessed.size(); i++) {
for (int j = 0; j < alpha2.size(); j++) {
if (alpha2.get(j).equals(lettersGuessed.get(i))) {
alpha2.remove(j);
break;
}
}
}
return alpha2;
}
public static void function() throws IOException {
int numGuesses = 5;
String w = getRandomWord("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt");
String[] word = w.split("");
ArrayList< String> wList = new ArrayList<>(Arrays.asList(word));
ArrayList< String> wAnswer = new ArrayList< String>(wList.size());
for (int i = 0; i < wList.size(); i++) {
wAnswer.add("_ ");
}
int left = wList.size();
Scanner scanner = new Scanner(System.in);
boolean notDone = true;
ArrayList< String> lettersGuessed = new ArrayList< String>();
while (notDone) {
System.out.println();
String sOut = "";
List< String> lettersLeft = getRemainingLetters(lettersGuessed);
for (String s : lettersLeft) {
sOut += s + " ";
}
System.out.println("Letters Left: " + sOut);
sOut = "";
for (int i = 0; i < wList.size(); i++) {
sOut += wAnswer.get(i);
}
System.out.println(sOut + " Guesses left:" + numGuesses);
System.out.print("Enter a letter(* exit): ");
String sIn = scanner.next();
numGuesses--;
if (sIn.equals("*")) {
break;
}
lettersGuessed.add(sIn);
for (int i = 0; i < wList.size(); i++) {
if (sIn.equals(wList.get(i))) {
wAnswer.set(i, sIn);
left--;
}
}
if (left == 0) {
System.out.println("Congradulations you guessed it!");
break;
}
if (numGuesses == 0) {
StringBuilder sb = new StringBuilder();
for (String string : wList) {
sb.append(string);
}
String stm = sb.toString();
System.out.println("Sorry you ran out of guesses, the word was: " + stm);
break;
}
}
}
public static void hangman(String word) {
System.out.println("Welcome to Hangman Ultimate Edition");
System.out.println("I am thinking of a word that is " + word.length() + " letters long");
System.out.println("-------------");
}
}
Problems in your code:
Not passing the random word to the methods, hangman and function.
Instead of re-using the random word obtained from the method, getRandomWord in main, you have called getRandomWord again in the method, hangman which will give you a different random word causing incosistency.
Given below is the corrected program with a sample run:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
String word = getRandomWord("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt");
hangman(word);
function(word);
}
public static String getRandomWord(String path) throws IOException {
List<String> words = new ArrayList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
String line;
while ((line = reader.readLine()) != null) {
String[] wordline = line.split("\\s+");
for (String word : wordline) {
words.add(word);
}
}
}
Random rand = new Random();
return words.get(rand.nextInt(words.size()));
}
public static List<String> getRemainingLetters(ArrayList<String> lettersGuessed) {
String alpha = "abcdefghijklmnopqrstuvwxyz";
String[] alpha1 = alpha.split("");
ArrayList<String> alpha2 = new ArrayList<>(Arrays.asList(alpha1));
for (int i = 0; i < lettersGuessed.size(); i++) {
for (int j = 0; j < alpha2.size(); j++) {
if (alpha2.get(j).equals(lettersGuessed.get(i))) {
alpha2.remove(j);
break;
}
}
}
return alpha2;
}
public static void function(String w) throws IOException {
// The available number of guesses = length of the random word
int numGuesses = w.length();
// Split the random word into letters
String[] word = w.split("");
ArrayList<String> wList = new ArrayList<>(Arrays.asList(word));
ArrayList<String> wAnswer = new ArrayList<String>(wList.size());
for (int i = 0; i < wList.size(); i++) {
wAnswer.add("_ ");
}
int left = wList.size();
Scanner scanner = new Scanner(System.in);
boolean notDone = true;
ArrayList<String> lettersGuessed = new ArrayList<String>();
while (notDone) {
System.out.println();
String sOut = "";
List<String> lettersLeft = getRemainingLetters(lettersGuessed);
for (String s : lettersLeft) {
sOut += s + " ";
}
System.out.println("Letters Left: " + sOut);
sOut = "";
for (int i = 0; i < wList.size(); i++) {
sOut += wAnswer.get(i);
}
System.out.println(sOut + " Guesses left:" + numGuesses);
System.out.print("Enter a letter(* exit): ");
String sIn = scanner.next();
numGuesses--;
if (sIn.equals("*")) {
break;
}
lettersGuessed.add(sIn);
for (int i = 0; i < wList.size(); i++) {
if (sIn.equals(wList.get(i))) {
wAnswer.set(i, sIn);
left--;
}
}
if (left == 0) {
System.out.println("Congradulations you guessed it!");
break;
}
if (numGuesses == 0) {
StringBuilder sb = new StringBuilder();
for (String string : wList) {
sb.append(string);
}
String stm = sb.toString();
System.out.println("Sorry you ran out of guesses, the word was: " + stm);
break;
}
}
}
public static void hangman(String word) {
System.out.println("Welcome to Hangman Ultimate Edition");
System.out.println("I am thinking of a word that is " + word.length() + " letters long");
System.out.println("-------------");
}
}
A sample run:
Welcome to Hangman Ultimate Edition
I am thinking of a word that is 3 letters long
-------------
Letters Left: a b c d e f g h i j k l m n o p q r s t u v w x y z
_ _ _ Guesses left:3
Enter a letter(* exit): c
Letters Left: a b d e f g h i j k l m n o p q r s t u v w x y z
_ _ _ Guesses left:2
Enter a letter(* exit): a
Letters Left: b d e f g h i j k l m n o p q r s t u v w x y z
_ _ _ Guesses left:1
Enter a letter(* exit): t
Sorry you ran out of guesses, the word was: fox
To make your existing code run, you should just clean up the main method:
remove unused code:
Main ma = new Main(); // no need to create an instance, you use only static methods
String stm= null; // not used anywhere
loadWords(); // not used, entire method may be removed:
// it reads words only in the first line
fix method function to have a String w parameter, move getting the random word out of this method.
Thus, resulting changes should be:
public static void main(String[] args) throws IOException {
String word = getRandomWord("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt");
hangman(word);
function(word);
}
public static void function(String w) throws IOException {
int numGuesses = 5;
String[] word = w.split("");
// ... the rest of this method remains as is
}
I'm looking for some help. What is the easiest way to concatenate multiline strings in Java and print it after ?
For example : I've got two strings :
String turtle1 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r";
String turtle2 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r";
And I want to get this result in the Java Eclipse console :
_ _
.-./*) .-./*)
_/___\/ _/___\/
U U U U
I've already try some algorithms to divide my strings in differents parts and after re-concatenate it. But it was without success.
I know there are StringBuffer class and StringBuilder class but after some research, I didn't found something that correspond to my need.
Thanks in advance for your help.
See my example below, should be self explaining.
public class Turtle {
private static final String returnpattern = "\r\n";
public static void main(String[] args) {
// the data to run through
String turtle1 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r\n";
String turtle2 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r\n";
// split the data into individual parts
String[] one = turtle1.split(returnpattern);
String[] two = turtle2.split(returnpattern);
// find out the longest String in data set one
int longestString = 0;
for (String s : one) {
if (longestString < s.length()) {
longestString = s.length();
}
}
// loop through parts and build new string
StringBuilder b = new StringBuilder();
for (int i = 0; i < one.length; i++) {
String stringTwo = String.format("%1$" + longestString + "s", two[i]); // left pad the dataset two to match
// length
b.append(one[i]).append(stringTwo).append(returnpattern);
}
// output
System.out.println(b);
}
}
Just for fun, here is another solution using streams, prepared for more than two turtles to be shown side-by-side:
public static void main(String[] args) {
String turtle1 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r";
String turtle2 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r";
// split lines into fragments
List<List<String>> fragments = Stream.of(turtle1, turtle2)
.map(x -> Stream.of(x.split("\\r\\n?|\\n")).collect(Collectors.toList()))
.collect(Collectors.toList());
// make all lists same length by adding empty lines as needed
int lines = fragments.stream().mapToInt(List::size).max().orElse(0);
fragments.forEach(x -> x.addAll(Collections.nCopies(lines - x.size(), "")));
// pad all fragments to maximum width (per list)
List<List<String>> padded = fragments.stream().map(x -> {
int width = x.stream().mapToInt(String::length).max().orElse(0);
return x.stream().map(y -> String.format("%-" + width + "s", y)).collect(Collectors.toList());
}).collect(Collectors.toList());
// join corresponding fragments to result lines, and join result lines
String result = IntStream.range(0, lines)
.mapToObj(i -> padded.stream().map(x -> x.get(i)).collect(Collectors.joining()))
.collect(Collectors.joining(System.lineSeparator()));
System.out.println(result);
}
Not so pretty but works:
String turtle1 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r\n";
String turtle2 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r\n";
String[] turtle1Lines = turtle1.split("\r\n");
String[] turtle2Lines = turtle2.split("\r\n");
StringBuilder sb = new StringBuilder();
int turtle1Width = 0;
for (int i = 0; i < 4; i++) {
if (turtle1Lines[i].length() > turtle1Width) {
turtle1Width = turtle1Lines[i].length();
}
}
for (int i = 0; i < 4; i++) {
sb.append(turtle1Lines[i]);
for (int j = turtle1Width - turtle1Lines[i].length(); j > 0; j--) {
sb.append(' ');
}
sb.append(turtle2Lines[i]);
sb.append("\r\n");
}
String turtles = sb.toString();
I'm here too ;)
public class Test {
static String turtle1 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r".replace("\r", "");
static String turtle2 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r".replace("\r", "");
public static int countRows(String string){
return string.length() - string.replace("\n", "").length() + 1;
}
public static int getMaxLength(String string){
int maxLength = 0;
int currentLength = 0;
char[] data = string.toCharArray();
for(Character c : data){
if(c != '\n'){
if(++currentLength > maxLength) {
maxLength = currentLength;
}
}else{
currentLength = 0;
}
}
return maxLength;
}
public static String[] toStringArray(String string){
int length = getMaxLength(string);
int rows = countRows(string);
String[] result = new String[rows];
int last = 0;
for(int i = 0; i < rows; i++){
int temp = string.indexOf("\n", last);
String str;
if(temp != -1) {
str = string.substring(last, temp);
}else{
str = string.substring(last);
}
while(str.length() < length){
str += " ";
}
result[i] = str;
last = temp + 1;
}
return result;
}
public static String concatMultilineStrings(String first, String second){
StringBuilder sb = new StringBuilder();
String[] arrayFirst = toStringArray(first);
String[] arraySecond = toStringArray(second);
if(arrayFirst.length != arraySecond.length){
System.exit(69);
}
for(int i = 0; i < arrayFirst.length; i++){
sb.append(arrayFirst[i]);
sb.append(arraySecond[i]);
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(concatMultilineStrings(turtle1, turtle2));
}
}
I want to split string only inside the first braces. How can I do it in java
Input String 1: text2(text3, text4), text5(text6, text7)
String1: text2(text3, text4)
String2: text5(text6, text7)
Input String 2: text2, text3(text4, text5(text6, text7, text8))
String1: text2
String2: text3(text4, text5(text6, text7, text8))
Input String can have arbitrary number of levels. Please assume that the input string has matching braces.
Thanks in advance
package ic.ac.uk.relationshipvisualiser.app;
import java.util.ArrayList;
import java.util.List;
public class tmpTest3 {
public static List<String> process(String p_inp) {
List<String> res = new ArrayList<String>();
p_inp = p_inp.trim();
int numberOfOpenBracketsEncountered = 0;
String t = "";
String cur = "";
for (int c=0;c<p_inp.length();c++) {
cur = p_inp.substring(c,c+1);
if (cur.equals("(")) {
numberOfOpenBracketsEncountered++;
}
if (cur.equals(")")) {
numberOfOpenBracketsEncountered--;
}
if (cur.equals(",")) {
if (numberOfOpenBracketsEncountered==0) {
if (t.length()>0) res.add(t.trim());
t = "";
} else {
cur = cur;
t = t + cur;
}
} else {
cur = cur;
t = t + cur;
}
}
if (t.length()>0) res.add(t.trim());
return res;
}
public static void main(String[] args) {
System.out.println("Start tmpTest3");
List<String> inputs = new ArrayList<String>();
inputs.add("text2(text3, text4), text5(text6, text7)");
inputs.add("text2, text3(text4, text5(text6, text7))");
for (int c=0;c<inputs.size();c++) {
System.out.println("Running test for " + inputs.get(c));
List<String> res = process(inputs.get(c));
System.out.println("Got " + res.size() + " strings as a result:");
for (int d=0;d<res.size();d++) {
System.out.println(" - :" + res.get(d) + ":");
}
System.out.println("----------------------");
}
System.out.println("End tmpTest3");
}
}
Will This works for you ..?
import java.util.Arrays;
class Program {
public static void main (String[] args) throws java.lang.Exception {
String subject1 = "text2(text3, text4), text5(text6, text7)";
String subject2 = "text2, text3(text4, text5(text6, text7))";
String p = "\\s*\\d*\\(\\)";
String[] res = subject1.split(p);
System.out.println(Arrays.toString(res));
res=subject2.split(p);
System.out.println(Arrays.toString(res));
} // end main
} // end
Out put :-
[text2(text3, text4), text5(text6, text7)]
[text2, text3(text4, text5(text6, text7))]
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Not sure why it gives me the NullPointerException. Please help.
I am pretty sure all the arrays are full, and i restricted all the loops not to go passed empty spaces.
import java.util.;
import java.io.;
public class TextAnalysis {
public static void main (String [] args) throws IOException {
String fileName = args[0];
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
int MAX_WORDS = 10000;
String[] words = new String[MAX_WORDS];
int unique = 0;
System.out.println("TEXT FILE STATISTICS");
System.out.println("--------------------");
System.out.println("Length of the longest word: " + longestWord(fileScanner));
read(words, fileName);
System.out.println("Number of words in file wordlist: " + wordList(words));
System.out.println("Number of words in file: " + countWords(fileName) + "\n");
System.out.println("Word-frequency statistics");
lengthFrequency(words);
System.out.println();
System.out.println("Wordlist dump:");
wordFrequency(words,fileName);
}
public static void wordFrequency(String[] words, String fileName) throws IOException{
File file = new File(fileName);
Scanner s = new Scanner(file);
int [] array = new int [words.length];
while(s.hasNext()) {
String w = s.next();
if(w!=null){
for(int i = 0; i < words.length; i++){
if(w.equals(words[i])){
array[i]++;
}
}
for(int i = 0; i < words.length; i++){
System.out.println(words[i] + ":" + array[i]);
}
}
}
}
public static void lengthFrequency (String [] words) {
int [] lengthTimes = new int[10];
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(w!=null){
if(w.length() >= 10) {
lengthTimes[9]++;
} else {
lengthTimes[w.length()-1]++;
}
}
}
for(int j = 0; j < 10; j++) {
System.out.println("Word-length " + (j+1) + ": " + lengthTimes[j]);
}
}
public static String longestWord (Scanner s) {
String longest = "";
while (s.hasNext()) {
String word = s.next();
if (word.length() > longest.length()) {
longest = word;
}
}
return (longest.length() + " " + "(\"" + longest + "\")");
}
public static int countWords (String fileName) throws IOException {
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
int count = 0;
while(fileScanner.hasNext()) {
String word = fileScanner.next();
count++;
}
return count;
}
public static void read(String[] words, String fileName) throws IOException{
File file = new File(fileName);
Scanner s = new Scanner(file);
while (s.hasNext()) {
String word = s.next();
int i;
for ( i=0; i < words.length && words[i] != null; i++ ) {
words[i]=words[i].toLowerCase();
if (words[i].equals(word)) {
break;
}
}
words[i] = word;
}
}
public static int wordList(String[] words) {
int count = 0;
while (words[count] != null) {
count++;
}
return count;
}
}
There are two problems with this code
1.You didn't do null check,although the array contains null values
2.Your array index from 0-8,if you wan't to get element at 9th index it will throw ArrayIndexOutOfBound Exception.
Your code should be like that
public static void lengthFrequency (String [] words) {
int [] lengthTimes = new int [9];
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(null!=w) //This one added for null check
{
/* if(w.length() >= 10) {
lengthTimes[9]++;
} else {
lengthTimes[w.length()-1]++;
}
}*/
//Don't need to check like that ...u can do like below
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(null!=w)
{
lengthTimes[i] =w.length();
}
}
}
//here we should traverse upto length of the array.
for(int i = 0; i < lengthTimes.length; i++) {
System.out.println("Word-length " + (i+1) + ": " + lengthTimes[i]);
}
}
Your String Array String[] words = new String[MAX_WORDS]; is not initialized,you are just declaring it.All its content is null,calling length method in line 31 will give you null pointer exception.
`
Simple mistake. When you declare an array, it is from size 0 to n-1. This array only has indexes from 0 to 8.
int [] lengthTimes = new int [9];
//some code here
lengthTimes[9]++; // <- this is an error (this is line 29)
for(int i = 0; i < 10; i++) {
System.out.println("Word-length " + (i+1) + ": " + lengthTimes[i]); // <- same error when i is 9. This is line 37
When you declare:
String[] words = new String[MAX_WORDS];
You're creating an array with MAX_WORDS of nulls, if your input file don't fill them all, you'll get a NullPointerException at what I think is line 37 in your original file:
if(w.length() >= 10) { // if w is null this would throw Npe
To fix it you may use a List instead:
List<String> words = new ArrayList<String>();
...
words.add( aWord );
Or perhaps you can use a Set if you don't want to have repeated words.