I'm writing JDBC in Java, my thought is to write a method called userInsertCruise, which can make user input the data, and these data will add a new row into my database table.
Here is my code look like:
public class Insert_Cruise {
public void userInsertCruise(Date sailingDate, Date returnDate,String departurePort,
String shipName, String portOfCalls, String cruiseSerialNumber, int passengerID){
while(true){
System.out.println("Input the sailing date:");
Scanner sc1 = new Scanner(System.in);
sailingDate = java.sql.Date.valueOf(sc1.next());
System.out.println("Input the return date :");
Scanner sc2 = new Scanner(System.in);
returnDate = java.sql.Date.valueOf(sc2.next());
System.out.println("Input the departure port:");
Scanner sc3 = new Scanner(System.in);
departurePort = sc3.next();
System.out.println("Input the ship name");
Scanner sc4 = new Scanner(System.in);
shipName = sc4.next();
System.out.println("Input the ports of calls:");
Scanner sc5 = new Scanner(System.in);
portOfCalls = sc5.next();
System.out.println("Input the cruise serial number:");
Scanner sc6 = new Scanner(System.in);
cruiseSerialNumber = sc5.next();
System.out.println("Input the passenger ID:");
Scanner sc7 = new Scanner(System.in);
passengerID = sc7.nextInt();
System.out.println("Are you finish establish your data? Y/N");
Scanner ans = new Scanner(System.in);
String answer = ans.next();
if(answer != "y"){
break;
}else{
continue;
}
public void insertCruise() throws SQLException
{
String url = ("org.apache.derby.jdbc.ClientDriver");
Connection conn = null;
Statement st = conn.createStatement();
try {
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/mydata");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
try {
st.executeUpdate("INSERT INTO CRUISE ("
+ "SAILING_DATE, RETURN_DATE, DEPARTURE_PORT, SHIP_NAME,
PORTS_OF_CALLS, CRUISE_SERIAL_NUMBER, PASSENGER_ID_NUMBER) "
+ "VALUES (?,?,?,?,?,?,?)");
} catch (SQLIntegrityConstraintViolationException e) {
System.out.println("Record Already exists.");
}
}
Then I want to call the method in main:
Insert_Cruise insert = new Insert_Cruise();
insert.userInsertCruise(sailingDate, returnDate, passward, username, passward, username, 0);
insert.insertCruise();
However, it does not work. Because I have no parameter to input in the userInsertCruise method.
The reason that I don't want to use Scanner in the main method is it would make the main method too long. And I have to make user can insert row in different tables in my database, if I write all the scanner in main, it would be very mess.
Is there any method to fix this problem?
Related
I'm taking some value with the scanner in class student : mat,name and surname. I want to finish the program when the insert of mat is == "" and not a code.
For exemple when i insert mat: 8293 the program go on but when i will insert "" a blank value the program will finish. I think the mat value should be converted to an Integer but don't work the if block.
public static void inserimento() {
Studente s=null;
do{
System.out.println("\nmatricola:");
Scanner mat = new Scanner(System.in);
int matricola = mat.nextInt();
Integer i = Integer.valueOf(matricola);
if(i.equals(null)){
break;
}
System.out.println("\ncognome:");
Scanner cog = new Scanner(System.in);
String cognome = cog.next();
System.out.println("\nnome:");
Scanner nom = new Scanner(System.in);
String nome = nom.next();
s = new Studente(matricola,cognome,nome);
} while(true);
System.out.println("fine inserimento");
}
You can read the input like string and parse it to an Integer. This allow you to check if the input value is empty.
public static void inserimento() {
Studente s=null;
do{
System.out.println("\nmatricola:");
Scanner mat = new Scanner(System.in);
try {
String matricola = mat.nextLine();
if(matricola.equals("")){
break;
}
Integer i = Integer.valueOf(matricola);
System.out.println("\ncognome:");
Scanner cog = new Scanner(System.in);
String cognome = cog.next();
System.out.println("\nnome:");
Scanner nom = new Scanner(System.in);
String nome = nom.next();
s = new Studente(matricola,cognome,nome);
}
catch(Exception e) {
System.out.println("the input value must be an Integer");
}
} while(true);
System.out.println("fine inserimento");
}
public static void inserimento() {
Studente s=null;
do{
System.out.println("\nmatricola:");
Scanner mat = new Scanner(System.in);
String matricolaString = mat.nextLine();
if(!matricolaString.equals(""))
{
int i = Integer.parseInt(matricolaString);
}
else{
break;
}
System.out.println("\ncognome:");
Scanner cog = new Scanner(System.in);
String cognome = cog.next();
System.out.println("\nnome:");
Scanner nom = new Scanner(System.in);
String nome = nom.next();
s = new Studente(matricola,cognome,nome);
} while(true);
System.out.println("fine inserimento");
}
I am trying to run this code where it reads a file and sorts the words by the tabs in between the words.
File Example
Area Word Area Word Area 1111 Word
public static void start() throws FileNotFoundException {
// Create Empty address book
AddressBook book = new AddressBook();
Scanner scnr = new Scanner(System.in);
String filename = "contacts.txt";
addContactfromFile(book,filename);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
// Insert contacts FEATURE
System.out.println("------------------------INSERTING CONTACT--------------------------------");
int ans = 0;
System.out.println("Would you like to insert a Contact? 1 or 2");
ans = scnr.nextInt();
scnr.nextLine();
if(ans == 1){
System.out.println("What is the First name");
String f = scnr.nextLine();
System.out.println("What is the Last name");
String l = scnr.nextLine();
System.out.println("What is the Number name");
String n = scnr.nextLine();
System.out.println("What is the Address name");
String a = scnr.nextLine();
System.out.println("What is the City name");
String c = scnr.nextLine();
System.out.println("What is the State name");
String s = scnr.nextLine();
System.out.println("What is the Zip Code name");
int z = scnr.nextInt();
book.insertContact(f,l,n,a,c,s,z);
System.out.println("Contact has been added!");
}else {
System.out.println("Ok");
}
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// search FEATURE
System.out.println("------------------------SEARCHING CONTACT--------------------------------");
addContactfromFile(book, "contacts.txt");
checkSearch(book);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// delete Contact FEATURE
System.out.println("------------------------DELETING CONTACT--------------------------------");
addContactfromFile(book, "contacts.txt");
checkDelete(book);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// Check if address book is empty FEATURE
addContactfromFile(book, "contacts.txt");
System.out.println("Is the Address Book Empty: "+book.isAddressBookEmpty());
System.out.println(book.getNumberOfContacts());
}
public static void checkSearch(AddressBook book) throws FileNotFoundException{
Scanner scnr = new Scanner(System.in);
System.out.println("Who would like to look for?'First name'");
String first = scnr.nextLine();
System.out.println("Who would like to look for?'Last name'");
String last = scnr.nextLine();
try{
Contact c = book.searchContact(first,last);
System.out.println(c.getFirstName()+ " " + c.getAddress().getStreet());
}catch (Exception e){
System.out.println(e);
System.out.println("Contact isnt there");
}
}
public static void checkDelete(AddressBook book) throws FileNotFoundException{
Scanner scnr = new Scanner(System.in);
System.out.println("Enter First Name");
String first = scnr.nextLine();
System.out.println("Enter Last Name");
String last = scnr.nextLine();
try{
book.deleteContact(first,last);
}catch (Exception e){
System.out.println(e);
System.out.println("Didnt work");
}
}
public static void addContactfromFile(AddressBook book, String filename) throws NumberFormatException, FileNotFoundException{
Scanner reader = new Scanner(new File(filename));
while(reader.hasNextLine()) {
String contactString = reader.nextLine();
String[] contactElementStrings = contactString.split("\t");
int zipcode = Integer.parseInt(contactElementStrings[5]);
Address address = new Address(contactElementStrings[2],contactElementStrings[3],contactElementStrings[4],zipcode);
Contact contact = new Contact(contactElementStrings[0],contactElementStrings[1],address,contactElementStrings[6]);
book.insertContact2(contact);
}
}
The Error I receive from this is:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at Helper.addContactfromFile(Helper.java:106)
at Helper.start(Helper.java:16)
at Driver.main(Driver.java:17)
contactElementStrings[5] contains an empty string.
Integer.parseInt(contactElementStrings[5]) is throwing NumberFormatException because an empty string cannot be parsed to an int.
Add a check to see whether contactElementStrings[5] can be parsed to an int.
int zipcode;
if (contactElementStrings.length > 6) {
if (contactElementStrings[5] != null && !contactElementStrings[5].isEmpty()) {
zipcode = Integer.parseInt(contactElementStrings[5]);
}
else {
zipcode = 0;
}
}
EDIT
From your comment, it appears that there are lines that don't contain all the fields that you expect. Hence you also need to check whether the split line contains all the expected parts. I have edited the above code to also check whether the split line contains all the expected parts.
I am trying to read an object via ObjectInputStream. However I retrieve the following stacktrace with an EOFException:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2325)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2794)
at
java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:801)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at student.operations.StudentOperations.addStudentDetails(StudentOperations.java:46)
at student.
My code is the following:
FileInputStream fi = new FileInputStream(file.getPath());
ObjIn = new ObjectInputStream(fi);
FileOutputStream fo = new FileOutputStream(file.getPath());
Objout = new ObjectOutputStream(fo);
//bo = new BufferedOutputStream(Objout);
//bi = new BufferedInputStream(ObjIn);
System.out.println("Enter the number of students to add");
number = in.nextInt();
System.out.println("Enter Student roll number:");
int rollno = in.nextInt();
try {
HashMap<Integer, StudentModel> hs = (HashMap<Integer, StudentModel>) ObjIn
.readObject();
if (hs.containsKey(rollno)) {
System.out.println("Duplicate values are not allowed ");
} else {
for (counter = 0; counter < number; counter++) {
System.out.println("Enter Student name:");
String name = in.next();
System.out.println("Enter Student's Father name:");
String fname = in.next();
System.out.println("Enter Gender:");
String gender = in.next();
System.out.println("Enter Date of birth:");
String date = in.next();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy");
Date dateObj = null;
try {
dateObj = dateFormat.parse(date);
} catch (ParseException e) {
System.out.println(e);
}
Calendar birthday = Calendar.getInstance();
birthday.setTimeInMillis(dateObj.getTime());
Calendar current = Calendar.getInstance();
long currentTime = System.currentTimeMillis();
current.setTimeInMillis(currentTime);
int age = current.get(Calendar.YEAR)
- birthday.get(Calendar.YEAR);
System.out.println("Enter the AddressLine1:");
String address1 = in.next();
in.nextLine();
System.out.println("Enter the AddressLine2:");
String address2 = in.next();
in.nextLine();
System.out.println("Enter the city");
String city = in.next();
in.nextLine();
System.out.println("Enter the state");
String state = in.next();
in.nextLine();
System.out.println("Enter the country:");
String country = in.next();
in.nextLine();
System.out.println("Enter the Zipcode");
int code = in.nextInt();
in.nextLine();
StudentUtill.student.put(rollno, new StudentModel(name,
fname, rollno, age, gender, dateObj, address1,
address2, city, state, country, code));
Objout.writeObject(StudentUtill.student.toString());
Objout.flush();
}// for loop ends here
tester.StudentTester.main(StudentTester.java:30)
You're trying to read objects from an empty file. Look at the stack trace. End of file trying to read the header. There isn't even a header in the file, let alone an object. It's empty.
Don't create a FileOutputStream until you have something to write to it, and don't forget to close it immediately afterwards.
You're also incorrectly converting the map to a String before writing it to the file, but you haven't yet got to the point where that's a problem.
Hi guys please is there anyone can help me out with this program?
write a program that asks the user to enter a postcode and returns the city for that
postcode. If the postcode in not in the list then it should return city not found.
The find city code must be in a separate method findCity()
The user should be able to continue entering postcodes until they enter 9999 to indicate they
are complete (9999 should not appear as “city not found”)
================================================
in the txt file:
Dandenong 3175
Frankstone 3199
Berwick 3816
Cranbourne 3977
Rosebud 3939
Thats what i've done so far.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) throws FileNotFoundException
{
try
{
File f = new File("Files\\cities.txt");
Scanner input = new Scanner(f);
String text;
while(input.hasNextLine())
{
text = input.nextLine();
process(text);
}
}
catch (FileNotFoundException ex)
{
System.out.println(ex.getMessage());
}
}
public static void process(String text)
{ String name = null;
int id;
Scanner code = new Scanner(System.in);
System.out.println("enter the postcode");
id = code.nextInt();
Scanner data = new Scanner(text);
if(code.equals(0))System.out.println(name);
name = data.next();
id = data.nextInt();
while(data.hasNextDouble())
{
}
System.out.println(name+ " ");
// System.out.println(id+ " ");
}
}
File f = new File("d:\\cities.txt");
Scanner input = new Scanner(f);
Map<Integer,String> cityCode = new HashMap<Integer,String>();
String text;
while(input.hasNextLine())
{
text = input.nextLine();
Scanner data = new Scanner(text);
String name = data.next();
int id2 = data.nextInt();
cityCode.put(id2, name);
}
System.out.println("enter the postcode");
Scanner code = new Scanner(System.in);
int id = code.nextInt();
if(cityCode.containsKey(id)) {
System.out.println(cityCode.get(id));
} else {
System.out.println("City Not found");
}
Here's a straight forward approach:
First, you want user to enter a passcode. If passcode is lesser than 9999, you want to search the text file to find a city with that passcode. This thing can be implemented as:
int passcode = 5; // Suppose passcode is 5. You may suppose any value lesser than 9999
Scanner input = new Scanner(System.in);
// Ask user to enter a passcode. If user enters 9999 the while loop is exited
while(passcode < 9999)
{
System.out.println("Enter passcode: ");
passcode = input.nextInt();
// donot search if passcode is greater than or equal to 9999
if(passcode < 9999)
searchCity(passcode);
}
searchCity() method works like:
public static String searchCity(int passcode) {
Scanner citiesScanner = new Scanner(new File("Files\\cities.txt"));
while(citiesScanner.hasNext()) {
String city = citiesScanner.next();
String pass = citiesScanner.next();
if(Integer.parseInt(pass) == passcode) {
return city;
}
}
return "City not found";
}
Just try to break your problem into sub problems. Do some paper work before starting typing code. Things become a lot simpler this way.
Having an issue here, I need this loop to print new lines of code to a file until but what it does is print 1 line then fails on the second time round,
Can never get it to print to another line, below is code
public class study {
public static void main(String[] args) throws IOException{
BufferedWriter post = null;
File file = new File("text.txt");
if(!file.exists()){
file.createNewFile();
}
boolean promptUser = true;
FileWriter fileWriter = new FileWriter(file);
post = new BufferedWriter(fileWriter);
try {
while(promptUser){
System.out.println("enter age "); //get age
Scanner getage = new Scanner(System.in);
int age= getage.nextInt();
if(age <20 || age>50){ //age range
System.out.println("age must be between 20 and 50");
System.exit(0);
}
System.out.println("enter name "); //get name
Scanner getname = new Scanner(System.in);
String name= getname.nextLine();
System.out.println("enter email "); //get email
Scanner getarea = new Scanner(System.in);
String email= getarea.nextLine();
post.write(age + "\t"); <===== fails here on second run
post.write(name + "\t");
post.write(email + "\t");
post.newLine();
post.close();
System.out.println("enter quit to quit or any key to continue");
Scanner options = new Scanner(System.in);
String option = options.nextLine();
if(option.equalsIgnoreCase("quit")){
System.out.println("goodbye!");
System.exit(0);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
post.write(age + "\t");
post.newLine();
post.write(name + "\t");
post.newLine();
post.write(email + "\t");
post.newLine();
//remove post.close(); from here
Now it may solve Your problem
Replace post.close(); with post.flush(); and you should be fine.
Close the stream when the exit condition is entered.
FIXED IT GUYS
I needed to move the FileWriter line out of the TRY
import java.io.*;
import java.util.*;
public class study {
public static void main(String[] args) throws IOException {
BufferedWriter post = null;
File file = new File("text.txt"); //create file
if (!file.exists())
{
file.createNewFile();
}
boolean promptUser = true;
FileWriter fileWriter = new FileWriter(file);
try {
while (promptUser) {
post = new BufferedWriter(fileWriter);
System.out.println("enter age "); // get age
Scanner getage = new Scanner(System.in);
int age = getage.nextInt();
if (age < 20 || age > 50){ //age range
System.out.println("age must be between 20 and 50");
System.exit(0);
}
System.out.println("enter name "); //get name
Scanner getname = new Scanner(System.in);
String name= getname.nextLine();
System.out.println("enter email "); // get email
Scanner getarea = new Scanner(System.in);
String email= getarea.nextLine();
//send data to file
post.write(age + ";");
post.write(name + ";");
post.write(email + ";");
post.newLine();
post.flush();
System.out.println("enter quit to quit or any key to continue");
Scanner options = new Scanner(System.in);
String option = options.nextLine();
if (option.equalsIgnoreCase("quit")) {
System.out.println("goodbye!");
post.close(); // close file upon quitting
System.exit(0);
}
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}