How to insert and display arraylist in java program? - java

This is the output of the program:
Enter your last name: Dela Cruz
Enter your first name: Juan
Enter your course: BSCS
Enter your year: 4th Year
Display Array List
[0] - Dela Cruz | Juan | BSCS | 4th Year
Add More (y/n): if yes it will add more entry...

Use following code.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class IO {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String continueAdd = "y";
List<Student> studentList = new ArrayList<>();
Student student;
while ("y".equalsIgnoreCase(continueAdd)) {
student = new Student();
System.out.println("Enter your last name:");
student.lastName = scn.nextLine();
System.out.println("Enter your first name:");
student.firstName = scn.nextLine();
System.out.println("Enter your course:");
student.course = scn.nextLine();
System.out.println("Enter your year:");
student.year = scn.nextLine();
studentList.add(student);
System.out.println("Add More (y/n): ");
continueAdd = scn.nextLine();
}
int i = 0;
for(Student studentTemp : studentList){
System.out.println("["+i+"] - " + studentTemp);
i++;
}
}
}
class Student {
String firstName;
String lastName;
String course;
String year;
#Override
public String toString(){
return lastName+" | "+ firstName +" | "+course+" | "+year;
}
}

You need :
public class Entries {
private String lname;
private String fname;
private String course;
private String year;
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}
and then your mainApp :
public class MainApp {
public static void main(String[] args) {
List<Entries> students = new ArrayList<Entries>();
Scanner scan = new Scanner(System.in);
System.out.println("Enter a student:(y/n)");
String option = scan.nextLine();
while(option.equalsIgnoreCase("y")||option.equalsIgnoreCase("yes")){
Entries stud = new Entries();
System.out.println("Enter student's first name");
stud.setFname(scan.nextLine());
System.out.println("Enter student's last name");
stud.setLname(scan.nextLine());
System.out.println("Enter student's course");
stud.setCourse(scan.nextLine());
System.out.println("Enter student's year");
stud.setYear(scan.nextLine());
students.add(stud);
System.out.println("Enter another student:(y/n)");
option = scan.nextLine();
}
if(option.equalsIgnoreCase("n")||option.equalsIgnoreCase("no")){
System.out.println("Do you want to dispay all students? (y/n");
String display = scan.nextLine();
if(display.equalsIgnoreCase("y")||display.equalsIgnoreCase("yes"))
for (Entries entrie : students) {
System.out.println(entrie.getLname()+" |"+
entrie.getFname()+" |"+
entrie.getCourse()+" |"+
entrie.getYear());
} else {
System.exit(0);;
}
} else {
System.out.println("option not availabe");
System.exit(0);
}
}

use this code
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class hi {
static String n,c,y;
static String option="";
static ArrayList al= new ArrayList();
static Scanner s=new Scanner(System.in);
public static void input(){
System.out.println("Enter the name");
n=s.next();
System.out.println("Enter the course");
c=s.next();
System.out.println("Enter the year");
y=s.next();
al.add(n+"|"+c+"|"+y);
System.out.println("Add More (y/n)");
option=s.next();
System.out.println(option);
if(option.equals("y")|| option.equals("Y")){
input();
}
else{
System.out.println(al);
//System.exit(0);
}
}
public static void main(String args[]) throws InstantiationException, IllegalAccessException{
input();
}
}

It would probably be better to have a class and work with objects but here is with List.
boolean flag = true;
List<String> list = new ArrayList<>();
int i = 0;
while (flag) {
String lastname, firstname, code, year;
Scanner sc = new Scanner(System.in);
System.out.println("Enter lastname");
lastname = sc.nextLine();
System.out.println("Enter firstname");
firstname = sc.nextLine();
System.out.println("Enter code");
code = sc.nextLine();
System.out.println("Enter year");
year = sc.nextLine();
list.add(i, lastname + " | " + firstname + " | " + code + " | " + year);
System.out.println(list.get(i));
i++;
System.out.println("add more? y/n");
if (!"y".equals(sc.next())) {
flag = false;
}
}

Related

How can i access the variable from different class method

This is the main file, im trying to print the result of the Age, Name, Birthdate, etc.
LabExercise1
package labexercise1;
/**
*
* #author user
*/
public class LabExercise1{
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
NewClass newClass = new NewClass();
NewClass.getFirstName();
NewClass.getLastName();
NewClass.getAge();
NewClass.getBirthDate();
NewClass.getGWA();
// TODO code application logic here
System.out.println("My name is " + FirstName + "." + " I am " + Age + " years old and the day that i was born is on " + BirthDate + ". My general weighted average this semester is " + GWA + ".");
}
NewClass
package labexercise1;
import java.util.Scanner;
/**
*
* #author user
*/
public class NewClass {
public static void getFirstName(){
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter First Name: ");
String FirstName = myObj.nextLine(); // Read user input
}
public static void getLastName(){
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter Last Name: ");
String LastName = myObj.nextLine(); // Read user input
}
public static void getAge(){
Scanner myObj = new Scanner(System.in);
System.out.println("Enter your age: ");
int Age = myObj.nextInt();
}
public static void getBirthDate(){
Scanner myObj = new Scanner(System.in);
System.out.println("Enter your BirthDate: ");
String BirthDate = myObj.nextLine();
}
public static void getGWA(){
Scanner myObj = new Scanner(System.in);
System.out.println("Enter your GWA: ");
float GWA = myObj.nextFloat();
}
}
A lot of this is basic Java 101, concepts and ideas which you should be building around "what is an object".
I would, highly, recommend taking the time to go through things like...
Declaring Member Variables
Defining Methods
Providing Constructors for Your Classes
Passing Information to a Method or a Constructor
Understanding Class Members
For example...
import java.text.ParseException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws ParseException {
new Main();
}
public Main() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter First Name: ");
String firstName = scanner.nextLine();
System.out.print("Enter Last Name: ");
String lastName = scanner.nextLine();
System.out.print("Enter Age: ");
int age = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter Birthdate: ");
String dateOfBirth = scanner.nextLine();
System.out.print("Enter GWA: ");
int gwa = scanner.nextInt();
scanner.nextLine();
Person person = new Person(firstName, lastName, age, dateOfBirth, gwa);
System.out.println("First name = " + person.getFirstName());
System.out.println("Last name = " + person.getLastName());
System.out.println("Age = " + person.getAge());
System.out.println("Date of birth = " + person.getDateOfBirth());
System.out.println("GWA = " + person.getGwa());
}
public class Person {
private String firstName;
private String lastName;
private int age;
private String dateOfBirth;
private int gwa;
public Person(String firstName, String lastName, int age, String dateOfBirth, int gwa) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.dateOfBirth = dateOfBirth;
this.gwa = gwa;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public int getGwa() {
return gwa;
}
}
}
Please keep in mind, Stack overflow is NOT a tutorial site/forum and you will, ultimately, be expected to make the effort to learn these basic concepts.

How to search and display an object by ID number in an Arraylist java?

i really need help with my program. I'm new to Arraylist and I have no idea how can i search and display an object by its ID number.
So the program has 4 class: Main, Person (parent class) Student and Employee (both are child of Person)
Now my main class has a menu that will do the following:
Add Student ( ID must be unique for each stud )
Add Employee ( ID must be unique for each emp )
Search Student ( By Student ID then display it)
Search Employee ( By Employee No then display it)
Display All ( Display All Stud and Employee )
Quit
I have done this before with array searching and displaying but now we have to use Arraylist which is better but im new to it.
Any help and suggestion is highly appreciated. Thank you!
Here's my code:
Main Class:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
ArrayList<Student> stud = new ArrayList<Student>();
ArrayList<Employee> emp = new ArrayList<Employee>();
while (true) {
int select;
System.out.println("Menu");
System.out.println("1. Add Student");
System.out.println("2. Add Employee");
System.out.println("3. Search Student");
System.out.println("4. Search Employee");
System.out.println("5. Display All");
System.out.println("6. Quit");
select = sc.nextInt();
switch (select) {
case 1:
addStud(stud);
break;
case 2:
addEmp(emp);
break;
case 3:
srchStud();
break;
case 4:
srchEmp();
case 5:
displayAll(stud, emp);
break;
case 6:
return;
default:
System.out.println("Invalid Option");
}
}
}
public static void addStud(ArrayList<Student> stud) {
String name, address, course;
int age, cNum, studNum, year;
int addMore;
System.out.println("ADD STUDENT");
do {
System.out.println("Student No: ");
studNum = sc.nextInt();
sc.nextLine();
for(int x = 0; x < stud.size(); x++){ // Please help fix, this accepts another ID if already existing to prevent duplicate
if(studNum == stud[x].getStudNum()) { // this code works with array of object but not on arraylist,
System.out.println("The Student ID: " +studNum+ " already exist.\nEnter New Student ID: ");
studNum = sc.nextInt();
sc.nextLine();
x = -1;
}
}
System.out.println("Name: ");
name = sc.nextLine();
System.out.println("Age: ");
age = sc.nextInt();
sc.nextLine();
System.out.println("Address: ");
address = sc.nextLine();
System.out.println("Contact No: ");
cNum = sc.nextInt();
sc.nextLine();
System.out.println("Course: ");
course = sc.nextLine();
System.out.println("Year: ");
year = sc.nextInt();
sc.nextLine();
stud.add(new Student(name, address, age, cNum, studNum, year, course));
System.out.println("To add another Student Record Press 1 [any] number to stop");
addMore = sc.nextInt();
sc.nextLine();
} while (addMore == 1);
}
public static void addEmp(ArrayList<Employee> emp) {
String name, address, position;
int age, cNum, empNum;
double salary;
int addMore;
System.out.println("ADD Employee");
do {
System.out.println("Employee No: ");
empNum = sc.nextInt();
sc.nextLine();
for(int x = 0; x < emp.size(); x++){
if(empNum == emp[x].getEmpNum()) {
System.out.println("The Employee ID: " +empNum+ " already exist.\nEnter New Student ID: ");
empNum = sc.nextInt();
sc.nextLine();
x = -1;
}
}
System.out.println("Name: ");
name = sc.nextLine();
System.out.println("Age: ");
age = sc.nextInt();
sc.nextLine();
System.out.println("Address: ");
address = sc.nextLine();
System.out.println("Contact No: ");
cNum = sc.nextInt();
sc.nextLine();
System.out.println("Position: ");
position = sc.nextLine();
System.out.println("Salary: ");
salary = sc.nextInt();
sc.nextLine();
emp.add(new Employee(name, address, age, cNum, empNum, salary, position));
System.out.println("To add another Student Record Press 1 [any] number to stop");
addMore = sc.nextInt();
sc.nextLine();
} while (addMore == 1);
}
public static void displayAll(ArrayList<Student> stud, ArrayList<Employee> emp){ // Definitely not working with Arraylist
System.out.println("Student ID\tStudent Name\tStudent Course\tStudent Year");
for (int x = 0; x < stud.size(); x++) {
System.out.println(stud[x].getStudNum() + "\t\t\t\t" + stud[x].getName() + "\t\t\t\t" + stud[x].getCourse() + "\t\t\t\t" + stud[x].getYear());
}
}
}
Person Class :
public class Person {
private String name, address;
private int age, cNum;
public Person() {
}
public Person(String name, String address, int age, int cNum) {
this.name = name;
this.address = address;
this.age = age;
this.cNum = cNum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getcNum() {
return cNum;
}
public void setcNum(int cNum) {
this.cNum = cNum;
}
}
Student Class :
public class Student extends Person{
private int studNum, year;
private String course;
public Student(String name, String address, int age, int cNum, int studNum, int year, String course) {
super(name, address, age, cNum);
this.studNum = studNum;
this.year = year;
this.course = course;
}
public int getStudNum() {
return studNum;
}
public void setStudNum(int studNum) {
this.studNum = studNum;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
Employee Class :
public class Employee extends Person {
private int empNum;
private double salary;
private String position;
public Employee(String name, String address, int age, int cNum, int empNum, double salary, String position) {
super(name, address, age, cNum);
this.empNum = empNum;
this.salary = salary;
this.position = position;
}
public int getEmpNum() {
return empNum;
}
public void setEmpNum(int empNum) {
this.empNum = empNum;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
}
If you are not limited to use ArrayList, better performance will be achieved using a Map.
Map<Integer, Employee> employeeIndex = new HashMap<>();
//put
employeeIndex.put(employeeId, empployee);
//get
employeeIndex.get(employeeId);
In case, you need to use ArrayList, you can use filter:
List<Student> students = new ArrayList<Student>();
List<Student> filteredStudent = students.stream()
.filter(student -> student.getStudNum() == student_id)
.collect(Collectors.toList());
just this way if you are searching for a student the id is 12
ArrayList<Integer> students;
students.forEach(stu -> {if ( stu.getStudNum() == 2) System.out.println(stu.getName());});

How to search for an element in an array? and How to add variables with declared methods into an array list?

I have 2 major troubles (that I'm aware of) with this program. Firstly, I don't know how to get FinalGrade and LetterGrade into the array. Secondly, I don't know how to use last name and first name to search for a student in the array. Let me know if you find other problems with my program. Thanks
This is the 1st class
package student;
public class Person {
protected String FirstName, LastName;
//Constructor
public Person(String FirstName, String LastName) {
this.FirstName = FirstName;
this.LastName = LastName;
}
//Getters
public String getFirstName() {
return FirstName;
}
public String getLastName() {
return LastName;
}
//Setters
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
}
This is the 2nd class:
package student;
import java.util.ArrayList;
import java.util.Scanner;
public class Student extends Person{
private int HomeworkAve, QuizAve, ProjectAve, TestAve;
private double FinalGrade;
private String LetterGrade;
//Constructor for the averages
public Student(int HomeworkAve, int QuizAve, int ProjectAve, int TestAve, String FirstName, String LastName)
{
super(FirstName, LastName);
this.HomeworkAve = HomeworkAve;
this.QuizAve = QuizAve;
this.ProjectAve = ProjectAve;
this.TestAve = TestAve;
}
//Method to calculate final grade and letter grade
//Final grade calculation
public double CalcGrade (int HomeworkAve, int QuizAve, int ProjectAve, int TestAve)
{
FinalGrade = (double)(0.15*HomeworkAve + 0.05*QuizAve + 0.4 * ProjectAve + 0.4*TestAve);
return FinalGrade;
}
//Letter grade calculation
public String CalcGrade ( double FinalGrade)
{
if ( FinalGrade >= 90.00)
LetterGrade="A";
else if(FinalGrade >= 80.00)
LetterGrade="B";
else if(FinalGrade>=70.00)
LetterGrade="C";
else if(FinalGrade>=60.00)
LetterGrade="D";
else LetterGrade="F";
return LetterGrade;
}
public String getFullName (String FirstName,String LastName)
{
String str1 = FirstName;
String str2 = LastName;
String FullName = str1+","+str2;
return FullName;
}
public Student(int HomeworkAve, int QuizAve, int ProjectAve, int TestAve, double FinalGrade, String LetterGrade, String FirstName, String LastName) {
super(FirstName, LastName);
this.HomeworkAve = HomeworkAve;
this.QuizAve = QuizAve;
this.ProjectAve = ProjectAve;
this.TestAve = TestAve;
this.FinalGrade = FinalGrade;
this.LetterGrade = LetterGrade;
}
//Setters for this student class
public void setHomeworkAve(int HomeworkAve) {
this.HomeworkAve = HomeworkAve;
}
public void setQuizAve(int QuizAve) {
this.QuizAve = QuizAve;
}
public void setProjectAve(int ProjectAve) {
this.ProjectAve = ProjectAve;
}
public void setTestAve(int TestAve) {
this.TestAve = TestAve;
}
public void setFinalGrade(int FinalGrade) {
this.FinalGrade = FinalGrade;
}
public void setLetterGrade(String LetterGrade) {
this.LetterGrade = LetterGrade;
}
//Getters for this student class
public int getHomeworkAve() {
return HomeworkAve;
}
public int getQuizAve() {
return QuizAve;
}
public int getProjectAve() {
return ProjectAve;
}
public int getTestAve() {
return TestAve;
}
public double getFinalGrade() {
return FinalGrade;
}
public String getLetterGrade() {
return LetterGrade;
}
public void DisplayGrade (){
System.out.println(FirstName+" "+LastName+"/nFinal Grade: "+FinalGrade+"/nLetter Grade: "+ LetterGrade);
}
public static void main(String[] args){
Scanner oScan = new Scanner(System.in);
Scanner iScan = new Scanner(System.in);
boolean bContinue = true;
int iChoice;
ArrayList<Student> students = new ArrayList<>();
while (bContinue == true)
{
//The menu
System.out.println("1. New Class List");
System.out.println("2. Search for a Student");
System.out.println("3. Exit");
System.out.println("Choose an item");
iChoice = iScan.nextInt();
//The 1st case: when the user wants to enter the new list
if (iChoice == 1){
System.out.println("Enter the number of students");
int numberOfStudents = iScan.nextInt();
for(int iCount = 0;iCount < numberOfStudents;){
System.out.println("Enter the name for Student " + ++iCount);
System.out.println("Enter First Name");
String FirstName = oScan.nextLine();
System.out.println();
System.out.println("Enter Last Name");
String LastName = oScan.nextLine();
System.out.println();
System.out.println("Enter Homework Average");
int HomeworkAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Quiz Average");
int QuizAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Project Average");
int ProjectAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Test Average");
int TestAve = iScan.nextInt();
System.out.println();
How to get FinalGrade and LetterGrade??
Student hobbit = new Student(HomeworkAve,QuizAve, ProjectAve,TestAve,FirstName, LastName);
students.add(hobbit);
}
}
//The 2nd case: when the user wants to search for a student
else if (iChoice == 2)
{
System.out.println("Enter First Name");
String FirstName = oScan.nextLine();
System.out.println();
System.out.println("Enter Last Name");
String LastName = oScan.nextLine();
System.out.println();
Here is my revised code to find the student but I don't know how to print the array after I found it
int i = 0;
for (Student student : students) {
if (FirstName != null & LastName != null);{
if (student.getFirstName().equals(FirstName) && student.getLastName().equals(LastName)) {
System.out.println(students.get(i)); //this doesn't work
break;
}
i++;
}
}
//The 3r case: when the user wants to exit
else if (iChoice == 3)
{
bContinue = false;
}
}
}
}
You have an ArrayList of type Student and you are doing indexOf on a variable of type String. You will have to traverse the entire ArrayList and then do a comparison to find out if the student name mathces. Sample code:
int i = 0;
for (Student student : students) {
// Add null checks if first/last name can be null
if (student.getFirstName().equals(firstName) && student.getLastName().equals(lastName)) {
System.out.println("Found student at " + i);
break;
}
i++;
}
FinalGrade and LetterGrade are variables in each object, I think you are mistaken about the concept of an Array/ArrayList. The ArrayList only holds each Student object, not the variable in each object. You can go through each student and get their finalGrade and letterGrade with the get* functions. Before doing this, you should make a call to CalcGrade methods so the grades are calculated.

String ArrayList returning null values

I am new to java and doing some arraylist work, and when compiling my lists just return null values instead of names I have typed in.
I don't understand why this is so, so if anyone could advise/help me that would be great.
Here is my main code
import java.util.*;
public class StudentData
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList<Student> studentList = new ArrayList<Student>();
String yesNo = "true";
do
{
System.out.println("Enter student's name: ");
String name = in.next();
Student s = new Student();
studentList.add(s);
String input;
do
{
System.out.println("Would you like to enter data for another student? Yes/No ");
yesNo = in.next();
}
while (!yesNo.equalsIgnoreCase("YES") && !yesNo.equalsIgnoreCase("NO"));
}
while (yesNo.equalsIgnoreCase("YES"));
for(int i = 0; i < studentList.size(); i++)
{
System.out.println(studentList.get(i).getName());
}
}
}
And
class Student
{
private String studentName;
public StudentData(String name)
{
setName(name);
}
public String getName()
{
return studentName;
}
public void setName(String name)
{
studentName = name;
}
}
You're creating a student but didn't set the name :
String name = in.next();
Student s = new Student();
studentList.add(s);
Try with :
String name = in.next();
Student s = new Student();
s.setName(name);
studentList.add(s);
Also replace your constructor. I.e :
public StudentData(String name){
setName(name);
}
should be
public Student(String name) {
setName(name);
}
Then you will be able to do Student s = new Student(name);

Scanner issue, input information not working

the question, I look at the code millions of times, may be I just can't see the simple answer but why at the point of Author name and Author Surname, system print out like this:
Enter author Name: Enter author Surname:
and it should be like this...
Enter author Name:
Enter author Surname:
and if I input information in system remember only Author first name and I can't put information for surname.
import java.util.Scanner;
public class BookTest {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
Book bookIn = new Book();
System.out.print("Enter book title: ");
bookIn.setTitleBook(scan.nextLine());
System.out.print("Enter author Name: ");
bookIn.setFirstName(scan.nextLine());
System.out.print("Enter author Surname: ");
bookIn.setSecondName(scan.nextLine());
System.out.print("Enter author Nationality: ");
bookIn.setNationality(scan.nextLine());
System.out.print("Enter book price: ");
bookIn.setPriceBook(scan.nextDouble());
System.out.print("Enter book ISBN: ");
bookIn.setIsbn(scan.nextInt());
System.out.println("Title: " +bookIn.getTitleBook());
System.out.println("Author: "+ bookIn.getFirstName()+ " " + bookIn.getSecondName());
System.out.println("Price: "+bookIn.getPriceBook());
System.out.println("ISNB Number: "+bookIn.getIsbn());
System.out.println("Aurhor Nationality: " + bookIn.getNationality());
}
}
Book Class
public class Book {
private double priceBook;
private int isbn;
private String titleBook;
private String firstName;
private String secondName;
private String nationality;
public void setTitleBook(String titleBook){
this.titleBook = titleBook;
}
public String getTitleBook(){
return titleBook;
}
public void setPriceBook(double priceBook) {
this.priceBook = priceBook;
}
public double getPriceBook() {
return priceBook;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
public int getIsbn() {
return isbn;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public String getSecondName() {
return secondName;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public String getNationality() {
return nationality;
}
}
Move the scanner to the next line after reading the ISBN. When using Scanner.nextInt the input only reads the number and not the new line character created when you press enter. Calling Scanner.nextLine after Scanner.nextInt reads the new line character and clears the buffer.
import java.util.Scanner;
public class BookTest {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
Book title = new Book();
Book price = new Book();
Book isbn = new Book();
Book fName = new Book();
Book sName = new Book();
Book nation = new Book();
System.out.print("Enter book title: ");
title.setTitleBook(scan.nextLine());
System.out.print("Enter book price: ");
price.setPriceBook(scan.nextDouble());
System.out.print("Enter book ISBN: ");
isbn.setIsbn(scan.nextInt());
scan.nextLine(); //NOTICE CHANGE HERE
//System.out.println(); THIS WAS REMOVED
System.out.print("Enter author Name: ");
fName.setFirstName(scan.nextLine());
System.out.print("Enter author Surname: ");
sName.setSecondName(scan.nextLine());
System.out.print("Enter author Nationality: ");
nation.setNationality(scan.nextLine());
System.out.println("Title: " +title.getTitleBook());
System.out.println("Price: "+price.getPriceBook());
System.out.println("ISNB Number: "+isbn.getIsbn());
System.out.println("Author: "+ fName.getFirstName() + sName.getSecondName());
System.out.println("Aurhor Nationality: " + nation.getNationality());
}
}

Categories