How to thow InvalidNameException in Customer class - java

I have to modify setter method and constructor of the Customer class to throw an InvalidNameException if the length of first_name and last_name field of customer class id less than six and has numbers/special characters.
SAMPLE INPUT : Jack
O/P : javax.naming.InvalidNameException.Customer.setFirstName(Customer.java:67)
I tried this code but it is showing errors.
import java.util.*;
class Customer
{
String name;
public void setFirstName(String name)
{
this.name = name;
char a[] = name.toCharArray();
if(a.length <6){
throw new InvalidNameException();
}
else{
Pattern p = Pattern.compile("[a-z]",Pattern.CASE_INSENSITIVE);
MAtcher m = p.matcher(name);
boolean b = m.find();
if(!b){
throw new InvalidNameException();
}
}
}
}
public class Source
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
Customer cus = new Customer();
cus.setFirstName(name);
}
}

This code works fine.
import java.util.*;
import java.util.regex.*;
import javax.naming.*;
class Customer{
private String firstname;
private String lastname;
public Customer(){
}
public Customer(String firstname, String lastname) throws InvalidNameException{
Pattern pattern = Pattern.compile("[^a-zA-Z0-9]");
Matcher matcherf = pattern.matcher(firstname);
Matcher matcherl = pattern.matcher(lastname);
if((firstname.length() < 6) || (lastname.length() < 6) || matcherf.find() || matcherl.find()){
throw new InvalidNameException(" ");
}else{
this.firstname = firstname;
this.lastname = lastname;
}
}
public void setFirstName(String firstname) throws InvalidNameException{
Pattern pattern = Pattern.compile("[^a-zA-Z0-9]");
Matcher matcherf = pattern.matcher(firstname);
if((firstname.length() < 6) || matcherf.find()){
throw new InvalidNameException(" ");
}else{
this.firstname = firstname;
}
}
public void setLastName(String lastname) throws InvalidNameException{
Pattern pattern = Pattern.compile("[^a-zA-Z0-9]");
Matcher matcherl = pattern.matcher(lastname);
if((lastname.length() < 6) || matcherl.find()){
throw new InvalidNameException(" ");
}else{
this.lastname = lastname;
}
}
public String getFirstName(){
return firstname;
}
public String getLastName(){
return lastname;
}
#Override
public String toString(){
return ("Name = "+firstname+" "+lastname);
}
}
public class Source{
public static void main(String[] args) throws InvalidNameException{
Scanner sc = new Scanner(System.in);
String first = sc.next();
String last = sc.next();
Customer c = new Customer();
c.setFirstName(first);
c.setLastName(last);
}
}

Firstly your code having a compilation issue.
Once you are throwing an exception from method or caller of method thatit should also throws the same exception.
throws explanation
import javax.naming.InvalidNameException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Question2 {
public static void main(String[] args) throws InvalidNameException {
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
Customer cus = new Customer();
cus.setFirstName(name);
}
}
class Customer
{
String name;
public void setFirstName(String name) throws InvalidNameException {
this.name = name;
char a[] = name.toCharArray();
if(a.length <6){
throw new InvalidNameException();
}
else{
Pattern p = Pattern.compile("[a-z]",Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(name);
boolean b = m.find();
if(!b){
throw new InvalidNameException();
}
}
}
}

For achieving this you need to create a custom exception class. also, java is case sensitive so write code in a proper manner. below is an example of a custom exception. The custom exception will help you to create your own exception which should be inherited from the root Exception class.
import java.util.*;
import java.lang.*;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Rextester
{
public static void main(String[] args) throws InvalidNameException {
String name = "mukes";
Customer cus = new Customer();
cus.setFirstName(name);
}
}
class Customer {
String name;
public void setFirstName(String name) throws InvalidNameException {
this.name = name;
char a[] = name.toCharArray();
if (a.length < 6) {
throw new InvalidNameException("Invalid Name");
} else {
Pattern p = Pattern.compile("[a-z]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(name);
boolean b = m.find();
if (!b) {
throw new InvalidNameException("Invalid Name");
}
}
}
}
class InvalidNameException extends Exception {
private static final long serialVersionUID = 1L;
InvalidNameException(String s) {
super(s);
}
}
here is working example. I just removed the scanner here for showing quick output.

Related

Java Isolate comma seperated values in text file

I've been searching for a solution to my problem without any luck. So now I'm asking here for help.
I'm creating "Groups" by the following class:
public class Group {
private String groupID;
private ArrayList<User> usersInGroup;
The User class looks like this:
NOTE: I already have an ArrayList containing all existing Users.
public class User {
private String firstName;
private String lastName;
private String age;
private String gender;
private String usernameID;
private String password;
I'm already adding the groupID field from the "groupData.txt" CSV text file like this:
public static ArrayList<Group> listOfCreatedGroups() throws IOException {
ArrayList<Group> listOfGroups = new ArrayList<>();
FileReader fr = new FileReader("src/groupData.txt");
BufferedReader bfr = new BufferedReader(fr);
String line;
int totalLine = Destination.linesInFile("src/groupData.txt"); //total lines in file
for (int i = 0; i < totalLine; i++) {
line = bfr.readLine();
String[] groupID = line.split(",");
Group temp = new Group();
temp.setGroupID(groupID[0]);
listOfGroups.add(temp);
}
try {
bfr.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
return listOfGroups;
}
The "groupData.txt" file is structured like this:
Line example = groupID,String_1,String2,String3 ... Stringn,\n
groupid,user,user,user,user,user,user,user,
groupid,user,user,user,
groupid,user,user,user,user,user
groupid,user,user
groupid,user,user,user,user
Since I only have the number of users in every group User.usernameID as 1 to n strings in the text file I can't add the whole User object to the Arraylist usersInGroup.
I somehow need to isolate the usernameID's and find the corresponding Users and add them to the ArrayList usersInGroup.
I hope any of you can give me a hint in the right direction. Thanks.
I don't know if this is how you were wanting because I didn't find the user data very specific or even mentioned of how you wanted. But let me know if this is enough
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class Group {
private static String groupID;
private static ArrayList<User> usersInGroup = new ArrayList<User>();
public static void main (String [] args) throws IOException {
addListToGroup(readFile());
}
public static void addListToGroup(ArrayList<ArrayList<String>> list) {
for (int i = 0; i < list.size(); i++) {
groupID = list.get(i).get(0);
for (int x = 0; x < list.get(i).size(); x++) {
User temp = new User(); // change this to however you setup the txt file
// the information from the list is in list.get(i).get(x) in order as in the textfile
temp.setAge(null);
temp.setFirstName(null);
temp.setGender(null);
temp.setLastName(null);
temp.setPassword(null);
temp.setUsernameID(null);
usersInGroup.add(temp);
}
}
}
public static ArrayList<ArrayList<String>> readFile() throws IOException {
List<String> temp = new ArrayList<String>();
Path path = Paths.get("file.txt");
temp = Files.readAllLines(path);
ArrayList<ArrayList<String>> lines = new ArrayList<ArrayList<String>>();
for (int i = 0; i < temp.size(); i++) {
String [] s = temp.get(i).split(",");
ArrayList<String> quickArray = new ArrayList<String>();
for (int x=0; x < s.length; x++) {
quickArray.add(s[x]);
}
lines.add(quickArray);
}
return lines;
}
}
class User {
private String firstName;
private String lastName;
private String age;
private String gender;
private String usernameID;
private String password;
//setters and getters
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getUsernameID() {
return usernameID;
}
public void setUsernameID(String usernameID) {
this.usernameID = usernameID;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

Error while printing out arraylist elements

Here is a small program which adds and print out workers. When calling a method to print I receive an output with identical elements as many times as the number of elements I have added. I cant understand where is my mistake.
public class Radnik {
static List<Radnik> workers = new ArrayList<>();
private String name;
public static void main (String []args) {
Radnik.add();
for(Radnik r : workers) {
System.out.println(r);
}
}
public static void add () {
String name;
String answer;
do {
Scanner s = new Scanner(System.in);
System.out.println("name");
name = s.next();
Radnik f = new Radnik();
workers.add(f);
System.out.println("More");
answer = s.next();
} while (answer.equals("yes"));
}
}
You never set the name to a Radnik.
I would add the constructor Radnik(String name) to initialize name and also add an getter and setter.
System.out.println(r) will only print nonsense because it calls Object.toString(). You have to override toString() or call another method to output something meaningful.
public class Radnik {
static List<Radnik> workers = new ArrayList<>();
private String name;
public Radnik(String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Radnik=[name=\""+name+"\"]";
}
public static void main (String []args) {
Radnik.add();
for(Radnik r : workers) {
System.out.println(r);
}
}
public static void add () {
String name;
String answer;
do{
Scanner s = new Scanner(System.in);
System.out.println("name");
name = s.next();
Radnik f = new Radnik(name);
workers.add(f);
System.out.println("More");
answer = s.next();
} while (answer.equals("yes"));
}
}
public class MainClass{
private static List<Radnik> workers = new ArrayList<>();
public static void main (String []args) {
new MainClass().add();
for(Radnik r : workers) {
System.out.println(r.getName());
}
}
public void add () {
String name;
String answer;
do{
Scanner s = new Scanner(System.in);
System.out.println("name");
name = s.next();
Radnik f = new Radnik();
f.setName(name);
workers.add(f);
System.out.println("More");
answer = s.next();
} while (answer.equals("yes"));
}
public class Radnik {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}

To print the content of object?

What changes should i perform in my code so that it could print the whole family
Have tried toString, i am only getting null. This is just a pretty simple code soo plss help.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
* Created by Alpit on 26-05-2017.
*/
public class Fam {
String father;
String mother;
String sister;
String brother;
String r;
public Fam(String father, String sister, String brother, String mother) {
this.father = father;
this.sister = sister;
this.brother = brother;
this.mother = mother;
}
public String getFather() {
return father;
}
public void setFather(String father) {
this.father = father;
}
}
class add {
public static void main(String args[]) throws IOException {
BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Object> arrayList = new ArrayList<>();
for (int i = 0; i < 2; i++) {
String f = obj.readLine();
String s = obj.readLine();
String b = obj.readLine();
String m = obj.readLine();
Fam fam = new Fam(f, s, b, m);
arrayList.add(fam);
}
for (Object x : arrayList) {
System.out.println(String.valueOf(x));
}
}
}
I am only getting the address of Object, This question can be considered to be a duplicate of this question but i was not able to understand by the solution provided there.
This is what i tried again
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
* Created by Alpit on 26-05-2017.
*/
public class Fam {
String father;
String mother;
String sister;
String brother;
String r;
public Fam(String father, String sister, String brother, String mother) {
this.father = father;
this.sister = sister;
this.brother = brother;
this.mother = mother;
}
public String getFather() {
return father;
}
public void setFather(String father) {
this.father = father;
}
public String toString()
{
return r;
}
}
class add {
public static void main(String args[]) throws IOException {
BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Object> arrayList = new ArrayList<>();
for (int i = 0; i < 2; i++) {
String f = obj.readLine();
String s = obj.readLine();
String b = obj.readLine();
String m = obj.readLine();
Fam fam = new Fam(f, s, b, m);
arrayList.add(fam);
}
for (Object x : arrayList) {
System.out.println(x.toString());
}
}
}
And this returns null.
You can override toString() from Object in your Class Fam.
What String.valueOf(object) does is that it calls the toString() method of class Object (in your case it is Fam).
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
So you would need to override the toString() method in Fam class like this:
public class Fam {
String father;
String mother;
String sister;
String brother;
String r;
public Fam(String father, String sister, String brother, String mother) {
this.father = father;
this.sister = sister;
this.brother = brother;
this.mother = mother;
}
.
.
.
#Override
public String toString() {
return this.father +" "+this.mother +" "+ this.sister +" "+ this.brother;
}
Additionally, you will need to make this change in your main method.
ArrayList<Fam> arrayList = new ArrayList<Fam>();
This way you will get your object printed. (PS: you can change the return format in toString() method.)
Implement your own toString() method. Do something like this:
class Fam {
String father;
String mother;
String sister;
String brother;
String r;
public Fam(String father, String sister, String brother, String mother) {
this.father = father;
this.sister = sister;
this.brother = brother;
this.mother = mother;
}
public String getFather() {
return father;
}
public void setFather(String father) {
this.father = father;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(this.father);
builder.append(" ");
builder.append(this.sister);
builder.append(" ");
builder.append(this.brother);
builder.append(" ");
builder.append(this.mother);
return builder.toString();
}
}
class add {
public static void main(String args[]) throws IOException {
Fam family = new Fam("father", "sister", "brother", "mother");
System.out.println(family.toString());
}
}
I have implmented toString() here. I have used a StringBuilder to demonstrate how you can create your own method, inserting a space between "father, sister, brother, mother".
Running you get:
father sister brother mother
Your ArrayList is given a type parameter of Object. This is fine and all, but when you're trying to print the data in the for loop, you'll need to cast x to Fam. It would be easier to declare it like ArrayList<Fam> arrayList = new ArrayList<>(). Also, you can't simply print objects the way you're trying to do it. Object references hold the value of the memory address. You'll need to manually print the data by using the getter methods in your Fam class. You could also override the toString() method to do this if you want.

Reading a text file (with filechooser) and storing into an ArrayList (each line is a new object inside arraylist

Could someone help me input this data into 3 objects in an ArrayList (one for each player)?
Text file example:
Steve| Barkley| 258| 300
Carl |Johnson |142
Frank|Davidson
Java code:
//couldn't write the normal jfilechoose code above due to space
File playerFile = new File(selectedFile.getAbsolutePath());
Scanner in = new Scanner(playerFile);
String[] playerData; //array to hold data
while (in.hasNext()) {
String data = in.nextLine();
playertData = data.split("\\|");
playerData = Arrays.copyOf(playerData,playerData.length+1);
String firstName = playerData[0];
String lastName = playerData[1];
double playererayear1 = Double.parseDouble(playerData[2]==null?"0":playerData[2]);
double playererayear2 = Double.parseDouble(playerData[3]==null?"0":playerData[3]);
double playererayear3 = Double.parseDouble(playerData[4] == null?"0":playerData[4]);
You can create a separate class for holding information about the Player.
public class Player {
private String firstName;
private String lastName;
private double playerEraYear1;
private double playerEraYear2;
private double playerEraYear3;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public double getPlayerEraYear1() {
return playerEraYear1;
}
public void setPlayerEraYear1(double playerEraYear1) {
this.playerEraYear1 = playerEraYear1;
}
public double getPlayerEraYear2() {
return playerEraYear2;
}
public void setPlayerEraYear2(double playerEraYear2) {
this.playerEraYear2 = playerEraYear2;
}
public double getPlayerEraYear3() {
return playerEraYear3;
}
public void setPlayerEraYear3(double playerEraYear3) {
this.playerEraYear3 = playerEraYear3;
}
}
Now you can parse the file, create a Player object for each of the players and add them to a list
public void parseFile() {
File playerFile = new File(selectedFile.getAbsolutePath());
Scanner in = new Scanner(playerFile);
List<Player> players = new ArrayList<>();
while (in.hasNext()) {
String data = in.nextLine();
String[] playerData = data.split("\\|");
Player p = new Player();
p.setFirstName(playerData[0]);
p.setLastName(playerData[1]);
if (playerData.size >= 3) {
double playererayear1 = Double.parseDouble(playerData[2] == null ? "0" : playerData[2]);
p.setPlayerEraYear1(playererayear1);
}
if (playerData.size >= 4) {
double playererayear2 = Double.parseDouble(playerData[3] == null ? "0" : playerData[3]);
p.setPlayerEraYear2(playererayear2);
}
if (playerData.size >= 5) {
double playererayear3 = Double.parseDouble(playerData[4] == null ? "0" : playerData[4]);
p.setPlayerEraYear3(playererayear3);
}
players.add(p);
}
}
package com.aegle.validator;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
List<Player> playerList = new ArrayList<Player>();
File playerFile = new File("");//Set your file path
Scanner in = new Scanner(playerFile);
while (in.hasNext()) {
String[] data = in.nextLine().split("\\|");
Player player = new Player(data[0], data[1]);
player.setYears(Arrays.copyOfRange(data, 2, data.length));
playerList.add(player);
}
System.out.println(playerList);//Just to test
}
}
class Player {
String firstName;
String lastName;
String[] years;
public Player(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void setYears(String[] years) {
this.years = years;
}
//Introduce getters as you need
#Override
public String toString() {
return "Player{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", years=" + Arrays.toString(years) +
'}';
}
}

Java - Adding 2 objects in an ArrayList

I'm pretty new to programming so I need help. I wanna add the SubjectGrades to the studentList ArrayList. But I think I'm doing the wrong way. What should I do for me to add the SubjectGrades to the ArrayList? Thanks
Here's my partial Main class.
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
private static Scanner in;
public static void main(String[] args) {
ArrayList<Student> studentList = new ArrayList<Student>();
//ArrayList<SubjectGrades> Grades = new ArrayList<SubjectGrades>();
in = new Scanner(System.in);
String search, inSwitch1, inSwitch2;
int inp;
do {
SubjectGrades sGrade = new SubjectGrades();
Student student = new Student();
System.out.println("--------------------------------------");
System.out.println("What do you want to do?");
System.out.println("[1]Add Student");
System.out.println("[2]Find Student");
System.out.println("[3]Exit Program");
System.out.println("--------------------------------------");
inSwitch1 = in.next();
switch (inSwitch1) {
case "1":
System.out.println("Input student's Last Name:");
student.setLastName(in.next());
System.out.println("Input student's First Name:");
student.setFirstName(in.next());
System.out.println("Input student's course:");
student.setCourse(in.next());
System.out.println("Input student's birthday(mm/dd/yyyy)");
student.setBirthday(in.next());
System.out.println("Input Math grade:");
student.subjectGrade.setMathGrade(in.nextDouble());
System.out.println("Input English grade:");
student.subjectGrade.setEnglishGrade(in.nextDouble());
System.out.println("Input Filipino grade:");
student.subjectGrade.setFilipinoGrade(in.nextDouble());
System.out.println("Input Java grade:");
student.subjectGrade.setJavaGrade(in.nextDouble());
System.out.println("Input SoftEng grade:");
student.subjectGrade.setSoftEngGrade(in.nextDouble());
studentList.add(student);
studentList.add(student.setSubjectGrade(sGrade)); //Here it is that I want to add
break;
//end case 1
Here is my Student Class.
package santiago;
public class Student {
private String lastName;
private String firstName;
private String course;
private String birthday;
SubjectGrades subjectGrade = new SubjectGrades();
public SubjectGrades getSubjectGrade() {
return subjectGrade;
}
public void setSubjectGrade(SubjectGrades subjectGrade) {
this.subjectGrade = subjectGrade;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
And my SubjectGrades class
package santiago;
public class SubjectGrades{
Double mathGrade, englishGrade, filipinoGrade, javaGrade, softEngGrade, weightedAverage;
public Double getMathGrade() {
return mathGrade;
}
public void setMathGrade(Double mathGrade) {
this.mathGrade = mathGrade;
}
public Double getEnglishGrade() {
return englishGrade;
}
public void setEnglishGrade(Double englishGrade) {
this.englishGrade = englishGrade;
}
public Double getFilipinoGrade() {
return filipinoGrade;
}
public void setFilipinoGrade(Double filipinoGrade) {
this.filipinoGrade = filipinoGrade;
}
public Double getJavaGrade() {
return javaGrade;
}
public void setJavaGrade(Double javaGrade) {
this.javaGrade = javaGrade;
}
public Double getSoftEngGrade() {
return softEngGrade;
}
public void setSoftEngGrade(Double softEngGrade) {
this.softEngGrade = softEngGrade;
}
public Double getWeightedAverage(){
weightedAverage = ((mathGrade + englishGrade + filipinoGrade + javaGrade + softEngGrade)*3) / 15;
return weightedAverage;
}
public String getScholarStatus(){
String status = "";
if(weightedAverage <= 1.5) {
status = "full-scholar";
} else if (weightedAverage <= 1.75){
status = "half-scholar" ;
} else {
status = "not a scholar";
}
return status;
}
}
Your mistake:
studentList.add(student);
studentList.add(student.setSubjectGrade(sGrade));
You are adding the student, then trying to add a void. The return value of setSubjectGrade is void, so nothing will be added:
Just do:
student.setSubjectGrade(sGrade);
studentList.add(student);
Where sGrade is an Object of type SubjectGrades, which was populated in the same way
student.subjectGrade.setSoftEngGrade(in.nextDouble()); was populated.
Use
ArrayList <SubjectGrades> list;
in student class instead SubjectGrades subjectGrade = new SubjectGrades();.
and generate getters and setters
Just remove this line:
studentList.add(student.setSubjectGrade(sGrade)); //Here it is that I want to add
The way you have done it, the student object already has the subjectGrade attribute with its values set.
You can access it with studentList.get(0).getSubjectGrade()

Categories

Resources