Unable To Print Value Of Variable - java

it seems simple to Print value of Variable in java but i am unable to do this properly.
i have Mysql table that contains first names "fname" & last names "lname". after connecting to my sql i fetch these values and store in variables. then problem starts... here is and here is my code
package signup;
import java.sql.*;
import java.util.Random;
import org.openqa.selenium.Keys;
public class Signup {
private static final String db_connect = "jdbc:mysql://localhost/test1" ;
private static final String uname = "username" ;
private static final String pass = "password" ;
private Connection conMethod(){
Connection conVar = null;
try{Class.forName("com.mysql.jdbc.Driver");conVar = DriverManager.getConnection(db_connect,uname,pass);}catch(SQLException e){e.printStackTrace();
}catch(ClassNotFoundException e){e.printStackTrace();}return conVar;}
public void selectMethod(){Statement query = null;
ResultSet rs1 = null;
Connection conVar2= conMethod();try{query = conVar2.createStatement();
rs1 = query.executeQuery("Select * from fnames2");
String[] fname=new String[500]; String[] lname=new String[500];
int a=0;while(rs1.next()){fname[a]=rs1.getString(2); lname[a]=rs1.getString(3); a++;}
String firstname = fname[1];
String lastname = lname[1];
String fullname = firstname+" "+lastname;
String email = firstname+lastname+"#yahoo.com";
System.out.println("first name is "+firstname);
System.out.println("last name is "+lastname);
System.out.println("full name is "+fullname);
System.out.println("email is "+email);
} catch(SQLException e){e.printStackTrace();}
}
public static void main (String args[]){Signup obj = new Signup();obj.selectMethod();}
}
and here is its out put
first name is PATRICIA
last name is ALISHA
full name is PATRICIA ALISHA
#yahoo.comATRICIAALISHA
you can see problem is in email variable. it should print PATRICIAALISHA#yahoo.com but it is printing something "#yahoo.comATRICIAALISHA" . Thanks

The output is consistent with lastname being "ALISHA\r". What happens is that when you print it (depending on your OS), the \r character causes the cursor to go back to the beginning of the line. This has no effect on the appearance of the output in the cases where you print "last name is" or "full name is", since the cursor will just go to the next line anyway. But it causes email to be "PATRICIAALISHA\r#yahoo.com", which means that after it outputs email is PATRICIAALISHA, the cursor goes back to the beginning of the line and overwrites what's already there with #yahoo.com, which is just enough to overwrite the text up through the P.

Related

Reading from CSV file and create object

I'm a complete beginner to Java and I have been given an exercise where I have to read data from a CSV file and then create an object for each line of the file as the program reads the data from the file.
Here is part of the CSV file:
1,Jay, Walker,91 Boland Drive,BAGOTVILLE,NSW,2477
2,Mel, Lowe,45 Ocean Drive,MILLERS POINT,NSW,2000
3,Hugh, Manatee,32 Edgecliff Road,REDFERN,NSW,2016
4,Elizabeth, Turner,93 Webb Road,MOUNT HUTTON,NSW,2290
and so on ...
Here is my code that reads data from the CSV file:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Client_19918424 {
public static void main(String[] args) throws FileNotFoundException {
File inFile = new File("clients.txt");
Scanner inputFile = new Scanner(inFile);
String str;
String[] tokens;
while (inputFile.hasNext()) {
str = inputFile.nextLine(); // read a line of text from the file
tokens = str.split(","); // split the line using commas as delimiter
System.out.println("Client ID: " + tokens[0]);
System.out.println("Client First Name: " + tokens[1]);
System.out.println("Client Sur Name: " + tokens[2]);
System.out.println("Street Address: " + tokens[3]);
System.out.println("Suburb: " + tokens[4]);
System.out.println("State: " + tokens[5]);
System.out.println("Postcode:" + tokens[6]);
System.out.println( );
} // end while
}
}
this is my Client class (have constructor):
public class Client {
private int clientID;
private String firstName;
private String surName;
private String street;
private String suburb;
private String state;
private int postcode;
// constructor
public Client (int ID, String fName, String sName, String str, String sb, String sta, int pCode) {
clientID = ID;
firstName = fName;
surName = sName;
street = str;
suburb = sb;
state = sta;
postcode = pCode;
}
However I don't know how to create a Client object for each line of text file as the program reads data from file.
like for the first line make something like this:
Client client1 = new Client(1, "Jay", "Walker", "91 Boland Drive", "BAGOTVILLE", "NSW", 2477);
And then add it to array:
Client[0] = client1;
can someone help me to solve this question, im really appreciate.
You are almost there.
All that's left to do is to map each token that is already printed to the corresponding fields in the Client class. Since token[0] doesn't really tell what value it holds you could do it in three ways:
while (inputFile.hasNext()) {
str = inputFile.nextLine();
tokens = str.split(",");
// Because tokens[0] is of type String but clientID is of type int,
// we need to parse it and get the integer representation.
int clientID = Integer.parseInt(tokens[0]);
// Both of type String, no parsing required.
String firstName = tokens[1];
String surName = tokens[2];
String street = tokens[3];
String suburb = tokens[4];
String state = tokens[5];
int postcode = Integer.parseInt(tokens[6]);
// Then all that's left to do is to create a new object of `Client` type
// and pass all the gathered information.
Client client = new Client(clientID, firstName, surName, street, suburb, state, postcode);
System.out.println(client + "\n");
}
At this moment if we try to print the client (last line) we will get something like this: com.example.demo.Client#30a3107a. That's because we didn't tell how we want our object to be displayed. For that toString() method in Client class has to be overriden like so:
#Override
public String toString() {
return "Client ID: " + clientID + "\n" + "Client First Name: " + firstName + "\n"
+ "Client Sur Name: " + surName + "\n" + "Street Address: " + street + "\n"
+ "Suburb: " + suburb + "\n" + "State: " + state + "\n" + "Postcode: " + postcode;
}
It will give the exact output that is in your example.
It is achievable to create the class by passing those tokens directly as well, without the creation of temporary variables:
Client client = new Client(Integer.parseInt(tokens[0]), tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], Integer.parseInt(tokens[6]));
This case brings us to the third solution with setters and getters.
The variables that describe the Client are already defined, it is possible to pass them to assemble the perfect object, but it is not possible to retrieve them. Instead of setting the variables directly in the constructor, we can create a special method that will do the job, for instance:
// Other fields omitted
private int clientID;
// The empty constructor required for later usage,
// since right now, we can't create the object without specifying every property.
public Client() {
}
// This method does exactly the same thing that was done before but
// in the constructor directly
public void setClientID(int clientID) {
this.clientID = clientID;
}
// This method will assist in retrieving the set data from above.
public int getClientID() {
return clientID;
}
And then the while loop would look like this instead:
Client client = new Client();
client.setClientID(Integer.parseInt(tokens[0]));
client.setFirstName(tokens[1]);
client.setSurName(tokens[2]);
client.setStreet(tokens[3]);
client.setSuburb(tokens[4]);
client.setState(tokens[5]);
client.setPostcode(Integer.parseInt(tokens[6]));
And to get those values:
System.out.println("Client ID: " + client.getClientID());
Or you could use the constructor with the fields to create the client, add getters in the class, omit both setters, and the empty constructor if the creation of the client should only be possible with all the fields present.

How can I implement String.split() in my login system?

I have a text file called UserDetails.txt that I am trying to read from.
Each line of the text file is as follows:
John : Doe : Seattle : jd3 : 1234
Jane : Doe : Olympia : jd4 : 5678
Jerry : Doe : Redmond : jd5 : 9101
And so on...
Each line has the first name, last name, username, and password of the registered user by which I am trying to search for only the last two variables (username and password).
public class LoginFrame extends javax.swing.JFrame
{
private static Scanner keyboard = new
Scanner(System.in);
String username;
String password;
String filePath = "UserDetails.txt";
public LoginFrame() {
initComponents();
}
private void jButtonLoginActionPerformed(java.awt.event.ActionEvent evt) {
username = jTextFieldUsername.getText();
password = jTextFieldPassword.getText();
verifyLogin(username,password,filePath);
}
public static void verifyLogin(String username,
String password, String filepath)
{
boolean match = false;
String tempUserName = "";
String tempPassword = "";
try
{
keyboard = new Scanner(new
File(filepath));
keyboard.useDelimiter("[:\n]");
while(keyboard.hasNext() && !match)
{
tempUserName = keyboard.next();
tempPassword = keyboard.next();
if(tempUserName.trim().equals(username.trim()) &&
tempPassword.trim().equals(password.trim()))
{
match = true;
}
}
keyboard.close();
System.out.print(match);
}
catch (Exception e)
{
System.out.print("Error");
}
}
This above code snippet is my original code by which I tried to use a delimiter to find the two specific values but it only seems to work if the username and password are the only two variables in the text file (with first and last names removed).
I've been reading up on the String.split() method so that I can replace my original use of the delimiter. However, I'm still struggling with how I can apply it to my text file. Many of the examples online explain how one can convert an individual line into a String array (which in my example, would have the username at index 3 and password at index 4). This is where I'm confused though. How can I implement the String.split() method without having to manually input it for every specific line? (since there are 50 users in the text file). Would it be possible to implement it with the Scanner.nextLine() method?
Here:
while(keyboard.hasNext() && !match)
{
tempUserName = keyboard.next();
tempPassword = keyboard.next();
You are reading each of the lines in pairs. You should instead call keyboard.next four times in each iteration. I am guessing that you intend to ignore the first name and last name, so you don't need to assign them to any variable:
while(keyboard.hasNext() && !match)
{
// These two lines read the first name and last name and do nothing with them
keyboard.next();
keyboard.next();
// these will read the username and password
tempUserName = keyboard.next();
tempPassword = keyboard.next();
If you want to use split, you need to call nextLine and hasNextLine instead:
while (keyboard.hasNextLine() && !match) {
String[] parts = keyboard.nextLine().split(" : ");
tempUserName = parts[2];
tempPassword = parts[3];
...
}

Reading Files to Store their Data in an Array

The program that I am writing is in Java.
I am attempting to make my program read the file "name.txt" and store the values of the text file in an array.
So far I am using a text file that will be read in my main program, a service class called People.java which will be used as a template for my program, and my main program called Names.java which will read the text file and store its values into an array.
name.txt:
John!Doe
Jane!Doe
Mike!Smith
John!Smith
George!Smith
People.java:
public class People
{
String firstname = " ";
String lastname = " ";
public People()
{
firstname = "First Name";
lastname = "Last Name";
}
public People(String firnam, String lasnam)
{
firstname = firnam;
lastname = lasnam;
}
}
Names.java:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Names
{
public static void main(String[]args)
{
String a = " ";
String b = "empty";
String c = "empty";
int counter = 0;
People[]peoplearray=new People[5];
try
{
File names = new File("name.txt");
Scanner read = new Scanner(names);
while(read.hasNext())
{
a = read.next();
StringTokenizer token = new StringTokenizer("!", a);
while(token.hasMoreTokens())
{
b = token.nextToken();
c = token.nextToken();
}
People p = new People(b,c);
peoplearray[counter]=p;
++counter;
}
}
catch(IOException ioe1)
{
System.out.println("There was a problem reading the file.");
}
System.out.println(peoplearray[0]);
}
}
As I show in my program, I tried to print the value of peoplearray[0], but when I do this, my output reads: "empty empty" which are the values I gave String b and String c when I instantiated them.
If the program were working corrrectly, the value of peoplearray[0] should be, "John Doe" as those are the appropriate values in "names.txt"
What can I do to fix this problem?
Thanks!
StringTokenizer(String str, String delim)
is the constructor of StringTokenizer.
You have written it wrong .
Just change your line
StringTokenizer token = new StringTokenizer("!", a); to
StringTokenizer token = new StringTokenizer(a, "!");
Just change it a little bit
StringTokenizer token = new StringTokenizer(a, "!");
while(token.hasMoreTokens())
{
b = token.nextToken();
c = token.nextToken();
}
//do something with them

Reading a records file and create a index for it

So I need to read from a records file where '#' determines the end of a record and '|' the end of a field like this: #9783642217074|Interaction|Macie|Furtado,Elizabeth|Winckler,Marco|2011#.
Then I need to write just the first field of each record in another file.
I'm trying to use Java I/O RandomAccessFile but I really need some light to figure it out.
If anyone could tell what methods or the ideia behind this Ill be thankful.
You do not need RandomAccessFile, you would be fine with reading and writing your files character-by-character.
Your program can be in any of these three states:
Waiting for the start of the next record
Writing the content of the first field
Waiting for the end of the record
The program changes its state as follows:
Initially, it is in the state number 1
When # character is detected in state 1, the state becomes 2
When | is detected in state 2, the state becomes 3
When # is detected in state 3, the state becomes 1.
Each character received in state 2 is duplicated into the output file
When the state transitions from 3 to 1, write a separator into the output.
This should be really straightforward to code with a single loop that reads from a file, and a handful of if-then-else statements. Make a variable called state outside the loop, set it to 1, open the input and the output files, and make a loop to read the input character-by-character until the end of the file is reached.
Here is an implementation using the Scanner class.
Main.class
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// The path of the project
String basePath = new File("").getAbsolutePath();
// The path of the record file, in relevance to <basePath>
String recordPath = basePath.concat("/RecordList.txt");
// Make sure that path is correct
System.out.println(recordPath + "\n");
// Store all Record objects in an array
ArrayList<Record> recordArray = new ArrayList<Record>();
// Lets try to read the file, and parse each line at a time
try {
// input the file content to the String "input"
BufferedReader file = new BufferedReader(new FileReader(recordPath));
// Store every line of <file> in <input> String
String line;
String input = "";
while ((line = file.readLine()) != null) {
input += line + '\n';
// Remove the # symbols at beginning and end
line = line.replaceFirst("#", "");
System.out.println(line);
//
String recordData[] = line.split("[|]");
Record record = new Record(recordData);
recordArray.add(record);
}
// Make sure to close the <file>
file.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println();
//Verify results
for (Record record : recordArray) {
System.out.println(record.toString());
}
}
}
Record.class
public class Record {
// #9783642217074|Interaction|Macie|Furtado,Elizabeth|Winckler,Marco|2011#
private String id;
private String field2;
private String field3;
private String field4;
private String field5;
private String year;
public Record(String[] recordData) {
this.id = recordData[0];
this.field2 = recordData[1];
this.field3 = recordData[2];
this.field4 = recordData[3];
this.field5 = recordData[4];
this.year = recordData[5];
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "Record [id=" + id + ", field2=" + field2 + ", field3="
+ field3 + ", field4=" + field4 + ", field5=" + field5
+ ", year=" + year + "]";
}
}
And here is the RecordFile.txt I generated (mind the data I made up)
#9783642217074|Interaction|Macie|Furtado,Elizabeth|Winckler,Marco|2011#
#9783612343243|Interaction|Freddie|Fuder,Franscon|Winner,Marie|2013#
#9213432423534|Interaction|Jimbo|Furtado,Melo|Yakasabi,Johnson|2001#
As always, please use my code as a reference. It is always better to learn how to write code yourself, especially when this question pertains to a homework assignment.

How do you parse a difficult .txt file?

I'm fairly new to java and have been attempting to read a very difficult .txt file and input it into my MySQL DB.
To me, the file has some very weird delimiting rules. the delimiting seems to be all commas but other parts just do not make any sense. here is a few examples:
" "," "," "," "," "
" ",,,,,,," "
" ",0.00," "
" ",," ",," ",," "
What I do know is that all fields containing letters will be the normal ,"text", format.
all columns that only have numerals will follow this format: ,0.00, except for the first column which follows the normal format "123456789",
Then anything with no data will alternate between ,, or ," ",
I have been able to get the program to read correctly with java.sql.Statement but I need it to work with java.sql.PreparedStatement
I can get it to work with only a few columns selected but I need this to work with 100+ columns and some fields contain commas e.g. "Some Company, LLC"
Here is the code I currently have but I am at a loss as to where to go next.
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.*;
public class AccountTest {
public static void main(String[] args) throws Exception {
//Declare DB settings
String dbName = "jdbc:mysql://localhost:3306/local";
String userName = "root";
String password = "";
String fileName = "file.txt";
String psQuery = "insert into accounttest"
+ "(account,account_name,address_1,address_2,address_3) values"
+ "(?,?,?,?,?)";
Connection connect = null;
PreparedStatement statement = null;
String account = null;
String accountName = null;
String address1 = null;
String address2 =null;
String address3 = null;
//Load JDBC Driver
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
System.out.println("JDBC driver not found.");
e.printStackTrace();
return;
}
//Attempt connection
try {
connect = DriverManager.getConnection(dbName,userName,password);
}
catch (SQLException e) {
System.out.println("E1: Connection Failed.");
e.printStackTrace();
return;
}
//Verify connection
if (connect != null) {
System.out.println("Connection successful.");
}
else {
System.out.println("E2: Connection Failed.");
}
BufferedReader bReader = new BufferedReader(new FileReader(fileName));
String line;
//import file into mysql DB
try {
//Looping the read block until all lines in the file are read.
while ((line = bReader.readLine()) != null) {
//Splitting the content of comma delimited file
String data[] = line.split("\",\"");
//Renaming array items for ease of use
account = data[0];
accountName = data[1];
address1 = data[2];
address2 = data[3];
address3 = data[4];
// removing double quotes so they do not get put into the db
account = account.replaceAll("\"", "");
accountName = accountName.replaceAll("\"", "");
address1 = address1.replaceAll("\"", "");
address2 = address2.replaceAll("\"", "");
address3 = address3.replaceAll("\"", "");
//putting data into database
statement = connect.prepareStatement(psQuery);
statement.setString(1, account);
statement.setString(2, accountName);
statement.setString(3, address1);
statement.setString(4, address2);
statement.setString(5, address3);
statement.executeUpdate();
}
}
catch (Exception e) {
e.printStackTrace();
statement = null;
}
finally {
bReader.close();
}
}
}
Sorry if it's not formatted correctly, I am still learning and after being flustered for several days trying to figure this out, I didn't bother making it look nice.
My question is would something like this be possible with such a jumbled up file? if so, how do I go about making this a possibility? Also, I am not entirely familiar with prepared statements, do I have to declare every single column or is there a simpler way?
Thanks in advance for your help.
EDIT : To clarify what I need is I need to upload a txt file to a MySQL database, I need a way to read and split(unless there is a better way) the data based on either ",", ,,,,, ,0.00, and still keep fields together that have commas in the field Some Company, LLC. I need to do this with 100+ columns and the file varies from 3000 to 6000 rows. Doing this as a prepared statement is required. I'm not sure if this is possible but I appreciate any input anyone might have on the matter.
EDIT2 : I was able to figure out how to get the messy file sorted out thanks to rpc1. instead of String data[] = line.split("\",\""); I used String data[] = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); I still had to write out each variable to link it to the data[] then write out each statement.setString for each column as well as write the replaceALL("\"", ""); for each column but I got it working and I couldn't find another way to use prepared statements. Thank you for all your help!
You can cycles
for example:
String psQuery = "insert into accounttest"
+ "(account,account_name,address_1,address_2,address_3,..,adrress_n) values"
+ "(?,?,?,?,?,?,..,?)"; //you have to put m=n+2 values
.....
//you can change separator
String data[] = line.replace("\",\"",";").replace("\"","").split(";");
for(int i=0;i<m;i++)
{
if(i<data.length) //if index smaller then array siz
statement.setString(i+1, data[i]);
else
statement.setString(i+1, ""); //put null
}
statement.executeUpdate();
P.S. if your csv file large use batch insert (addBatch())
and use Pattern to split string
Pattern p = Pattern.compile(";","");
p.split(st);
EDIT
Try this split function
private static Pattern pSplit = Pattern.compile("[^,\"']+|\"([^\"]*)\"|'([^']*)'"); //set pattern as global var
private static Pattern pReplace = Pattern.compile("\"");
public static Object[] split(String st)
{
List<String> list = new ArrayList<String>();
Matcher m = pSplit.matcher(st);
while (m.find())
list.add( pReplace.matcher(m.group(0)).replaceAll("")); // Add .replace("\"", "") to remove surrounding quotes.
return list.toArray();
}
for example
intput string: st="\"1212\",\"LL C ,DDD \",\"CA, SPRINGFIELD\",232.11,3232.00";
split on 5 item array:
1212
LL C ,DDD
CA, SPRINGFIELD
232.11
3232.00
EDIT2
this example solves all your problems (even empty values)
private static Pattern pSplit = Pattern.compile(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
public static String[] split2(String st)
{
String[] tokens = pSplit.split(st);
return tokens;
}
I was able to figure out both issues that I was having by this little bit of code. Again, thanks for all of your help!
for (String line = bReader.readLine(); line != null; line = bReader.readLine()) {
//Splitting the content of comma delimited file
String data[] = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
//Iterating through the file and updating the table.
statement = connect.prepareStatement(psQuery);
for (int i =0; i < data.length;i++) {
temp = data[i];
temp = temp.replaceAll("\"", "");
statement.setString(i+1, temp);
}
statement.executeUpdate();
}

Categories