Java .split() not working - java

I am trying to split a line from a text file. The text file is being imported from an inventory system and I don't know how to make it formatted with a tabular format. I can't tell you what is in the file but I will explain what I'm talking about. Confidentiality...
Line 1:
name order sorder assemblyID desc date
123 123 123 1-2-3 123-456-789 12-3 1\2\3
Line 2:
123 123 123 1-2-3 123-456-789 12 3 1\2\3
If you can see... The description column has a space in it. Which means it will allocate that into separate part of my array. First array is of size 7 but the second array will be 8. Here is what I have.
public static void main(String[] args) throws IOException, ParseException {
ArrayList < CustordData > list = new ArrayList < CustordData > ();
CustordData cd = new CustordData();
int[] array = new int[10];
DateFormat format = new SimpleDateFormat("MM/dd/Y");
try {
String read = null;
BufferedReader in = new BufferedReader(new FileReader("Custord.txt"));
while ((read = in .readLine()) != null) {
String[] splited = read.split("\\s+");
cd.setCustName(splited[0]);
cd.setPurchaseOrder(splited[1]);
cd.setSalesOrder(splited[2]);
cd.setAssemblyID(splited[4]);
cd.setOrderDesc(splited[5]);
cd.setKitDate(format.parse(splited[6]));
}
for (CustordData d: list) {
System.out.println(d.getCustName() + d.getPurchaseOrder() + d.getSalesOrder() + d.getAssemblyID() + d.getOrderDesc() + d.getKitDate() + d.getShipDate() + d.getPricePer() + d.getTotal());
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
}

If you are certain that only one column will have extra spaces, and that it will be always the same column, you could still use split but you would do something like so:
Let N be the index of the description column,
Assign columns [1, N-1] to the data you need
Assign columns [N, TotalColumns - 1] to description
Assign column TotalColumns to date
Something like so:
public static void main(String[] args) {
String noSpaces = "123 123 123 1-2-3 123-456-789 12-3 1\\2\\3";
String withSpaces = "123 123 123 1-2-3 123-456-789 12 3 1\\2\\3";
String[] splitNoSpaces = noSpaces.split("\\s+");
printData(splitNoSpaces);
String[] splitWithSpaces = withSpaces.split("\\s+");
printData(splitWithSpaces);
}
private static void printData(String[] data)
{
int totalColumns = data.length;
System.out.println("Name: " + data[0]);
System.out.println("Order: " + data[1]);
System.out.println("SOrder: " + data[2]);
System.out.println("AssemblyID: " + data[3]);
System.out.print("Description: ");
for(int i = 4; i < totalColumns - 2; i++)
{
System.out.print(data[i] + " ");
}
System.out.println();
System.out.println("AssemblyID: " + data[totalColumns - 1]);
}
Yields:
Name: 123
Order: 123
SOrder: 123
AssemblyID: 1-2-3
Description: 123-456-789
AssemblyID: 1\2\3
Name: 123
Order: 123
SOrder: 123
AssemblyID: 1-2-3
Description: 123-456-789 12
AssemblyID: 1\2\3

If you know that only problem is in description then test lenght of array. Then join array from index 5 to array lenght - 1.
KitDate will be last field of array.

Related

How to collect names in a loop then use StringBuilder?

Have been up for hours trying to figure out how to add in these in a string array using user input and StringBuilder.
I have to in a loop collect names from user input (scanner).
when they enter a blank name stop looping. Then iterate over the attendee list to create the output string using StringBuilder.
only 1 name = Name .
2 names = Name 1 and name 2 . more then 2 names = name 1, name2, and name 3 . output should exactly match the way these are formatted with spaces, commas, and the "and".
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
sb.append("You have invited: ");
System.out.println("enter names.");
String attendee = keyboard.nextLine();
// receiving input
while (attendee != "") {
sb.append(attendee);
if (attendee == "") break;
}
System.out.println(sb);
for (int i = 0; i > sb.length(); i++) {
if (i == 0) {
keyboard.nextLine(); //consuming the <enter> from input above
sb.append(keyboard.nextLine());
i++;
} else if (i == 1) {
sb.append(keyboard.nextLine() + " and " + keyboard.nextLine());
System.out.println(sb);
} else if (i > 1) {
sb.append(keyboard.nextLine() + ", " + keyboard.nextLine() + ", and " + keyboard.nextLine());
System.out.println(sb);
}
}
}
There is a lot of errors in your code
you don't ask again in the while loop for a new value, so either you never get in (first empty string) or never get out (first not empty) also that isn't how you compare a string, that is an object, use .equals()
you may not call keyboard.nextLine() (getting input) in the loop where you build the output
names shouldn't be joined in the StringBuilder, then how would you build the output
So, make a nice loop that populates a list of String, then nicely concatenate the different parts to make the output
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
List<String> names = new ArrayList<>();
System.out.print("enter name: ");
String attendee = keyboard.nextLine();
while (!attendee.equals("")) {
names.add(attendee);
System.out.print("enter name: ");
attendee = keyboard.nextLine();
}
System.out.println(namesToString(names));
}
static String namesToString(List<String> names) {
List<String> firsts = names.subList(0, names.size() - 1);
String last = names.get(names.size() - 1);
if (names.size() == 1)
return "You have invited: " + last;
return "You have invited: " + String.join(", ", firsts) + " and " + last;
}
enter name: Patrick
enter name: Pierre
enter name: James
enter name: John
enter name:
You have invited: Patrick, Pierre, James and John
Full possibilities of outputs
System.out.println(namesToString(Arrays.asList("pierre")));
// You have invited: pierre
System.out.println(namesToString(Arrays.asList("pierre", "jean")));
// You have invited: pierre and jean
System.out.println(namesToString(Arrays.asList("pierre", "jean", "eude")));
// You have invited: pierre, jean and eude
System.out.println(namesToString(Arrays.asList("pierre", "jean", "eude", "john", "james")));
// You have invited: pierre, jean, eude, john and james

Replace all strings in array that contain minus character with another string

I ask the user to insert numbers in the console.
Then, I print those numbers but if any number contains "-", it will be converted in the same number inside parentheses..
For example: if user inserts 5 -17 35 -8 ,the output will be 5 (-17) 35 (-8)
The code I have tried:
public class Run {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter numbers");
String s = input.nextLine();
String[] split = s.split(" ");
for (int i = 0; i < split.length; i++) {
if (split[i].contains("-")) {
split[i].replace(split[i], "(" + split[i] + ")");
}
}
input.close();
System.out.println(Arrays.toString(split));
}
}
But it does not work as it prints numbers exactly as the user inputs them..
For instance, 5 -17 35 -8 and not 5 (-17) 35 (-8)..
I'm new in Java so that's why I can't understand what's wrong..
You are replacing the - with your desired format but then you are not storing it back in the split array.
You have to replace the following code snippet:
if (split[i].contains("-")) {
split[i].replace(split[i], "(" + split[i] + ")");
}
Here is the corrected code snippet:
if (split[i].contains("-")) {
/* Change Here */
split[i] = split[i].replace(split[i], "(" + split[i] + ")");
}
You don't do anything with the replaced string.
Simply calling this method won't replace the string directly, it returns a new string, which you simply ignore.
split[i].replace
So you have to do
spilt[i] = split[i].replace
The method replace(...) does not change the String you work on, but creates a new String with the replaced values.
You have to assign the result of split[i].replace(split[i], "(" + split[i] + ")"); back to split[i].

I have a file with 3 columns and 7 rows, I need to make 3 arrays out of each column in the file

I have been trying to figure this out for days and I feel that I am just stuck on something that is so easy from over thinking it. I need to read the file, (contents of what text file looks like are right below)... create 3 arrays out of each column.
My issue is when splitting the String under " " conditions into a String [] Array, takes the last row of my txt and puts that into the new String [] Array, not the entire contents of string that i made from file...
my txt file looks like this...
200 1000 800
450 845 1200
800 250 400
0 1500 1800
600 500 1000
700 1400 1700
675 400 900
my code so far after days of manipulation, deletion, starting over from scratch...all to come to this small piece.
PLEASE HELP ME!!!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class WeeklyCalorieCount {
public static void main(String[] args) {
try {
File input = new File("Lab1File.txt"); //reads file and names it input to refer back later
Scanner klg = new Scanner(input); //creates scanner that reads the file named input
String [] b = new String [7]; //creating breakfast, lunch and dinner Strings (To Split later)
String [] l = new String [7];
String [] d = new String [7];
String fileLine = null;
System.out.println("TEST 1: Contents of file are as follows: ");
while (klg.hasNextInt()) { //Puts file contents into string
fileLine = klg.nextLine();
System.out.println(fileLine);
}
System.out.println("");
System.out.println("TEST 2 BELOW");
String strArr[] = fileLine.split(" "); //temporary array to hold all numbers and split
for(int i = 0; i < strArr.length; i++){ //Trying to split String into individual elements and put into string array.
System.out.print(strArr[i] + " ");
}
System.out.println("");
System.out.println("--------");
for(int k = 0; k < strArr.length;k++) {
b[k] = strArr[k]; //Assigns contents into 3 arrays
l[k] = strArr[k];
d[k] = strArr[k];
System.out.println(b[k]);
System.out.println(l[k]);
System.out.println(d[k]);
}
OUTPUT:
TEST 1: Contents of file are as follows:
200 1000 800
450 845 1200
800 250 400
0 1500 1800
600 500 1000
700 1400 1700
675 400 900
TEST 2 BELOW
675 400 900
--------
675
675
400
400
900
900
Use a 3x7 matrix and two for loops, saving each int value separately:
File input = new File("Lab1File.txt");
Scanner scanner = new Scanner(input);
int[][] matrix = new int[7][3];
for(int i = 0; i < 7; i++)
{
for(int j = 0; j < 3; j++)
{
matrix[i][j] = scanner.nextInt();
}
}
scanner.close();
After the while loop finishes which has fileLine = klg.nextLine();, fileLine will have only the last line. You are not concatenating the strings.
You are replacing fileLine with the line that you read every time. So you only have the last line after the loop.
You probably need to do:
fileLine = fileLine + " " + klg.nextLine();
instead of:
fileLine = klg.nextLine();
Edit:
You need to initialize String fileLine = ""; with this approach.
Your problems are in :
fileLine = klg.nextLine(); fileLine will have only one line
for(int k = 0; k < strArr.length;k++)
Better you move the code in for loop to the while (klg.hasNextInt()):
int k = 0;
while (klg.hasNextInt()) {
fileLine = klg.nextLine();
System.out.println(fileLine);
String strArr[] = fileLine.split(" ");
b[k] = strArr[0];
l[k] = strArr[1];
d[k] = strArr[2];
k++;
}
Or you can do it the way you initially planned as shown in the runnable below:
package weeklycaloriecount;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class WeeklyCalorieCount {
public static void main(String[] args) {
// Declare and initialize string variables to hold
// the values from each column of each file line as
// they are read in.
String colA = "";
String colB = "";
String colC = "";
try {
File input = new File("Lab1File.txt");
Scanner klg = new Scanner(input);
// Read each line of file until the end.
while (klg.hasNextInt()) {
// Place the line read into a String Array
String[] fileLine = klg.nextLine().split(" ");
// Take each element of the array and place them into
// their respective column variable and delimit them
// with a whitespace...
colA+= fileLine[0] + " ";
colB+= fileLine[1] + " ";
colC+= fileLine[2] + " ";
}
klg.close(); // Close the scanner.
}
catch(FileNotFoundException ex) {
// Trap the File Not Found Exception
System.out.println("Whoops! File Not Found!");
}
// Display each String variable...
System.out.println("The colA Variable: " + colA);
System.out.println("The colB Variable: " + colB);
System.out.println("The colC Variable: " + colC);
// You can at this point use each variable (colA, colB, and colC)
// as your separated columns or you can place the contents of each
// variable and place them into individual arrays as done below...
String[] b = colA.trim().split(" ");
String[] l = colB.trim().split(" ");
String[] d = colC.trim().split(" ");
// Display our Arrays (b[], l[], and d[])
// Breakfast...
System.out.println("");
System.out.println("The b[] Array: " + Arrays.toString(b));
// Lunch...
System.out.println("The l[] Array: " + Arrays.toString(l));
// Dinner...
System.out.println("The d[] Array: " + Arrays.toString(d));
}
}

Word count from text

This is my code to work out the length of a word:
public class WordCount {
public static void main (String args []) {
String text;
text = "Java";
System.out.println (text);
//Work out the length
String [] input = text.split(" ");
int MaxWordLength = 0;
int WordLength = 0;
for (int i = 0; i < input.length; i++)
{
MaxWordLength = input[i].length();
WordLength = MaxWordLength;
} //End of working out length
//Work out no. of words
int[] intWordCount = new int[WordLength + 1];
for(int i = 0; i < input.length; i++) {
intWordCount[input[i].length()]++; }
for (int i = 1; i < intWordCount.length; i++) {
System.out.println("There are " + intWordCount[i] + " words of length " + MaxWordLength);
}
}
}
The problem I am having is that when it prints out the length of the word, I get these results:
Java
There are 0 words of length 4
There are 0 words of length 4
There are 0 words of length 4
There are 1 words of length 4
But when I change the text to "J" this prints out:
J
There are 1 words of length 1
Any idea why it's doing that?
P.S. I'm kind of new to Java and any help would be appreciated.
I am not sure if you want to count letter or word because your code counts letter to me.
Just you need to change this line from
String [] input = text.split(" ");
to
String [] input = text.split("");
and your program works perfectly.
input: Java
output: There are 4 letters of length 1 <- Hope this is the expected result for you
Source: Splitting words into letters in Java
You can achieve this in better and less headache by using Lambda in Java
Code:
import java.util.*;
public class LambdaTest
{
public static void main (String[] args)
{
String[] st = "Hello".split("");
Collection myList = Arrays.asList(st);
System.out.println("your word has " + myList.stream().count() + "letters");
}
}
Output:
your word has 5 letters CLEARLY in length 1
My answer when you cleared what your issue is
Code:
public class WordCount
{
public static void main (String[] args)
{
String text ="";
int wordLenght = 0;
text = "Java is awesome for Me";
System.out.println (text);
String [] input = text.split(" ");
List<Integer> list = new ArrayList<>();
for (int i = 0; i < input.length; i++)
{
list.add(input[i].length());
}
Set<Integer> unique = new HashSet<Integer>(list);
for (Integer length : unique) {
System.out.println("There are " + Collections.frequency(list, length) + " words of length " + length);
}
}
}
output:
There are 2 words of length 2
There are 1 words of length 3
There are 1 words of length 4
There are 1 words of length 7
Note: Read about HashSet and Set in Java
Source: http://javarevisited.blogspot.com/2012/06/hashset-in-java-10-examples-programs.html
Let's walk through this:
public class WordCount {
public static void main (String args []) {
String text;
text = "Java";
text is equal to "Java".
System.out.println (text);
Prints "Java"
//Work out the length
String [] input = text.split(" ");
This splits the string "Java" on spaces, of which there are none. So input (which I'd recommend be renamed to something more indicative, like inputs) is equal to an array of one element, and that one element is equal to "Java".
int MaxWordLength = 0;
int WordLength = 0;
for (int i = 0; i < input.length; i++)
{
MaxWordLength = input[i].length();
For each element, of which there is only one, MaxWordLength is set to the length of the first (and only) element, which is "Java"...whose length is 4.
WordLength = MaxWordLength;
So WordLength is now equal to 4.
} //End of working out length
//Work out no. of words
int[] intWordCount = new int[WordLength + 1];
This creates an int array of [WordLength + 1] elements (which is equal to [4 + 1], or 5), where each is initialized to zero.
for(int i = 0; i < input.length; i++) {
intWordCount[input[i].length()]++; }
For each element in input, of which there is only one, this sets the input[i].length()-th element--the fifth, since input[i] is "Java" and it's length is four--to itself, plus one (because of the ++).
Therefore, after this for loop, the array is now equal to [0, 0, 0, 0, 1].
for (int i = 1; i < intWordCount.length; i++) {
System.out.println("There are " + intWordCount[i] + " words of length " + MaxWordLength);
So this naturally prints the undesired output.
}
}
}
Your output is different when the input is only "J", because the intWordCount array is shortened to input[i].length() elements, which is now 1. But the value of the last element is still set to "itself plus one", and "itself" is initialized to zero (as all int-array elements are), and then incremented by one (with ++).
for (int i = 1; i < intWordCount.length; i++) {
System.out.println("There are " + intWordCount[i] + " words of length " + MaxWordLength);
}
1) You print out words with intWordCount[i] == 0, which is why you have the "There are 0 words of length X"
2) System.out.println("There are " ... + MaxWordLength); should probably be System.out.println("There are " ... + i);, so you have "There are 0 words of length 1" , "There are 0 words of length 2", etc
I know this question has been solved long time ago, but here is another solution using new features of Java 8. Using Java streams the whole exercise can be written in one line:
Arrays.asList(new String[]{"Java my love"}) //start with a list containing 1 string item
.stream() //start the stream
.flatMap(x -> Stream.of(x.split(" "))) //split the string into words
.map((String x) -> x.length()) //compute the length of each word
.sorted((Integer x, Integer y) -> x-y) //sort words length (not necessary)
.collect(Collectors.groupingBy(x -> x, Collectors.counting())) //this is tricky: collect results to a map: word length -> count
.forEach((x,y) -> {System.out.println("There are " + y + " word(s) with " + x + " letter(s)");}); //now print each result
Probably in few year time this would be a preferred method for solving such problems. Anyway it is worth knowing that such alternative exists.
To count words in text with we used Pattern class with while loop:
I. Case Sensitive word counts
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CountWordsInText {
public static void main(String[] args) {
String paragraph = "I am at office right now."
+ "I love to work at office."
+ "My Office located at center of kathmandu valley";
String searchWord = "office";
Pattern pattern = Pattern.compile(searchWord);
Matcher matcher = pattern.matcher(paragraph);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println(count);
}
}
II. Case Insensitive word counts
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CountWordsInTextCaseInsensitive {
public static void main(String[] args) {
String paragraph = "I am at office right now."
+ "I love to work at oFFicE."
+"My OFFICE located at center of kathmandu valley";
String searchWord = "office";
Pattern pattern = Pattern.compile(searchWord, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(paragraph);
int count = 0;
while (matcher.find())
count++;
System.out.println(count);
}
}
Idk, but using the length method as much as you have to figure out how the length mechanism works is like defining a word using the word. It's an honorable conquest figuring out how the length method works, but you should probably avoid using the length method.

Java servlet, reading from file, array out of Bound

I'm making a java servlet, and my task is to get the sum cost of products written in file:
category1 1 10 101 1 good1
category6 2 11 105 2 good5
category1 5 13 103 3 good4
category3 6 14 102 4 good2
category5 3 12 107 2 good1
The cost is in column 4. I have written:
public int Sum_of_Elements()throws IOException{
int sum = 0;
BufferedReader br = new BufferedReader(new FileReader("/Data.txt"));
String line = "";
while((line=br.readLine())!=null){
String[] columns = line.split(" ");
sum = sum + Integer.parseInt(columns[4]);
}
System.out.println(sum);
return sum;
}
And it doesn't work. When i go to servlet page I get
java.lang.ArrayIndexOutOfBoundsException: 4
What's wrong ? and how to fix it ?
This code will fail if there is e.g. an empty line in the file, or a line formatted differently, or if the spaces are actually tabs (maybe there are more reasons). If you want to program defensively, you should do:
while((line=br.readLine())!=null) {
String[] columns = line.split(" ");
if( columns != null && columns.length >= 5 ) {
sum = sum + Integer.parseInt(columns[4]);
}
else {
// do what you must here; it may be an error to encounter such a line:
throw new IllegalArgumentException("malformatted line: " + line);
// or it may be OK to swallow the exceptional case
// or you may only need to silently log it:
logger.warn("malformatted line: " + line);
// etc...
}
}
I ran your code as following and it was fine. make sure that your Data file is ASCII
import java.io.*;
public class Test{
public static void main(String[] args){
try{
int sum = 0;
BufferedReader br = new BufferedReader(new FileReader("Data.txt"));
String line = "";
while((line=br.readLine())!=null){
String[] columns = line.split(" ");
sum = sum + Integer.parseInt(columns[4]);
}
System.out.println("Sun:" + sum);
}catch(Exception e){
System.out.println("error:" + e.getMessage());
}
}
}
There is no index 4 in your columns array. Check your length of columns array. It will be lesser than 5, ArrayIndexOutOfBoundException is thrown when an illegal index of the array is accessed. Check the array length like this
if( columns != null && columns.length >= 5 )
sum = sum + Integer.parseInt(columns[4]);

Categories