try/exception for integer or double or string - java

How to differentiate the integer and double. Example if i wanted to get integer and verify it. if it is integer then output "YOU are correct" else "You entred wrong. try again".
import javax.swing.*;
public class InputExceptions {
private static int inputInt;
private static double inputDouble;
public static int inputInt() {
boolean inputOK = false;
while (inputOK == false) {
inputInt = Integer.parseInt(JOptionPane.showInputDialog("Enter Integer"));
try {
inputOK = true;
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"*** ERROR: VALUE ENTERED NOT INTEGER ***");
}
} return inputInt;
}
public static void main(String[] args) {
JOptionPane.showMessageDialog(null,"*** INTEGER is correct Input: " + inputInt() + " ***");
}
}

Related

How to check if input meets the criteria?

Part of my assignment was to have the user input an Eployee Id between 0-9 and contains a letter between A-M(ex. 999-M), and then if it doesn't meet one of the criteria it is supposed to throw an error code using an exception class. I figured out how to check the Id, but only works with the number part. I have no clue how to check if the input also meets the letter criteria. I know it has something to do with employee Id being an int and not a string, but when I attempted to fix it. I almost messed my whole code up. Any help would be appreciated.
My main code:
package payrollexceptions;
import java.util.Scanner;
public class PayRollExceptions
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Payroll employee = new Payroll();
String name;
int employeeId;
double payRate;
System.out.print("Enter the employee's name: ");
employee.setName(keyboard.nextLine());
System.out.print("Enter employee number, (ex. 999-M): ");
employee.setEmployeeId(keyboard.nextInt());
System.out.print("Enter the employee's hourly rate: ");
employee.setPayRate(keyboard.nextDouble());
System.out.print("Enter the number of hours the employee has worked: ");
employee.setHours(keyboard.nextInt());
System.out.println("\n" + employee.getName());
System.out.println("-----------");
System.out.println("ID: " + employee.getEmployeeId());
System.out.println("Pay rate: $" + employee.getPayRate());
System.out.println("Hours worked: $" + employee.getHours());
System.out.println("Gross pay: $" + employee.getGrossPay());
}
}
The code that involves setting the employeeId:
package payrollexceptions;
public class Payroll
{
private int employeeId, hours;
private double payRate;
private String name;
public Payroll() {}
public Payroll(String name, int employeeId, double payRate)
{
try
{
if(name == "")
{
throw new EmptyNameException();
}
setName(name);
if(employeeId <= 0)
{
throw new InvalidEmployeeIdException();
}
setEmployeeId(employeeId);
if(payRate < 0 || payRate > 25)
{
throw new InvalidPayRateException();
}
setPayRate(payRate);
}
catch(EmptyNameException e)
{
System.out.println("Error: the employee's name cannot be blank");
System.exit(1);
}
catch(InvalidEmployeeIdException e)
{
System.out.println("Error: the employee's id must be above 0");
System.exit(1);
}
catch(InvalidPayRateException e)
{
System.out.println("Error: the payrate must not be negative nor exceed 25");
System.exit(1);
}
setEmployeeId(employeeId);
setPayRate(payRate);
}
public double getGrossPay()
{
return payRate * hours;
}
public int getEmployeeId()
{
return employeeId;
}
public int getHours()
{
return hours;
}
public double getPayRate()
{
return payRate;
}
public String getName()
{
return name;
}
public void setEmployeeId(int employeeId)
{
try
{
if(employeeId <= 0)
{
throw new InvalidEmployeeIdException();
}
this.employeeId = employeeId;
}
catch(InvalidEmployeeIdException e)
{
System.out.println("Error: Numericals in ID must be between 0-9 and letters must be between A-M");
System.exit(1);
}
}
public void setHours(int hours)
{
try
{
if(hours < 0 || hours > 84)
{
throw new InvalidHoursException();
}
this.hours = hours;
}
catch(InvalidHoursException e)
{
System.out.println("Error: Hours Cannot be negative or greater than 84");
System.exit(1);
}
}
public void setPayRate(double payRate)
{
try
{
if(payRate < 0 || payRate > 25)
{
throw new InvalidPayRateException();
}
this.payRate = payRate;
}
catch(InvalidPayRateException e)
{
System.err.println("Error: Hourly Rate Cannot be negative or greater than 25");
System.exit(1);
}
}
public void setName(String name)
{
try
{
if(name.isEmpty())
{
throw new EmptyNameException();
}
this.name = name;
}
catch(EmptyNameException e)
{
System.out.println("Error: the employee's name cannot be blank");
System.exit(1);
}
}
}

Using methods in array list from TUI class

I'm trying to access an (add) method in my arrayList class from a TUI class, which will add a user to my arrayList.
This is my TUI class.
import java.util.ArrayList;
import java.util.Scanner;
public class BorrowerTUI
{
private BorrowerList borrowerList;
private Scanner myScanner;
public BorrowerTUI()
{
myScanner = new Scanner(System.in);
BorrowerList borrowerList = new BorrowerList();
}
public void menu()
{
int command = -1;
while (command != 0)
{
displayMenu();
command = getCommand();
execute (command);
}
}
private void displayMenu()
{
System.out.println( "Options are" );
System.out.println( "Enter 1" );
System.out.println( "Enter 2" );
System.out.println( "Enter 3" );
System.out.println( "Enter 4" );
}
private void execute( int command)
{
if ( command == 1)
addBorrower();
else
if ( command == 2 )
getNumberOfBorrowers();
else
if ( command == 3)
quitCommand();
else
if ( command == 4)
quitCommand();
else
if ( command == 5)
quitCommand();
else
System.out.println("Unknown Command");
}
private int getCommand()
{
System.out.print ("Enter command: ");
int command = myScanner.nextInt();
myScanner.nextLine();
return command;
}
public void getNumberOfBorrowers()
{
int command = myScanner.nextInt();
System.out.println("We have" + borrowerList.getNumberOfBorrowers() + "borrowers");
}
public void quitCommand()
{
int command = myScanner.nextInt();
System.out.println("Application Closing");
System.exit(0);
}
public void addBorrower()
{
Borrower borrower = new Borrower();
borrowerList.addBorrower(borrower);
}
}
This is my array list class.
import java.util.ArrayList;
public class BorrowerList
{
private ArrayList<Borrower> borrowers;
public BorrowerList()
{
borrowers = new ArrayList<Borrower>();
}
public void addBorrower(Borrower borrower)
{
borrowers.add(borrower);
}
public int getNumberOfBorrowers()
{
return borrowers.size();
}
public boolean getBorrower(String libraryNumber)
{
for(Borrower borrower : borrowers)
borrower.getLibraryNumber();
return true;
}
public void getBorrower(int borrowerEntry)
{
if (borrowerEntry < 0)
{
System.out.println("Negative entry: " + borrowerEntry);
}
else if (borrowerEntry < getNumberOfBorrowers())
{
Borrower borrower = borrowers.get(borrowerEntry);
borrower.printBorrowerDetails();
}
else
{
System.out.println("No such entry: " + borrowerEntry);
}
}
public void getAllBorrowers()
{
for(Borrower borrower : borrowers)
{
borrower.printBorrowerDetails();
System.out.println();
}
}
public void removeBorrower(int borrowerEntry)
{
if(borrowerEntry < 0)
{
System.out.println("Negative entry :" + borrowerEntry);
}
else if(borrowerEntry < getNumberOfBorrowers())
{
borrowers.remove(borrowerEntry);
}
else
{
System.out.println("No such entry :" + borrowerEntry);
}
}
public boolean removeBorrower(String libraryNumber)
{
int index = 0;
for (Borrower borrower: borrowers)
{
if (libraryNumber.equals(borrower.getLibraryNumber()))
{
borrowers.remove(index);
return true;
}
index++;
}
return false;
}
public int search(String libraryNumber)
{
int index = 0;
for (Borrower borrower : borrowers)
{
if (libraryNumber.equals(borrower.getLibraryNumber()))
{
return index;
}
else
{
index++;
}
}
return -1;
}
}
But for some reason when I try to link this method in my TUI class using the code at the top, it is returning the error: ") expected after 'User'"
Can somebody help, thanks.
It is returning an error because the method addUser is expecting a User object as input. In your call of the function, you gave it the User type as if you were declaring a method. Try passing in just a user object like so:
public void addUser()
{
User user = new User();
userList.addUser(user);
}

TreeMap floorEntry function not working with integer values(Treemap defined as long)

I am trying to perform an interval based search where I am loading from a file and trying to find the interval where my ipaddress lies. Below is my code. This code only works for long but not working for the ip address whose integer version is not a long number.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class RangeBasedSearchAsn {
public static class AsnInfo {
private long asn;
private String ipSubnet;
private String isp;
#Override
public String toString() {
return "Here are the details:\n"
+ this.asn + " " + this.ipSubnet + " " + this.isp ;
}
public AsnInfo(long asn, String ipSubnet, String isp) {
this.asn = asn;
this.ipSubnet = ipSubnet;
this.isp = isp;
}
public long getAsn() {
return asn;
}
public void setAsn(long asn) {
this.asn = asn;
}
public String getIpSubnet() {
return ipSubnet;
}
public void setIpSubnet(String ipSubnet) {
this.ipSubnet = ipSubnet;
}
public String getIsp() {
return isp;
}
public void setIsp(String isp) {
this.isp = isp;
}
}
public static class Range {
private long upper;
private AsnInfo asnInfo;
public Range(long upper, AsnInfo value) {
this.upper = upper;
this.asnInfo = value;
}
public long getUpper() {
return upper;
}
public void setUpper(long upper) {
this.upper = upper;
}
public AsnInfo getValue() {
return asnInfo;
}
public void setValue(AsnInfo value) {
this.asnInfo = value;
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
long key = 848163455L;
NavigableMap<Long, Range> asnTreeMap = new TreeMap<>();
System.out.println(System.currentTimeMillis());
System.out.println("Loading isp Map.");
FileInputStream inputStream = null;
Scanner sc = null;
try {
inputStream = new FileInputStream("C:\\Talend\\TalendTestArea\\rbl_ipv4_zone.txt");
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
StringTokenizer st = new StringTokenizer(line, ";");
while (st.hasMoreTokens() && st.countTokens() == 7) {
st.nextToken();
st.nextToken();
long token1 = Long.parseLong(st.nextToken());
System.out.println("here is token1:" + token1);
long token2 = Long.parseLong(st.nextToken());
System.out.println("here is token1:" + token2);
long token3 = Long.parseLong(st.nextToken());
System.out.println("here is token1:" + token3);
asnTreeMap.put(token1, new Range(token2, new AsnInfo(token3,st.nextToken(),st.nextToken())));
}
}
if (sc.ioException() != null) {
throw sc.ioException();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
System.out.println("Loading Over.");
System.out.println(System.currentTimeMillis());
System.out.println("Starting Lookup.");
long[] ips = {30503936L};
for(int i = 0 ; i < ips.length;i++){
System.out.println(asnTreeMap.size());
Map.Entry<Long, Range> entry = asnTreeMap.floorEntry(ips[i]);
if (entry == null) {
System.out.println("Value not valid");
} else if (key <= entry.getValue().upper) {
System.out.println("Carrier = " + entry.getValue().asnInfo.toString() + "\n");
} else {
System.out.println("Not found");
}
System.out.println(System.currentTimeMillis());
}
}
}
Below is the output run: 1432262970924 Loading isp Map. Loading
Over. 1432262975089 Starting Lookup. 540772 Not found
1432262975089\n BUILD SUCCESSFUL (total time: 4 seconds)
An IP address is a 32-bit unsigned integer. In Java, ints are 32-bit signed integers.
If you use a signed int to represent an IP address, you'll have to accommodate into your code the fact that the upper half of all IP addresses will in fact be negative.
Java 7 doesn't provide built-in support for unsigned ints, so you'd have to implement the desired behavior or find another class wrapper (from somewhere) for Integer that fulfills your need.
Java 8 introduced methods in the Integer class for comparing ints as unsigned. See https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html for the appropriate methods.

DeSerialized Object containing ArrayList has all null values

Hopefully someone can provide some insight on this issue. I have created an instance of an object that contains an ArrayList of information (username, password, password hint). I am trying to serialize the object. It looks like it is serializing properly, but when I restart the project to deserialize, it returns null values in the ArrayList. Why is it returning null values for the ArrayList objects?
Driver Class:
import java.io.Serializable;
public class TestingDriver implements Serializable{
private static final long serialVersionUID = 12345L;
private static TestingAccount users = new TestingAccount();
public static void main(String[] args) {
int foreverLoop = 0;
users = DeSerialize.main();
while (foreverLoop < 1) {
int selection = users.displayMainMenu();
if (selection == 1) {
users.listUsers();
}
else if (selection == 2) {
users.addUser();
}
else if (selection == 3) {
users.deleteUser();
}
else if (selection == 4) {
users.getPasswordHint();
}
else if (selection == 5) {
Serialize.main(users);
System.exit(0);
}
else {
System.out.println("That option does not exist. Please try again.");
}
}
}
}
TestingUser Class (objects of this class will populate the ArrayList):
import java.io.Serializable;
public class TestingUser extends UserAccount implements Serializable, Comparable <TestingUser> {
private static final long serialVersionUID = 12345L;
public TestingUser(String username, String password, String passwordHint) {
super(username, password, passwordHint);
}
public TestingUser() {
}
#Override
public void getPasswordHelp() {
System.out.println("");
System.out.println("Password hint: " + passwordHint);
System.out.println("");
}
#Override
public int compareTo(TestingUser otherAccount) {
if (this.username.compareToIgnoreCase(otherAccount.username) < 0) {
return -1;
}
else if (this.username.compareToIgnoreCase(otherAccount.username) > 0) {
return 1;
}
else {
return 0;
}
}
}
TestingAccount class (calling this class creates an object that contains the ArrayList):
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Scanner;
public class TestingAccount implements Serializable {
private static final long serialVersionUID = 12345L;
public ArrayList<TestingUser> userList;
private String username;
private String password;
private String passwordHint;
public TestingAccount() {
userList = new ArrayList<TestingUser>();
}
public void listUsers() {
for (int i=0; i<this.userList.size(); i++) {
System.out.println(this.userList.get(i));
}
}
#SuppressWarnings("resource")
public void addUser() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a username: ");
username = input.next();
TestingUser tempAccount = new TestingUser(username, null, null);
if (this.userList.contains(tempAccount) == true) {
System.out.println("This user already exists.");
}
else {
System.out.println("Please enter a password: ");
password = input.next();
System.out.println("Please enter a password hint: ");
passwordHint = input.next();
tempAccount.password = password;
tempAccount.passwordHint = passwordHint;
this.userList.add(tempAccount);
System.out.println("Account " + tempAccount.username + " has been added.");
}
}
#SuppressWarnings("resource")
public void deleteUser() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the username to be deleted: ");
username = input.next();
TestingUser tempAccount = new TestingUser(username, null, null);
if (this.userList.contains(tempAccount) == true) {
int actIndex = this.userList.indexOf(tempAccount);
System.out.println("Please enter the password: ");
password = input.next();
tempAccount.password = password;
boolean passwordGood = this.userList.get(actIndex).CheckPassword(tempAccount);
int accountIndex = this.userList.indexOf(tempAccount);
tempAccount = this.userList.get(accountIndex);
if (passwordGood == true) {
this.userList.remove(actIndex);
System.out.println("The account has been deleted.");
}
else {
System.out.println("The password is not correct.");
}
}
else {
System.out.println("The account does not exist.");
}
}
#SuppressWarnings("resource")
public void getPasswordHint() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a username: ");
username = input.next();
TestingUser tempAccount = new TestingUser(username, null, null);
if (this.userList.contains(tempAccount) == true) {
int actIndex = this.userList.indexOf(tempAccount);
tempAccount = this.userList.get(actIndex);
System.out.println("The password hint isL: " + tempAccount.passwordHint);
}
else {
System.out.println("The account does not exist.");
}
}
#SuppressWarnings({ "resource" })
public int displayMainMenu() {
int selection = 0;
Scanner input = new Scanner(System.in);
System.out.println("");
System.out.println("System Menu:");
System.out.println("1. List Users");
System.out.println("2. Add User");
System.out.println("3. Delete User");
System.out.println("4. Get Password Hint");
System.out.println("5. Quit");
System.out.println("");
System.out.println("What would you like to do?");
selection = input.nextInt();
return selection;
}
}
Serialize class:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Serialize {
public static void main(TestingAccount users) {
try {
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("serialize"));
oos.writeObject(users);
oos.close();
} catch (FileNotFoundException e1) {
System.err.println("File not found.");
} catch (IOException e2) {
System.err.println("Unable to serialize.");
e2.printStackTrace();
}
}
}
Deserialize class:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class DeSerialize {
public static TestingAccount main() {
TestingAccount deSerialize = null;
try {
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("serialize"));
deSerialize = (TestingAccount) ois.readObject();
ois.close();
} catch (FileNotFoundException e1) {
System.err.println("Unable to open file.");
} catch (IOException e2) {
System.err.println("Could not de-serialize.");
e2.printStackTrace();
} catch (ClassNotFoundException e3) {
System.err.println("Could not cast to class TestingAccount.");
}
return deSerialize;
}
}
It looks like UserAccount isn'tSerializable. So when you serialize the derived TestingUser class, none of the UserAccount data gets serialized. See Object Serialization Specification #2.1.13(a). TestingUser doesn't have any instance state of its own to serialize.
The solution is to make UserAccount implement Serializable.
Not sure why this comes as a surprise.

Trouble outputting data from a loaded text file

I have a program that is supposed to load a text file and display/sort the data, however the data is not being displayed at all. Any ideas as to what I'm doing wrong? I have to stick with 1.4.2 Java only.
Here is the code:
import java.io.*;
import java.util.StringTokenizer;
class NewClass {
private static int quantity;
private static String[] name;
public static void main(String args[]) throws Exception {
InputStreamReader kb = new InputStreamReader(System.in);
BufferedReader in;
in = new BufferedReader(kb);
String buffer;
char choice;
boolean fileread=false;
int[]number=new int[quantity];
String[]name=new String[quantity];
String sorttype="";
do
{ //Setup Menu
choice=menu(in);
if(choice=='E')
{
if(fileread)
System.out.println("Data already has been entered");
else
{
fileread=true;
getdata(number,name);
}
}
else if(choice=='D')
{
if(fileread)
display(number,name,in);
else
System.out.println("Must enter data before it is displayed");
}
else if(choice=='S')
{
if(fileread)
sorttype=sort(number,name,in);
else
System.out.println("Must enter data before it is sorted");
}
} while(choice!='X');
}
//Sort Data
public static void sortint(int[] number, String[] name)
{
int i,j;
for(i=0;i<quantity-1;i++)
for(j=i+1;j<quantity;j++)
if(number[i]>number[j])
{
swap(number,i,j);
swap(name,i,j);
}
}
public static void sortstring(String[] name, int[] number)
{
int i,j;
for(i=0;i<quantity-1;i++)
for(j=i+1;j<quantity;j++)
if(name[i].compareToIgnoreCase(name[j])>0)
{
swap(number,i,j);
swap(name,i,j);
}
}
public static void swap(int[] a,int i,int j)
{
int t;
t=a[i];
a[i]=a[j];
a[j]=t;
}
public static void swap(String[] a,int i,int j)
{
String t;
t=a[i];
a[i]=a[j];
a[j]=t;
}
public static String sort(int[] number, String[] name, BufferedReader kb)throws Exception
{
String buffer;
do
{
//Allow user to sort the phone book
System.out.println("What do you want to sort by?");
System.out.println("Number");
System.out.println("Name");
System.out.print("Enter>>");
buffer=kb.readLine();
if(buffer.equalsIgnoreCase("number"))
{
sortint(number,name);
print(name, number,kb);
return buffer;
}
else if(buffer.equalsIgnoreCase("name"))
{
sortstring(name,number);
print(name,number,kb);
return buffer;
}
System.out.println("Invalid entry");
} while(true);
}
public static void print(String[] name, int[] number, BufferedReader kb)throws Exception
{
System.out.println("Sorted data");
System.out.println("Number\tName");
for(int i=0;i<quantity;i++)
System.out.println(number[i]+"\t"+name[i]);
}
public static void display(int[] number, String[] name, BufferedReader kb)throws Exception
{
System.out.println("Number Name");
for(int i=0;i<quantity;i++)
System.out.println(number[i]+" "+name[i]);
}
public static void getdata(int number[],String name[])throws Exception
{
FileReader file = new FileReader("phoneData.txt");
try (BufferedReader input = new BufferedReader(file)) {
int i;
String buffer;
for( i=0;i<quantity;i++)
{
buffer=input.readLine();
StringTokenizer st = new StringTokenizer(buffer, ",");
name[i]=st.nextToken();
number[i]=Integer.parseInt((st.nextToken()).trim());
}
}
}
public static char menu(BufferedReader kb)throws Exception
{
String buffer;
char input;
do
{
System.out.println("\nWhat would you like to do?");
System.out.println("E-Enter phone book data");
System.out.println("D-Display phone book data");
System.out.println("X-Exit program");
System.out.println("S-Sort list");
System.out.print("Enter E, D, X, S>>");
buffer=kb.readLine();
input=(buffer.toUpperCase()).charAt(0);
if(input=='E'||input=='D'||input=='X'||input=='S')
return input;
System.out.println("Invalid entry");
} while(true);
}
}
And here is what it is returning:
What would you like to do?
E-Enter phone book data
D-Display phone book data
X-Exit program
S-Sort list
Enter E, D, X, S>>D
Number Name
What would you like to do?
E-Enter phone book data
D-Display phone book data
X-Exit program
S-Sort list
Enter E, D, X, S>>
Any help is much appreciated.
You might want to initialize quantity
private static int quantity = 1;
instead of just
private static int quantity;
so that the code inside the the loop
for( i=0;i<quantity;i++)
can get a chance....
And as stated in my first comment, you should add some Exception handling and return value checking to your code.
Also you might just delete this line
private static String[] name;
since you have name declared locally in main.
EDIT
public static void getdata(int number[],String name[])throws Exception
{
BufferedReader input = null;
try {
input = new BufferedReader(new FileReader("phoneData.txt"));
int i;
String buffer;
for( i=0;i<quantity;i++)
{
// readLinde returns null when EOF is reached
buffer=input.readLine();
if(buffer != null) {
StringTokenizer st = new StringTokenizer(buffer, ",");
name[i]=st.nextToken();
number[i]=Integer.parseInt((st.nextToken()).trim());
} else {
break; // since nothing left to read
// remaining buckets in the arrays are left empty
}
}
} catch (Exception e) {
// catch exceptions to where know your program fails
System.out.println(e.toString());
} finally {
if(input != null) {
// close the input stream when you are done
input.close();
}
}
}
Also you should consider using List instead of arrays
public static void getdata(List number,List name) {
BufferedReader input = null;
try {
input = new BufferedReader(new FileReader("phoneData.txt"));
String buffer;
while(null != (buffer = input.readLine())) {
StringTokenizer st = new StringTokenizer(buffer, ",");
name.add(st.nextToken());
number.add(Integer.valueOf(Integer.parseInt((st.nextToken()).trim())));
}
} catch (Exception e) {
System.out.println(e.toString());
} finally {
if(input != null) {
try {
input.close();
} catch (IOException e) {
// ignore
}
}
}
}

Categories

Resources