How to get variables from exception code block - java

I want to get user1.name variable from public static void FileRead()to private void jButton1ActionPerformed but It doesn't read user1.name. Can you explain me how can I use that variable.
public static class Users {
public String name;
public String password;
Users(String name1, String password1) {
name = name1;
password = password1;
}
}
public static void FileRead() {
try {
BufferedReader in = new BufferedReader(new FileReader("C:/Users/B_Ali/Documents/NetBeansProjects/JavaApplication20/UserNamePassword.txt"));
String[] s1 = new String[5];
String[] s2 = new String[5];
int i = 0;
while ((s1[i] = in.readLine()) != null) {
s1[i] = s2[i];
i = i + 1;
if (i == 1) {
Users user1 = new Users(s2[0], s2[1]);
}
else if (i == 3) {
Users user2 = new Users(s2[2], s2[3]);
}
else if (i == 5) {
Users user3 = new Users(s2[4], s2[5]);
}
}
in.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(LoginScreen.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(LoginScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(null, user1.name);
// TODO add your handling code here:
}
where should I declare it?
Edit: if i declare it as you said before. It becomes meaningless because i want to use user1.name which is defined in FileRead().

Declare it global.
Users user1;
public static class Users {
public String name;
public String password;
Users(String name1, String password1) {
name = name1;
password = password1;
}
public String getName()
{ return this.name;
}
public String getPassword()
{return this.password;
}
}
Users user1, user2;
public static void FileRead() {
try {
BufferedReader in = new BufferedReader(new FileReader("C:/Users/B_Ali/Documents/NetBeansProjects/JavaApplication20/UserNamePassword.txt"));
String[] s1 = new String[5];
String[] s2 = new String[5];
int i = 0;
while ((s1[i] = in.readLine()) != null) {
s1[i] = s2[i];
i = i + 1;
if (i == 1) {
Users user1 = new Users(s2[0], s2[1]);
}
else if (i == 3) {
Users user2 = new Users(s2[2], s2[3]);
}
else if (i == 5) {
Users user3 = new Users(s2[4], s2[5]);
}
}
in.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(LoginScreen.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(LoginScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(null, user1.getName());
// TODO add your handling code here:
}

You need to declare the variables you need outside of the try clause like:
String global = null;
try{
global = "abc";
throw new Exception();
}
catch(Exception e){
if (global != null){
//your code
}
}

Related

Range in File Java

I have a problem. So I have a txt file, where is some datas. I have a class PatientView with method readInRange(PatientModel pm, Integer a, Integer b) and this class PatientModel with getter methods and one private method writeToFile() and I have a problem with this method readInRange cause I don't know how to output information between two numbers(this range must work with mediacalCard field). So what should I do to display the range using mediacalCard field? Should I make this mediacalCard an array? Please help me.
This is my code:
Class PatientView:
public void readInRange(PatientModel pm, Integer a, Integer b) {
try {
String str;
BufferedReader bufferedReader = new BufferedReader(new FileReader("test.txt"));
for (int i = a; i < b+1; i++) {
while ((str = bufferedReader.readLine()) != null) {
System.out.println(str);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Class PatientModel and his getter methods and write to file method:
public Integer getId() {
return Id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getPatronymic() {
return patronymic;
}
public String getAddress() {
return Address;
}
public Integer getNumberPhone() {
return numberPhone;
}
public Integer getMedicalCard() {
return medicalCard;
}
public String getDiagnose() {
return diagnose;
}
private void writeToFile() {
try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("test.txt", true))) {
bufferedWriter.write(String.format("%1d, %10s, %10s, %10s, %10s, %10d, %10d, %10s", Id, firstName,
lastName, patronymic, Address, numberPhone, medicalCard, diagnose));
bufferedWriter.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
Thanks everybody who tried to help me. This is how I solved this problem
My code:
public void readInRange(PatientModel pm, Integer low, Integer high) {
String[] splitdata;
String sixcol; Integer num=0;
try {
String str;
BufferedReader bufferedReader = new BufferedReader(new FileReader("test.txt"));
while ((str = bufferedReader.readLine()) != null) {
splitdata = str.split("[,\t]");
sixcol = splitdata[0];
Integer aa = num.valueOf(sixcol);
if(aa > low && aa < high) {
System.out.println(str);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

FileNotFoundException in Netbeans on a Web Service running on Glass Fish server

This the event handler when the button is clicked on GUI. Implements the declared
#WebMethod in class.
private void btn_loginActionPerformed(java.awt.event.ActionEvent evt) {
int result;
String username = us_textField.getText();
String password = new String(pw_textField.getPassword());
try {
result = employeeLogin(username, password);
} catch (IOException_Exception ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
result = 0;
} catch (FileNotFoundException_Exception ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
result = 0;
} catch (ClassNotFoundException_Exception ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
result = 0;
}
if (result == 0) {
lbl_loginStatus.setText("Invalid Inputs");
} else if (result == 1) {
lbl_loginStatus.setText("Username and password does not match!");
} else {
lbl_loginStatus.setText("Login Successful!");
new Choose().setVisible(true);
this.dispose();
}
}
This how the web service is declared in the same class.
private static int employeeLogin(java.lang.String username, java.lang.String password) throws IOException_Exception, FileNotFoundException_Exception, ClassNotFoundException_Exception {
ws_employee.CWWsEmployee_Service service = new ws_employee.CWWsEmployee_Service();
ws_employee.CWWsEmployee port = service.getCWWsEmployeePort();
return port.employeeLogin(username, password);
}
This is the Web Service Code.
EmployeeMainController controller = new EmployeeMainController();
#WebMethod(operationName = "EmployeeLogin")
public int EmployeeLogin(#WebParam(name = "username") String username, #WebParam(name = "password") String password) throws IOException, FileNotFoundException, ClassNotFoundException {
//TODO write your implementation code here:
return controller.EmployeeLogin(username, password);
}
This is the EmployeeLogin(username, password) method declared in EmployeeMainController.java class. During this method a ArrayList initialized by LoadData() method.
public int EmployeeLogin(String username, String password) throws FileNotFoundException, IOException, ClassNotFoundException {
// Loading to the array list from the text file.
ArrayList<EmployeeStruct> loadArray = new ArrayList<EmployeeStruct>();
loadArray = LoadList();
for (EmployeeStruct val : loadArray) {
if (val.getEmpUsername().equals(username) && val.getEmpPassword().equals(password)) {
return 2;
} else if (val.getEmpUsername().equals(username) || val.getEmpPassword().equals(password)) {
return 1;
}
}
return 0;
}
The LoadData() method is declared as below. This is simply a deserializing method. A have initialized the file path as this public static String filename = "cw_employeeData.txt";
public ArrayList<EmployeeStruct> LoadList() throws FileNotFoundException, IOException, ClassNotFoundException {
ArrayList<EmployeeStruct> employeeList = new ArrayList<EmployeeStruct>();
File file = new File(filename);
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
while (true) {
EmployeeStruct x = (EmployeeStruct) ois.readObject();
// System.out.println(x.toString());
employeeList.add(x);
}
} catch (EOFException e) {
// TODO Auto-generated catch block
System.out.println("Completed reading from the file " + filename);
}
// employeeList.add(admin);
return employeeList;
}
But when the code is executed, ws_employee.FileNotFoundException_Exception: cw_employeeData.txt (The system cannot find the file specified)... error comes in the console.
Even I have located the cw_employeeData.txt file in the root directory alongside the Root/src folder.

how to remove 503 exceptions in java

I have a list of names in the form of a CSV and I am up for google searching those names using java. But the problem that i am facing is that when i initially run the code i am able to search the query but in the middle of the code the code starts to throw 503 exceptions and when i again run the code it starts throwing 503 exceptions from the very beginning.Here is the code that i am using.
public class ExtractInformation
{
static String firstname,middlename,lastname;
public static final int PAGE_NUMBERS = 10;
public static void readCSV()
{
boolean first = true;
try
{
String splitBy = ",";
BufferedReader br = new BufferedReader(new FileReader("E:\\KOLDump\\names.csv"));
String line = null;
String site = null;
while((line=br.readLine())!=null)
{
if(first)
{
first = false;
continue;
}
String[] b = line.split(splitBy);
firstname = b[0];
middlename = b[1];
lastname = b[2];
String name = null;
if(middlename == null || middlename.length() == 0)
{
name = firstname+" "+lastname+" OR "+lastname+" "+firstname.charAt(0);
}
else
{
name = firstname+" "+lastname+" OR "+lastname+" "+firstname.charAt(0)+" OR "+firstname+" "+middlename.charAt(0)+". "+lastname;
}
BufferedReader brs = new BufferedReader(new FileReader("E:\\KOLDump\\site.csv"));
while((site = brs.readLine()) != null)
{
if(first)
{
first = false;
continue;
}
String [] s = site.split(splitBy);
String siteName = s[0];
siteName = (siteName.replace("www.", ""));
siteName = (siteName.replace("http://", ""));
getDataFromGoogle(name.trim(), siteName.trim());
}
brs.close();
}
//br.close();
}
catch(Exception e)
{
System.out.println("unable to read file...some problem in the csv");
}
}
public static void main(String[] args)
{
readCSV();
}
private static void getDataFromGoogle(String query,String siteName)
{
Set<String> result = new HashSet<String>();
String request = "http://www.google.co.in/search?q="+query+" "+siteName;
try
{
Document doc = Jsoup.connect(request).userAgent("Chrome").timeout(10000).get();
Element query_results = doc.getElementById("ires");
Elements gees = query_results.getElementsByClass("g");
for(Element gee : gees)
{
Element h3 = gee.getElementsByTag("h3").get(0);
String annotation = h3.getElementsByTag("a").get(0).attr("href");
if(annotation.split("q=",2)[1].contains(siteName))
{
System.out.println(annotation.split("q=",2)[1]);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
any suggestions on how to remove this exceptions from the code would really be helpful.
If you wait a little do the 503's go away? If so, then you're probably being rate-limited by Google. https://support.google.com/gsa/answer/2686272?hl=en
You may need to put some kind of delay between requests.

DAO initialising integer to 0 when loading

When my system loads the text file with the data already in it,it always initialises the integers for restaurantTables and restaurantSeats to 0? How do I stop this from happening and keep the figures assigned when adding to the system?
Here is the code which changes it back to 0:
public class TextRestaurantDAO extends RestaurantDAO {
static final char DELIMITER=':';
#Override
public List<Restaurant> loadRestaurants(Path path) {
List<Restaurant> restaurants = new ArrayList<>();
try (Scanner s = new Scanner(new BufferedReader(new FileReader(path.toString())))) {
s.useDelimiter(Character.toString(DELIMITER));
Restaurant r;
int restaurantId, restaurantTables, restaurantSeats;
String restaurantName, restaurantLocation;
while (s.hasNext()) {
if (s.hasNextInt()) {
restaurantId = s.nextInt();
}
else {
restaurantId = 0;
}
if (s.hasNextInt()) {
restaurantTables = s.nextInt();
}
else {
restaurantTables = 0;
}
if (s.hasNextInt()) {
restaurantSeats = s.nextInt();
}
else {
restaurantSeats = 0;
}
restaurantName = s.next();
restaurantLocation = s.next();
s.nextLine();
r = new Restaurant(restaurantId, restaurantName, restaurantLocation, restaurantTables, restaurantSeats);
restaurants.add(r);
}
s.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(TextCustomerDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return restaurants;
}
#Override
public void storeRestaurants(Path path, List<Restaurant> restaurants) {
try (PrintWriter output = new PrintWriter(path.toFile())) {
for (Restaurant r:restaurants) {
output.println(toFileString(r));
}
output.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(TextRestaurantDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String toFileString(Restaurant r) {
return Integer.toString(r.getRestaurantId()) + DELIMITER +
r.getRestaurantName() + DELIMITER +
r.getRestaurantLocation() + DELIMITER +
r.getRestaurantTables() + DELIMITER +
r.getRestaurantSeats() + DELIMITER;
}
}
If you could help it would be much appreciated.
Here is an example of what the text file has before it loads:
1:Riva:Bothwell:31:78:
After it Loads:
1:Riva:Bothwell:0:0:
How do i stop this from happening?
Thankyou
if you require more code please ask

Where to implement onSave and onLoad functions to create serializable file

I've created these two functions and added them into an action listener within a button . The aim is to create a serialized file and write what is in the Jlist to the file. When the program is closed , the jlist should be populated with what is in the serialized file. For some reason it isn't working. Can anyone see what is wrong?
Here is the code:
JButton btnAdd = new JButton("Add"); // Setting what is written on the button
btnAdd.addActionListener(new ActionListener() { // implementing an action listener
public void actionPerformed(ActionEvent arg0) {
patientname = textField.getText(); // Getting the patient name from the textfield
patientaddress = textField_1.getText();
patientphone = textField_2.getText();
textField.setText(""); // Setting the textfield to be blank so that the user can input there name address etc..
textField_1.setText("");
textField_2.setText("");
patientid = patientid + 1;//Implementing the id to add 1 every time another id is added
Patient patient = new Patient(patientname, patientaddress, patientphone, patientid); // Populating the array list patientlist with the users input
patientList.add(patient); // Adding the patient's details to the patientlist
patientListModel.addElement(patient); // adds the patient's details to the list model
}
public void onSave(List<Patient> PatientList) {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File("PatientList.ser")));
out.writeObject(PatientList);
out.flush();
}
catch (IOException e) {
// handle exception
}
finally {
if (out != null) {
try {
out.close();
}
catch (IOException e) {
// handle exception
}
}
}
}
public List<Patient> onLoad() {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(new File("PatientList.ser")));
return (List<Patient>) in.readObject();
}
catch (IOException e) {
// handle exception
}
catch (ClassNotFoundException e) {
// handle exception
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException e) {
// handle exception
}
}
}
return null;
}
});
btnAdd.setBounds(0, 86, 65, 23);
contentPane.add(btnAdd);
/////////////////
Here is my patient class :
public class Patient {
public String patientName;
public String patientAddress;
public String patientPhone;
public int patientID;
public Patient(String patientname, String patientaddress, String patientphone,int patientid){
patientName = patientname;
patientAddress = patientaddress;
patientPhone = patientphone;
patientID = patientid;
}
public String setName(String patientname){
return patientName = patientname;
}
public String getName(){
return patientName;
}
public String setAddress(String patientaddress){
return patientAddress = patientaddress;
}
public String getAddress(){
return patientAddress;
}
public String setPhoneNum(String patientphone){
return patientPhone = patientphone;
}
public String getPhoneNum(){
return patientPhone;
}
public int setID(int patientid){
return patientID = patientid;
}
public int getID(){
return patientID;
}
public String toString() { // Printing the patient's details to the scroll pane
return "Patient Name: " + patientName + ", PatientAddress: "
+ patientAddress + ", PatientPhone: " + patientPhone
+ ", patientID: " + patientID +"" ;
}
}

Categories

Resources