import ToolKit.Contact; import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.*; import javafx.stage.Stage; import java.io.*; import java.util.ArrayList; /** * (Address book) * Write a program that stores, retrieves, adds, and * updates addresses as shown in Figure 17.20. Use a * fixed-length string for storing each attribute in the address. * Use random access file for reading and writing an address. Assume * that the size of name, street, city, state, and zip is 32, * 32, 20, 2, 5 bytes, respectively. [91] * <p> * Created by Luiz Arantes Sa on 10/5/14. */ public class Exercise_09 extends Application { public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage primaryStage) throws Exception { AddressBook addrPane = new AddressBook("/Users/Kernel/Desktop/"); primaryStage.setScene(new Scene(addrPane)); primaryStage.setTitle("Address Book"); primaryStage.show(); } } class BasicAddressPane extends GridPane { // Labels Label lblName; Label lblStreet; Label lblCity; Label lblState; Label lblZip; // TextFields TextField tfName; TextField tfStreet; TextField tfCity; TextField tfState; TextField tfZip; BasicAddressPane() { // Grid pane settings this.setPadding(new Insets(10)); this.setHgap(10); this.setVgap(10); // Create Labels with Textfield lblName = createComponent("Name:", 0, tfName = new TextField(), 0); lblStreet = createComponent("Street:", 0, tfStreet = new TextField(), 0); lblCity = createComponent("City:", 140, tfCity = new TextField(), 100); lblState = createComponent("State:", 90, tfState = new TextField(), 40); lblZip = createComponent("Zip:", 130, tfZip = new TextField(), 100); // add name on first row this.add(lblName, 0, 0, 5, 1); tfName.setPrefColumnCount(25); // add street on second row this.add(lblStreet, 0, 1, 5, 1); tfStreet.setPrefColumnCount(25); // add city, state, zip on third row HBox hBox = new HBox(); hBox.getChildren().addAll(lblCity, lblState, lblZip); hBox.setMaxWidth(410); hBox.setSpacing(5); this.add(hBox, 0, 2, 5, 1); } /** * @param name - Name of Label * @param lblWidth - Label max width: 0 = default * @param textField - TextField to be attached with label * @param tfWidth - TextField max width: 0 = default * @return Label */ private Label createComponent(String name, double lblWidth, TextField textField, double tfWidth) { Label label = new Label(name, textField); label.setContentDisplay(ContentDisplay.RIGHT); // set textfield and label custom min width if needed if (lblWidth > 0) { label.setMaxWidth(lblWidth); } if (tfWidth > 0) { textField.setMaxWidth(tfWidth); } return label; } protected void setTextFields(String name, String street, String city, String state, String zip) { tfName.setText(name); tfStreet.setText(street); tfCity.setText(city); tfState.setText(state); tfZip.setText(zip); } } class AddressBook extends BasicAddressPane { ArrayList<Contact> contacts; int index = 0; // Buttons Button btnAdd; Button btnFirst; Button btnNext; Button btnPrev; Button btnLast; Button btnUpdate; boolean isNewFile; String fileName = "AddressBook.dat"; File file; AddressBook() { this(System.getProperty("user.dir")); // default path is current working directory } AddressBook(String path) { btnAdd = new Button("Add"); btnFirst = new Button("First"); btnNext = new Button("Next"); btnPrev = new Button("Prev"); btnLast = new Button("Last"); btnUpdate = new Button("Update"); // Init buttons and create bottom button panel HBox hBox = new HBox(15, btnAdd, btnFirst, btnPrev, btnNext, btnLast, btnUpdate); hBox.setAlignment(Pos.CENTER); this.add(hBox, 0, 3, 5, 1); // create listeners btnAdd.setOnAction(e -> addContact()); btnUpdate.setOnAction(e -> updateContact()); btnFirst.setOnAction(e -> { index = 0; refresh(); }); btnLast.setOnAction(e -> { index = contacts.size() - 1; refresh(); }); btnNext.setOnAction(e -> next()); btnPrev.setOnAction(e -> previous()); // Get address book file file = new File(path + fileName); // if file doesn't exist, create it try { isNewFile = file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if (!isNewFile) { syncContacts(); } else { contacts = new ArrayList<>(); } refresh(); } private void previous() { if (index > 0) { index--; refresh(); } } private void next() { if (index != contacts.size() - 1) { index++; refresh(); } } private void refresh() { if (contacts.isEmpty()) return; Contact c = contacts.get(index); setTextFields( c.getFullName(), c.getStreet(), c.getCity(), c.getState(), c.getZip() ); } public void addContact() { contacts.add(getCurrentContact()); index = contacts.size() - 1; refresh(); saveContacts(); } public void updateContact() { contacts.remove(index); contacts.add(index, getCurrentContact()); saveContacts(); } public Contact getCurrentContact() { return new Contact( tfName.getText(), tfStreet.getText(), tfCity.getText(), tfState.getText(), tfZip.getText() ); } /** * Reads address book and saves contacts to ArrayList */ private void syncContacts() { // Init new buffer array contacts = new ArrayList<>(); // Byte array for each field byte[] name = new byte[32]; byte[] street = new byte[32]; byte[] city = new byte[20]; byte[] state = new byte[2]; byte[] zip = new byte[5]; try (FileInputStream input = new FileInputStream(file)) { while (input.available() >= 91 && -1 != input.read(name)) { input.read(street); input.read(city); input.read(state); input.read(zip); contacts.add(new Contact( new String(name, "UTF-8"), new String(street, "UTF-8"), new String(city, "UTF-8"), new String(state, "UTF-8"), new String(zip, "UTF-8") )); } } catch (IOException e) { e.printStackTrace(); } } private void saveContacts() { try (FileOutputStream out = new FileOutputStream(file)) { for (Contact c : contacts) { out.write(getFixedSizeByteArray(c.getFullName(), 32)); out.write(getFixedSizeByteArray(c.getStreet(), 32)); out.write(getFixedSizeByteArray(c.getCity(), 20)); out.write(getFixedSizeByteArray(c.getState(), 2)); out.write(getFixedSizeByteArray(c.getZip(), 5)); } } catch (IOException e) { e.printStackTrace(); } } private byte[] getFixedSizeByteArray(String string, int fixedSize) { byte[] src = string.getBytes(); byte[] fixedArray = new byte[fixedSize]; System.arraycopy(src, 0, fixedArray, 0, Math.min(src.length, fixedSize)); return fixedArray; } }
Write, Run & Share Java code online using OneCompiler's Java online compiler for free. It's one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler's Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.
OneCompiler's Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
String inp = input.next();
System.out.println("Hello, " + inp);
}
}
OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle
file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies
apply plugin:'application'
mainClassName = 'HelloWorld'
run { standardInput = System.in }
sourceSets { main { java { srcDir './' } } }
repositories {
jcenter()
}
dependencies {
// add dependencies here as below
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
}
Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development.
short x = 999; // -32768 to 32767
int x = 99999; // -2147483648 to 2147483647
long x = 99999999999L; // -9223372036854775808 to 9223372036854775807
float x = 1.2;
double x = 99.99d;
byte x = 99; // -128 to 127
char x = 'A';
boolean x = true;
When ever you want to perform a set of operations based on a condition If-Else is used.
if(conditional-expression) {
// code
} else {
// code
}
Example:
int i = 10;
if(i % 2 == 0) {
System.out.println("i is even number");
} else {
System.out.println("i is odd number");
}
Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.
switch(<conditional-expression>) {
case value1:
// code
break; // optional
case value2:
// code
break; // optional
...
default:
//code to be executed when all the above cases are not matched;
}
For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.
for(Initialization; Condition; Increment/decrement){
//code
}
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while(<condition>){
// code
}
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (<condition>);
Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.
class
keyword is required to create a class.
class Mobile {
public: // access specifier which specifies that accessibility of class members
string name; // string variable (attribute)
int price; // int variable (attribute)
};
Mobile m1 = new Mobile();
public class Greeting {
static void hello() {
System.out.println("Hello.. Happy learning!");
}
public static void main(String[] args) {
hello();
}
}
Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.
Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:
This framework also defines map interfaces and several classes in addition to Collections.
Collection | Description |
---|---|
Set | Set is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc |
List | List is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors |
Queue | FIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue. |
Deque | Deque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail) |
Map | Map contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc. |