I want to print a formatted array in java - java

I haven't been able to find any questions similar to my situation so I hope I'm not missing something.
I have an array of strings. I want to print every 3 strings on their own line with commas and spacing.
Here is my method:
public static void Modify(String stringSearch)
{
ArrayList<String> records = new ArrayList<String>();
try {
File file = new File("Temp.txt");
input = new Scanner(file);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
if (input.hasNext()) {
while (input.hasNext())
{
String firstName = input.next();
String lastName = input.next();
String phoneNumber = input.next();
if ((Objects.equals(firstName, stringSearch)) || (Objects.equals(lastName, stringSearch)) || (Objects.equals(phoneNumber, stringSearch))) {
records.add(firstName);
records.add(lastName);
records.add(phoneNumber);
}
} // end while
}
int size;
size = (records.size()) / 3;
System.out.printf("Found %d records:%n", size);
String[] Array = records.toArray(new String[0]);
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);
}
}
I am converting an arrayList to a string array in order to try and format it. I'm very new to java and am working on a project in a time crunch.
I need it to print exactly like this:
Found 2 records:
1) Garcia, John 505-338-2567
2) John, Joseph 212-780-3342
It is printing like this:
Found 2 records:
GarciaJohn505-338-2567JohnJoseph212-780-3342

Java is an Object-Oriented language, and you should use it.
Create a class representing your Person, with firstName, lastName, and phoneNumber as fields.
Then you create a List<Person> with 2 objects in it, and write a method for printing that list. The System.out.printf() you're already using can help output values in columns like you want.

You probably need to create you own data-structure, with a toString() method that suits your needs.
Something like:
public class PersonalCustomerData {
private String firstName;
private String lastName;
private String phoneNumber;
...
#Override
public String toString() {
return lastName + "," + " " + firstName + " " + phoneNumber;
}
}
And, as #Andreas mentioned in his answer, you also need a Collection<PersonalCustomerData>, that when you iterate over it, you print your fully formatted output:
private Collection<PersonalCustomerData> col;
// init the collection + do stuff...
public void printCustomerData() {
int lineNumber = 0;
for(PersonalCustomerData pcd : col) {
lineNumber++;
System.out.println(lineNumber + ")" + " " + pcd);
}
}

If you don't want to use object to contain your values and stick with your plan of doing. you can use this code to print it with format.
Replace this:
String[] Array = records.toArray(new String[0]);
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);
}
to this:
int numberOfLine = 1; // Counter of words per line
String[] Array = records.toArray(new String[0]);
for(String str : Array) {
String strSperator = "";
switch (numberOfLine) {
case 1:
strSperator = ", ";
numberOfLine++;
break;
case 2:
strSperator = " ";
numberOfLine++;
break;
case 3:
strSperator = "\n";
numberOfLine = 1;
break;
}
System.out.printf("%s%s",str,strSperator);
}

replace this line
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);`
to something like this. I didn't test out the code so there might be small typos or what not. I think this will do what you want.
As Andreas said, it would be better if you make a person class. It will look more organized and probably easier to understand.
int counter = 1;
System.out.print(records.get(0) + ",\t")
while (counter !=records.size())
{
if(counter %3 ==0)
System.out.println(records.get(counter));
else if(counter% 3== 1)
System.out.print(records.get(counter) + ",\t");
else
System.out.print(records.get(counter)+ "\t");
counter ++;
}
Since your first element will always be first name , 2nd element will be last name and 3rd element is the phone number, I print the first one initially then the modding and the while loop should handle everything I believe.

Related

How do I exclude capitalizing specific words in a String?

I'm new to programming, and here I'm required to capitalise the user's input, which excludes certain words.
For example, if the input is
THIS IS A TEST I get This Is A Test
However, I want to get This is a Test format
String s = in.nextLine();
StringBuilder sb = new StringBuilder(s.length());
String wordSplit[] = s.trim().toLowerCase().split("\\s");
String[] t = {"is","but","a"};
for(int i=0;i<wordSplit.length;i++){
if(wordSplit[i].equals(t))
sb.append(wordSplit[i]).append(" ");
else
sb.append(Character.toUpperCase(wordSplit[i].charAt(0))).append(wordSplit[i].substring(1)).append(" ");
}
System.out.println(sb);
}
This is the closest I have gotten so far but I seem to be unable to exclude capitalising the specific words.
The problem is that you are comparing each word to the entire array. Java does not disallow this, but it does not really make a lot of sense. Instead, you could loop each word in the array and compare those, but that's a bit lengthy in code, and also not very fast if the array of words gets bigger.
Instead, I'd suggest creating a Set from the array and checking whether it contains the word:
String[] t = {"is","but","a"};
Set<String> t_set = new HashSet<>(Arrays.asList(t));
...
if (t_set.contains(wordSplit[i]) {
...
Your problem (as pointed out by #sleepToken) is that
if(wordSplit[i].equals(t))
is checking to see if the current word is equal to the array containing your keywords.
Instead what you want to do is to check whether the array contains a given input word, like so:
if (Arrays.asList(t).contains(wordSplit[i].toLowerCase()))
Note that there is no "case sensitive" contains() method, so it's important to convert the word in question into lower case before searching for it.
You're already doing the iteration once. Just do it again; iterate through every String in t for each String in wordSplit:
for (int i = 0; i < wordSplit.length; i++){
boolean found = false;
for (int j = 0; j < t.length; j++) {
if(wordSplit[i].equals(t[j])) {
found = true;
}
}
if (found) { /* do your stuff */ }
else { }
}
First of all right method which is checking if the word contains in array.
contains(word) {
for (int i = 0;i < arr.length;i++) {
if ( word.equals(arr[i])) {
return true;
}
}
return false;
}
And then change your condition wordSplit[i].equals(t) to contains(wordSplit[i]
You are not comparing with each word to ignore in your code in this line if(wordSplit[i].equals(t))
You can do something like this as below:
public class Sample {
public static void main(String[] args) {
String s = "THIS IS A TEST";
String[] ignore = {"is","but","a"};
List<String> toIgnoreList = Arrays.asList(ignore);
StringBuilder result = new StringBuilder();
for (String s1 : s.split(" ")) {
if(!toIgnoreList.contains(s1.toLowerCase())) {
result.append(s1.substring(0,1).toUpperCase())
.append(s1.substring(1).toLowerCase())
.append(" ");
} else {
result.append(s1.toLowerCase())
.append(" ");
}
}
System.out.println("Result: " + result);
}
}
Output is:
Result: This is a Test
To check the words to exclude java.util.ArrayList.contains() method would be a better choice.
The below expression checks if the exclude list contains the word and if not capitalises the first letter:
tlist.contains(x) ? x : (x = x.substring(0,1).toUpperCase() + x.substring(1)))
The expression is also corresponds to:
if(tlist.contains(x)) { // ?
x = x; // do nothing
} else { // :
x = x.substring(0,1).toUpperCase() + x.substring(1);
}
or:
if(!tlist.contains(x)) {
x = x.substring(0,1).toUpperCase() + x.substring(1);
}
If you're allowed to use java 8:
String s = in.nextLine();
String wordSplit[] = s.trim().toLowerCase().split("\\s");
List<String> tlist = Arrays.asList("is","but","a");
String result = Stream.of(wordSplit).map(x ->
tlist.contains(x) ? x : (x = x.substring(0,1).toUpperCase() + x.substring(1)))
.collect(Collectors.joining(" "));
System.out.println(result);
Output:
This is a Test

Is there an easy way to eliminate the final comma in my output? Number Seperator

For another assignment i needed to program a "number seperator", that splits any given int value into all of its digits and returns it to the main class as a String.
I have the program up and running but there's a small problem with my output.
public class NumberSeperator {
static String splitNumber(int zahl) {
String s = Integer.toString(zahl);
return s;
}
public static void main(String args[]) {
System.out.println("Input a Number: ");
int zahl = readInt();
String ziffern = splitNumber(zahl);
for (int i = 0; i < ziffern.length(); i++) {
System.out.print(ziffern.charAt(i) + ",");
}
}
}
The output of 1234 should be: 1,2,3,4
and the actual output is: 1,2,3,4,
At the risk of sounding extremely stupid, is there an easy fix to this?
How about printing first element without comma and rest in form ,nextElement like
one, two, three
^^^---------------- - before loop
^^^^^----------- - loop iteration
^^^^^^^---- - loop iteration
It can be achieved like:
if(ziffern.length()>0){
System.out.print(ziffern.charAt(0));
}
for(int i=1; i<ziffern.length(); i++){
System.out.print(", "+ziffern.charAt(i));
}
OR you can convert ziffern to String[] array first and use built-in solution which is: String.join(delimiter, data)
System.our.print(String.join(",", ziffern.split("")));
When it's the last iteration, just don't add it.
In the last iteration, it will make the comma empty so that you won't see it after the last value.
String comma=",";
for (int i = 0; i < ziffern.length(); i++) {
if (i == ziffern.length()-1) {
comma="";
}
System.out.print(ziffern.charAt(i) + comma);
}
with Java 8 and streams you can do it in a single command:
String join = Arrays.asList(ziffern.split(""))
.stream()
.collect(Collectors.joining(","));
System.out.println(join);
or with just plain java 8:
String join = String.join(",", ziffern.split(""));
System.out.println(join);
A simple one liner will do your job:
static String splitNumber(int zahl) {
return String.join(",", String.valueOf(zahl).split(""));
}
Quite often this occurs when you know you have at least two items to print. So here is how you could do it then.
String ziffern = splitNumber(zahl);
String output = ziffern[0];
for (int i = 1; i < ziffern.length(); i++) {
output = "," + ziffern[i];
}
System.out.println(output);
You can just output the string without the last character.
Your modified code should be:
public class NumberSeperator {
static String splitNumber(int zahl) {
String s = Integer.toString(zahl);
return s;
}
public static void main(String args[]) {
int zahl = 1234;
String s="";
String ziffern = splitNumber(zahl);
for (int i = 0; i < ziffern.length(); i++) {
s+=ziffern.charAt(i) + ",";
}
System.out.println(s.substring(0,s.length()-1));
}

How can I check if elements in my array list is ending with character "_bp"

How can I check if elements in my ArrayList are ending with "_bp" and append that suffix when they don't.
It would be great if i don't have to convert my ArrayList into String.
I tried below code:
ArrayList<String> comparingList = new ArrayList<String>();
String search = "_bp";
for (String str : comparingList)
{
if (str.trim().contains(search))
{
// Do Nothing
}
else
{
str.trim().concat("_bp");
//Replace existing value with this concated value to array list
}
}
But I am still not able to append "_bp" in the existing element, also dont want to convert my
comparingList into String.
A smaller code is preferable if possible.
Thanks in advance :)
String a = "test";
System.out.println("1 " + a.concat("_bp"));
System.out.println("2 " + a);
a = a.concat("_bp");
System.out.println("3 " + a);
output:
1 test_bp
2 test
3 test_bp
code like this:
ArrayList<String> comparingList = new ArrayList<String>();
comparingList.add("test1_bp");
comparingList.add("test2");
String search = "_bp";
for (int i = 0; i < comparingList.size(); i++) {
String tmpStr = comparingList.get(i);
if(tmpStr.contains(search)){
//do nothing
}else{
comparingList.set(i, tmpStr+"_bp");
}
}
System.out.println(comparingList);
This worked :)
String search = "_bp";
int i = 0;
for (String str : comparingList)
{
if (str.trim().contains(search))
{
}
else
{
comparingList.set(i, str.trim().concat("_bp"));
}
i++;
}

Remove last comma java

I am trying to insert an element into table from a 2D array.
I have a problem in removing the last comma to write the sql statement in a proper way
This is the code
String m="";
String matInsert = null;
for (int k=0;k<di.mat.length;k++) { //row
for (int j=0;j<di.mat[k].length;j++) {
m+=di.mat[k][j]+", ";
matInsert=new String("INSERT INTO "+ tableName +"("+ff+")"+"values" +"("+m+")");
}
m = m.replaceAll(", $","");
//m=m.substring(0,m.lastIndexOf(","));
System.out.println(matInsert);
stmt1.executeUpdate(matInsert);
}
I tried very much but i did not succeed to remove it
please help.
I commonly use the following structure for this type of thing
String sep = "";
for(...) {
m += (sep+di.mat[k][j]);
sep = ",";
}
It isn't the nicest but it works.
Now, part of the problem in your code is that you are creating matInsert inside the loop then updating m after the loop and not rebuilding it.
Updated code:
String matInsert = null;
for (int k=0;k<di.mat.length;k++) { //row
String m="";
String sep = "";
for (int j=0;j<di.mat[k].length;j++) {
m+= (sep+di.mat[k][j]);
sep = " ,";
}
matInsert="INSERT INTO "+ tableName +"("+ff+")"+"values" +"("+m+")";
System.out.println(matInsert);
stmt1.executeUpdate(matInsert);
}
You can avoid last comma addition with simple logic. It is good idea to omit unnecessary thing on spot, rather than to replace that with another operation.
for (int k=0;k<di.mat.length;k++) { //row
for (int j=0;j<di.mat[k].length;j++) {
m+=di.mat[k][j];
if(j<di.mat[k].length -1){ //This condition will escape you from last comma addition
m+= ", ";
}
}
}
Another point, use StringBuilder#append instead of String + concat to increase the efficiency.
Since m is a String, you can use m.substring(0,m.length()-1) or add and if statement inside the inner loop checking if it is the last index of k and j then don't add a comma at the end.
If you want to remove the last instance of a character in a string, as in delete it, use this:
public class Something
{
public static void main(String[] args)
{
String s = "test";
StringBuilder sb = new StringBuilder(s);
char delval = 'c';
int lastIndex = -1;
for(int i = 0; i < s.length()-1; i++)
{
if(s.charAt(i) == delval)
{
lastIndex = i;
}
}
try{
sb.deleteCharAt(lastIndex);
System.out.println(s);
}
catch(Exception e){
System.out.println("Value not present");
}
}
}

Separating an address line into House Number, Street name, and Apartment in Java or COBOL

I am currently trying to figure out the best way to take an address line and separate it out into three fields for a file, house number, street name, and apartment number. Thankfully, the city, state, and zip are already in columns so all I have to parse out is just the three things listed above, but even that is proving difficult. My initial hope was to do this in COBOL using SQL, but I dont think I am able to use the PATINDEX example someone else had listed on a separate question thread, I kept getting -440 SQL code. My second thought was to do this in Java using the strings as arrays and checking the arrays for numbers, then letters, then a compare for "Apt" or something to that effect. I have this so far to try to test out what I'm ultimately trying to do, but I am getting out of bounds exception for the array.
class AddressTest{
public static void main (String[] arguments){
String adr1 = "100 village rest court";
String adr2 = "1000 Arbor lane Apt. 21-D";
String[] HouseNbr = new String[9];
String[] Street = new String[20];
String[] Apt = new String[5];
for(int i = 0; i < adr1.length();i++){
String[] forloop = new String[] {adr1};
if (forloop[i].substring(0,1).matches("[0-9]")){
if(forloop[i+1].substring(0,1).matches("[0-9]")){
HouseNbr[i] = forloop[i];
}
else if(forloop[i+1].substring(0,1).matches(" ")){
}
else if(forloop[i].substring(0,1).matches(" ")){
}
else{
Street[i] = forloop[i];
}
}
}
for(int j = 0; j < HouseNbr.length; j++){
System.out.println(HouseNbr[j]);
}
for(int k = 0; k < Street.length; k++){
System.out.println(Street[k]);
}
}
}
Any other thoughts would be extremly helpful.
I would consider removing the unnecessary arrays and use a StringTokenizer...
public static void main(String[] args) {
String number;
String address;
String aptNumber;
String str = "This is String , split by StringTokenizer";
StringTokenizer st = new StringTokenizer(str);
System.out.println("---- Split by space ------");
while (st.hasMoreElements()) {
String s = System.out.println(st.nextElement());
if (StringUtils.isNumeric(s) {
number = s;
continue;
}
if(s.indexOf("Apt")) {
aptNumber = s.substring(s.indexOf("Apt"),s.length-1);
continue;
}
}
System.out.println("---- Split by comma ',' ------");
StringTokenizer st2 = new StringTokenizer(str, ",");
while (st2.hasMoreElements()) {
System.out.println(st2.nextElement());
}
}
If you leverage the freely available U.S. Postal Service zip code finder (https://tools.usps.com/go/ZipLookupAction!input.action), you can get back an address in standardized format. The valid options on that format are documented by the USPS and will make it easier to write a very complicated regex, or a number of simple regexes, to read the standard form.
I am still working on it, but for any in the future who may need to do this:
import java.util.Arrays;
import java.util.StringTokenizer;
import org.apache.commons.lang3.*;
class AddressTest{
public static void main (String[] arguments){
String adr1 = "100 village rest court";
//String adr2 = "1000 Arbor lane Apt. 21-D";
String reader = new String();
String holder = new String();
StringTokenizer a1 = new StringTokenizer(adr1);
String[] HouseNbr = new String[9];
String[] StreetName = new String[20];
String[] Apartment = new String[5];
int counter = 0;
while(a1.hasMoreElements()){
reader = a1.nextElement().toString();
System.out.println("Reader: " + reader);
if(StringUtils.isNumeric(reader)){
String[] HNBR = reader.split("");
for(int i = 1; i <= reader.length();i++){
System.out.println("HNBR:_" + HNBR[i]);
HouseNbr[i-1] = HNBR[i];
}
}
else if(StringUtils.startsWith(reader, "Apt.")){
holder = a1.nextElement().toString();
String[] ANBR = holder.split("");
for(int j = holder.length(); j >= 0;j--){
Apartment[j] = ANBR[j];
}
}
else{
String STR[] = reader.split("");
for(int k = 1; k <= reader.length();k++){
if(counter == StreetName.length){
break;
}
else{
StreetName[counter] = STR[k];
if(counter < StreetName.length){
counter++;
}
}
}
if((counter < StreetName.length) && a1.hasMoreElements()){
StreetName[counter] = " ";
counter++;
}
}
}
System.out.println(Arrays.toString(HouseNbr) + " " + Arrays.toString(StreetName)
+ " " + Arrays.toString(Apartment));
}
}

Categories