I am trying to insert tuples into newly created tables of a database schema I am building for SQL.
The issue is, I am to expect the first line to be
ssn INTEGER(9), cname VARCHAR(25), gender VARCHAR(6), age VARCHAR(3), profession VARCHAR(25)
But I want it to just be this:
ssn, cname, gender, age, profession
The previous method I tried with two splits, one for the space and the other for the comma is not working, so I thought using replace all would be easier. However, I am not sure what to try for the regular expression. How should these be created?
private static String parseFile (String[] x, Connection conn,
String tableName) {
// assume the first line is the relation name layout
String query = "INSERT INTO " + tableName;
String firstLine = x[0];
//System.out.println(firstLine);
String[] splits = firstLine.split(" ");
String[] finalSplit = new String[50];
String finalString = "";
for (int i=0; i<splits.length; i++) {
int counter = 0;
String[] split2 = splits[i].split(",");
//System.out.println (splits[i]);
for (int j=0; j<split2.length; j++) {
finalSplit[j+counter] = split2[j];
//System.out.println (split2[j]);
if (j%2 == 0)
finalString += split2[j];
counter += 1;
}
} // end outside for
System.out.println ("The attribute string is: " + finalString);
for (int i=1 ; i<x.length; i++)
{
String line = x[i];
String Final = query + " " + finalString + " " + line;
System.out.println ("Final string: " + Final);
}
return finalString;
}
I would appreciate a bit of guidance here.
EDIT:
Some of the output is:
The attribute string is: ssnINTEGER(9)cnameVARCHAR(25)genderVARCHAR(6)ageVARCHAR(3)professionVARCHAR(25)
Final string: INSERT INTO customer ssnINTEGER(9)cnameVARCHAR(25)genderVARCHAR(6)ageVARCHAR(3)professionVARCHAR(25) 3648993,Emily,male,63,Consulting
Final string: INSERT INTO customer ssnINTEGER(9)cnameVARCHAR(25)genderVARCHAR(6)ageVARCHAR(3)professionVARCHAR(25) 5022334,Barbara,male,26,Finance
Final string: INSERT INTO customer ssnINTEGER(9)cnameVARCHAR(25)genderVARCHAR(6)ageVARCHAR(3)professionVARCHAR(25) 1937686,Tao,female,5,IT
Some of the input of x is:
ssn INTEGER(9), cname VARCHAR(25), gender VARCHAR(6), age VARCHAR(3), profession VARCHAR(25)
3648993,Emily,male,63,Consulting
5022334,Barbara,male,26,Finance
1937686,Tao,female,5,IT
Try
firstLine.replaceAll(" [A-Z]+\\(\\d+\\)","");
Explanation: This regex finds words with 1 or more capital letters immediately followed by a left parenthesis, one or more digits, a right parenthesis and a comma.
replaceAll replaces all instances of this with an empty string.
Related
Currently stuck on an assignment that requires me to print out the users name as such: Last,First Initial.
(Bob, Billy H.) If I add too many spaces between the first and middle name when inputting, I get an index out of bounds exception. (String out of bounds 0) The program runs completely fine unless I have more than one space between the first and middle name.
I can only use the trim, indexOf, substring,and charAt methods in this program.
import java.util.Scanner;
public class Name {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter your name in this format: <spaces>First name<spaces>Middle name<spaces>Last name<spaces>");
String name = s.nextLine();
name = name.trim();
String first, middle, last;
int firstSpace = name.indexOf(' ');
first = name.substring(0, firstSpace);
int secondSpace = name.indexOf(" ", (firstSpace + 1));
middle = name.substring((firstSpace + 1), secondSpace);
middle.trim();
last = name.substring(secondSpace+1);
char middleInitial = middle.charAt(0);
String initial = "";
initial = initial + middleInitial;
for(int i = 1; i < middle.length(); i++) {
char currentLetter = middle.charAt(i);
char lastLetter = middle.charAt(i - 1);
if(lastLetter == ' ') {
initial = initial + "." + currentLetter;
}
}
System.out.println(last + "," + first + ' ' + initial + ".");
}
}
The reason for error is for input
amid skum asdf
for above input:
int firstSpace = name.indexOf(' '); //firstSpace = 0
int secondSpace = name.indexOf(" ", (firstSpace + 1));//secondSpace = 1
middle = name.substring((firstSpace + 1), secondSpace); // as the two or more continues space inputted, this will select empty string as firstSpace + 1 == secondSpace and later causing the exception
Do name = name.replaceAll(" +", " "); to replace all two or more white spaces.
As karthik suggested in comments, perform assignment middle = middle.trim();.
EDIT:
Since you can not use replaceAll, Modified the code just by using trim method. Have a closer look at the below snippets:
String middleNameLastName = name.substring(firstSpace+1).trim();
last = middleNameLastName.substring(index+1).trim();
These removes trailing spaces.
import java.util.Scanner;
public class Post1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter your name in this format: <spaces>First name<spaces>Middle name<spaces>Last name<spaces>");
String name = s.nextLine();
name = name.trim();
String first, middle, last;
int firstSpace = name.indexOf(' ');
first = name.substring(0, firstSpace);
String middleNameLastName = name.substring(firstSpace+1).trim();
int index = middleNameLastName.indexOf(" ");
middle = middleNameLastName.substring(0, index);
last = middleNameLastName.substring(index+1).trim();
System.out.println(last + "," + first + ' ' + middle.charAt(0) + ".");
s.close();
}
}
I'm trying to create a dialog window where I ask for a persons name with the format: Lastname, Surname
I'm then trying to show just the surname name in a new dialog window with the format: Hello! SURNAME!
This is my code so far:
import javax.swing.*;
public class Surname {
public static void main(String[] arg) {
String a = JOptionPane.showInputDialog(null, "Write your name: Lastname, surname ");
int i, j;
i = a.lastIndexOf(???);
j = a.indexOf(',' + 1);
a = a.substring(i, j);
JOptionPane.showMessageDialog(null, "Hello! " + a.toUpperCase()); }}
Your substring is not correct, for the start you'll need the index of the comma, for the end simply the length of the string:
int i, j;
i = a.indexOf(',') + 2;
j = a.length();
a = a.substring(i, j);
You can extract the surname by splitting the string by ", ".
For example
String surname = "Novovic, Felix".split(", ")[0];
Since we are accessing an array here which size is fully determined by the input of the user, i.e. the user inputs "Novovic, Felix, Hello, World" you should reassure that the input is in the correct format before you access the array.
For example, by checking that the array length = 2
Using split() this will do:
public static void main(String[] args) {
String a = JOptionPane.showInputDialog(null, "Write your name: Lastname, surname ");
String[] nameParts = a.split(",");
JOptionPane.showMessageDialog(null, "Hello! " + nameParts[1].trim().toUpperCase());
}
... but you would probably want to add some more error handling. So this is only a bare bone example
THIS IS ONE METHOD CLASS ONLY .
System.out.print("1. Add Customer..............................................P500.00\n");
case 1://Add Customer
for (int x = 0; x < CustomerInfo.length; x++){// Start For Records
x++;
System.out.print("\nConfimation Number: ");
CustomerInfo[x][0][0][0][0][0] = br.readLine();
System.out.print("\nFirst Name: ");
CustomerInfo[x][1][0][0][0][0] = br.readLine();
System.out.print("Last Name: ");
CustomerInfo[x][0][1][0][0][0] = br.readLine();
System.out.print("Guest: ");
CustomerInfo[x][0][0][1][0][0] = br.readLine();
System.out.print("Night: ");
CustomerInfo[x][0][0][0][1][0] = br.readLine();
System.out.print("Accommodation: ");
CustomerInfo[x][0][0][0][0][1] = br.readLine();
System.out.println();
break;
}
break;
for (int x = 0; x < CustomerInfo.length; x++){
if (CustomerInfo[x][0][0][0][0][0] != null){
if (CustomerInfo[x][1][0][0][0][0] != null){
if (CustomerInfo[x][0][1][0][0][0] != null){
if (CustomerInfo[x][0][0][1][0][0] != null){
if (CustomerInfo[x][0][0][0][1][0] != null){
if (CustomerInfo[x][0][0][0][0][1] != null){
System.out.print("\n|---------------------------------------------------------------------|\n");
System.out.print("\n\nConfirmation Number: |---------------> " + CustomerInfo[x][0][0][0][0][1]);
System.out.print("\nGuest Name: |---------------> " + CustomerInfo[x][1][0][0][0][0] + " " + CustomerInfo[x][0][1][0][0][0]);
System.out.print("\nNumber Of Guest: |---------------> " + CustomerInfo[x][0][0][1][0][0]);
System.out.print("\nNumber Of Nights: |---------------> " + CustomerInfo[x][0][0][0][1][0]);
System.out.println("\nAccommodations: |---------------> " + CustomerInfo[x][0][0][0][0][1]);
i add customer for first time then if i add customer for the second time the first customer wasn't recorded.
i noticed that the problem is the increment.
for (int x = 0; x < CustomerInfo.length; x++)
because i use break after that.
break;
but i want to accomplish is to add customer and when i add another one the previous should display along with the new.
what i asked is i want to add more array values one after one . or like after i add value to my '[x]' i want to add again, but not at the same time
any suggestions ?
i really need your help.
You probably meant to declare CustomerInfo as follows:
String[] customerInfo = new String[6];
and have each array - hold the information of one customer, where first-name will be stored on the first index, last-name on the second and etc.
By doing something like CustomerInfo[][][][][][] - the code tries to declare/access a multidimensional (6-dimensional) array - which is probably not what you wanted.
Now Java is an object oriented programming language, so instead of multidimensional arrays you should try to design your code to use objects - it will make your code easier to read and maintain.
So first, create a CustomerInfo class:
class CustomerInfo {
String confirmationNumber;
String firstName;
String lastName;
String guest;
String night;
String accommodation;
public CustomerInfo(String confirmationNumber,
String firstName,
String lastName,
String guest,
String night,
String accommodation) {
this.confirmationNumber = confirmationNumber;
this.firstName = firstName;
this.lastName = lastName;
this.guest = guest;
this.night = night;
this.accommodation = accommodation;
}
}
and now that you have such a "holder" for the data, you can read the user input and save it into a list of CustomerInfo:
public static void main(String[] args) {
...
List<CustomerInfo> customerInfos = new ArrayList<CustomerInfo>();
for (int i = 0; i < customerInfos.length; i++){// Start For Records
System.out.print("\Confirmation Number: ");
String confirmationNumber = br.readLine();
System.out.print("\nFirst Name: ");
String firstName = br.readLine();
System.out.print("Last Name: ");
String lastName = br.readLine();
System.out.print("Guest: ");
String guest = br.readLine();
System.out.print("Night: ");
String night = br.readLine();
System.out.print("Accommodation: ");
String accommodation = br.readLine();
CustomerInfo customer = new CustomerInfo(confirmationNumber, firstName, lastName, guest, night, accommodation);
customerInfos.add(customer);
System.out.println();
}
}
and if you want to do even better, add some validations on top, for example, if guest is a number, you can read it as int or try to parse it as an int - and if the user entered something weird - display a proper error message. And etc.
case 1://Add Customer
for (int x = 0; x < CustomerInfo.length; x++){// Start For Records
**x++;**
You have problem with your loop. You increase your incremental variable when you start loop and when you finish loop two times.
That means you start not with 0 but with 1. But you want to check that if there is a customer at 0.
I have the following data which is stored as a big string.
"John Chips Monday \n"
"Tom Pizza Tuesday\n"
"Jerry IceCream Wednesday\n"
"Jennifer Coffee Thursday\n"
Now I wish to split this string so I can get individual data from this string and place each data in an array for example.
each element of names array stores the names seen above like names[0] = john, names[1] = Tom etc.
each element of food array stores the foods seen above like food[0] = chips, food[1] = pizza.
I have tried doing this
John + "\t" + Chips + "-" + Monday + "\n"
Tom + "\t" + Pizza + "-" + Tuesday+ "\n"
Jerry + "\t" + IceCream + "-" + Wednesday+ "\n"
Jennifer + "\t" + Coffee + "-" + Thursday+ "\n"
String nameCol[] = data.split("\\t");
String foodCol[] = data.split("-");
The output I get is nearly there but wrong as it contains data that I don't want in the array for example the output for first array is
nameCol[0] = John
nameCol[1] = Chips -
nameCol[2] = Monday
Element 0 contains john but the other elements contain the parts I don't want.
I tried for a limit but this did not work
String nameCol[] = data.split("\\t",1);
String foodCol[] = data.split("-",1);
This will work:
String yourLine = "John Chips Monday\n"; // Read your line in here
String[] resultCol = yourLine.split(" ");
resultCol[2] = resultCol[2].split("\\n")[0];
System.out.println( resultCol[2] );
The first split on the string will give you "John", "Chips" and "Monday\n". The second split takes "Monday\n" from the array and splits it. Returning "Monday" back into the final index of the array resultCol[2]. From here you can simply assign each element in the array to the arrays you require.
Don't use them separately, use the delimiters together, like : String dataArr\[\] = data.split("\t\n",1);
Then iterate through the String[]:
for (int i = 0; i < dataArr.length; i+=2) {
String name = dataArr[i];
String food = dataArr[i+1];
// ... do whatever you want with them.
}
Or, you could also try the similar Pattern-Matcher approach
You should:
use Lists for each column, (Lists can increase their size dynamically, while arrays have fixed size)
iterate over each line,
split it on whitespace (or any separator you are using)
and add column[0] to list of names, column[1] to list of food and so on with other columns.
OR if you know that each line has only three words you could simply use Scanner and iterate over words instead of lines with split.
while(scanner.hasNext()){
listOfNames.add(scanner.next());
listOfFood.add(scanner.next());
listOfDays.add(scanner.next());
}
Try this,
String str="John" + "\t" + "Chips" + "\t" + "Monday" + "-" + "Test"+"\n"+"chet";
String st1= str.replaceAll("(\\t)|(-)|(\n)"," ");
String []st=st1.split(" ");
for(String s : st)
System.out.println(s);
From your data, I assume that you are reading this values from a files. If you know how many lines there are, you could use 3 arrays, each for every type of data that needs to be retrived. If you don't know the size, you could go with 3 ArrayLists. Your problem is that after making the split, you didn't put them in the correct arrays. The following code assumes that you already have all the data in one String.
final String values[] = data.split("\\n");
final ArrayList<String> names = new ArrayList<String>();
final ArrayList<String> foods = new ArrayList<String>();
final ArrayList<String> days = new ArrayList<String>();
for (String line : values) {
String[] split = line.trim().split("[ ]+");
names.add(split[0]);
foods.add(split[1]);
days.add(split[2]);
}
Another thing that you must consider is to check if the data always has 3 values on a "line", or else further error checking is needed.
If your string is always going to be "[name] [food] [day]", then you could do:
String[] names = new String[allData.length]; //A list of names
String[] food = new String[allData.length]; //A list of food
String[] day = new String[allData.length]; //A list of days
for(int i = 0 ; i < allData.length ; i++)
{
String[] contents = allData[i].split(" "); //Or use a similar delimiter.
names[i] = contents[0];
food[i] = contents[1];
day[i] = contents[2];
}
Try this code
String s = "John Chips Monday \n Tom Pizza Tuesday \n Jerry IceCream Wednesday \n Jennifer Coffee Thursday \n";
String split[] = s.split("\n");
String names[] = new String[split.length];
String foods[] = new String[split.length];
String days[] = new String[split.length];
for (int i = 0; i < split.length; i++) {
String split1[] = split[i].trim().split(" ");
names[i]=split1[0];
foods[i]=split1[1];
days[i]=split1[2];
System.out.println("name=" + names[i] + ",food=" + foods[i] + ",day=" + days[i]);
}
I created a program which will parse the firstName, middleName and lastName. Here is the program and output. This program can definitely be improved and need some input on reducing my cumbersome ugly code and replace it with a better one. Any suggestions or example ?
public class Test {
public static void main(String[] args) {
String fullName = "John King IV. Cena";
String[] tokens = fullName.split(" ");
String firstName = "";
String middleName = "";
String lastName = "";
if(tokens.length > 0) {
firstName = tokens[0];
middleName = tokens.length > 2 ? getMiddleName(tokens) : "";
lastName = tokens[tokens.length -1];
}
System.out.println(firstName);
System.out.println(middleName);
System.out.println(lastName);
}
public static String getMiddleName(String[] middleName){
StringBuilder builder = new StringBuilder();
for (int i = 1; i < middleName.length-1; i++) {
builder.append(middleName[i] + " ");
}
return builder.toString();
}
}
John
King IV.
Cena
This code does the same, but doesn't keep a trailing space in the middle name. This is one of several possible cleaner implementations.
public class Test {
public static void main(String[] args) {
String name = "John King IV. Cena";
int start = name.indexOf(' ');
int end = name.lastIndexOf(' ');
String firstName = "";
String middleName = "";
String lastName = "";
if (start >= 0) {
firstName = name.substring(0, start);
if (end > start)
middleName = name.substring(start + 1, end);
lastName = name.substring(end + 1, name.length());
}
System.out.println(firstName);
System.out.println(middleName);
System.out.println(lastName);
}
}
As the guys said, next time go directly to https://codereview.stackexchange.com/
The algorithm will fail if the persons last name has more than one word, like Abraham Van Helsing. Van is not a middle name but part of the last name.
Obviously, there is no algorithm to clearly distinguish between middle name and last name in general. We always have to guess and we can only try to improve the probability that the guess is correct, maybe be checking middle name parts against word or filter lists.
You could also use a StringTokenizer for this:
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) {
String fullName = "John King IV. Cena";
StringTokenizer stok = new StringTokenizer(fullName);
String firstName = stok.nextToken();
StringBuilder middleName = new StringBuilder();
String lastName = stok.nextToken();
while (stok.hasMoreTokens())
{
middleName.append(lastName + " ");
lastName = stok.nextToken();
}
System.out.println(firstName);
System.out.println(middleName.toString().trim());
System.out.println(lastName);
}
}
Update the code to handle where there is no last name i.e. user enters only the first name like "Mark"
if(tokens.length > 0) {
firstName = tokens[0];
middleName = tokens.length > 2 ? getMiddleName(tokens) : "";
if(tokens.length > 1){
lastName = tokens[tokens.length -1];
}
}