What does week23.UniversityProblem.Lesson#77459877 mean? [duplicate] - java

This question already has answers here:
Why does the default Object.toString() include the hashcode?
(3 answers)
Closed 8 months ago.
I was working on a problem for a club and tried to run it, here is the code:
package week23.UniversityProblem;
import java.util.ArrayList;
import java.util.Scanner;
public class UniversityProblem {
public static void main(String[] args) {
Lesson math101 = new Lesson();
math101.name = "Mathematics";
math101.credit = 4;
Lesson phys101 = new Lesson();
phys101.name = "Physics";
phys101.credit = 3;
Lesson cs102 = new Lesson();
cs102.name = "Computer Science";
cs102.credit = 3;
Lesson ictapp = new Lesson();
ictapp.name = "Ict applications";
ictapp.credit = 3;
Lesson rs101 = new Lesson();
rs101.name = "Romainian Studies";
rs101.credit = 3;
int o = 0;
Scanner scanner = new Scanner(System.in);
Scanner scanner2 = new Scanner(System.in);
while (o != 2){
System.out.println("What option do you want to use:");
System.out.println("1. Add & Print");
System.out.println("2. Exit");
o = scanner.nextInt();
if(o == 1){
Student s = new Student();
System.out.println("Name:");
s.name = scanner2.nextLine();
int c = 0;
int o2 = 0;
while(c < s.maxCredit){
System.out.println("What course would you like to take:");
System.out.println("1. " + math101.name);
System.out.println("2. " + phys101.name);
System.out.println("3. " + cs102.name);
System.out.println("4. " + ictapp.name);
System.out.println("5. " + rs101.name);
System.out.println("6. Exit");
o2 = scanner.nextInt();
if(o2 == 1){
s.arr2.add(math101);
c += math101.credit;
} else if (o2 == 2) {
s.arr2.add(phys101);
c += phys101.credit;
} else if (o2 == 3) {
s.arr2.add(cs102);
c += cs102.credit;
} else if (o2 == 4) {
s.arr2.add(ictapp);
c += ictapp.credit;
} else if (o2 == 5) {
s.arr2.add(rs101);
c += rs101.credit;
} else if (o2 == 6) {
break;
}
}
System.out.println(s.name + " ");
for (int i = 0; i < s.arr2.size(); i++) {
System.out.println(s.arr2.get(i));
}
}
}
}
}
And here is my lesson class and it's attributes:
package week23.UniversityProblem;
import java.util.ArrayList;
public class Lesson {
String name;
int credit;
}
And here is my Student class and it's attributes. Also, my arraylist is in the Student class. All of my lessons are stored in this arraylist. At the end I want to display student name and his/her lesson names with credits
package week23.UniversityProblem;
import java.util.ArrayList;
public class Student {
String name;
int maxCredit = 10;
ArrayList<Lesson> arr2 = new ArrayList<>();
}
After choosing my options from the menu i added, here is what it displays:
Tudor
week23.UniversityProblem.Lesson#77459877
week23.UniversityProblem.Lesson#5b2133b1

The Lesson class does not override the toString() method provided by the Object class (which all objects extend directly if they are not declared to extend some other object). As such, the JRE will use the toString() method of the Object class. The javadoc for that implementation states that this will be
getClass().getName() + '#' + Integer.toHexString(hashCode())

The result you get in your console is the hashcode value of an object. Since the object has no toString method to determine how it should be printed as a String. It instead prints the hashcode value which is the output you are receiving.
There are multiple ways to solve this issue. Here is one example: Add a toString method to your Lesson class:
public String toString(){//overriding the toString() method
return "Name: "+name+", Credit: "+credit;
}

Related

Library Program - Assigning & checking out books

I'm supposed to create a library program in java that allows you to create patrons and check out a maximum of 3 books. I'm really beginner at java so I apologize that my code is all over the place and may not make sense.
Below is the library class that I attempted(i also have a separate Patron, Book and Book Interface class)
My main concerns:
I have 2 ArrayLists, one for a list of inputed Users and another for a list of inputed Books. However how would i be able to assign certain checked out books to a certain user & make sure they borrow no more than 3?
I put a lot of the code in the main method but i end up having a lot of problems with static and non static stuff
How would I be able to create status' for each book? for example if "great expectations" is checked out, how can assign "borrowed" to it and make sure no one else can borrow it?
The program runs so far but its lacking depth because I'm lost as to how to check out/in books under a certain specified patron.
SORRY again for all the inconsistencies in my code and i really really appreciate the help!
import java.awt.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.Collections;
public class Library
{
static ArrayList <Patron> UserList = new ArrayList<Patron>();
static ArrayList <String> BookList = new ArrayList <String> ();
public static String status;
public static String borrower;
public static String borrowDate;
public static String returnDate;
public String status1 = "Available";
public String status2 = "Borrowed";
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int choice = 0;
System.out.println("********************Welcome to the Public Library!********************");
System.out.println(" Please Select From The Following Options: ");
System.out.println("**********************************************************************");
while(choice != 9)
{
System.out.println("1: Add new patron");
System.out.println("2: Add new book");
System.out.println("3: Edit patron");
System.out.println("4: Edit book");
System.out.println("5: Display all patrons");
System.out.println("6: Display all books");
System.out.println("7: Check out book");
System.out.println("8: Check in book");
System.out.println("9: Search book");
System.out.println("10: Search Patron");
System.out.println("9: Exit");
choice = input.nextInt();
switch(choice)
{
case 1: //Add new patron
System.out.print("Enter patron first name: ");
String firstName = input.next(); //read name from input
System.out.print("Enter patron last name: ");
String lastName = input.next();
UserList.add(new Patron(firstName, lastName)); //add name to list
System.out.println("-----You have successfully added a new patron!-----");
break;
case 2: //Add new book
System.out.print("Enter book title: ");
String title1 = input.next();
Scanner input1 = new Scanner(System.in);
System.out.print("Enter book author: ");
String author1 = input.next();
Book book1 = new Book(title1);
BookList.add(title1);
FullBookList.add(fullBook);
System.out.println("-----You have successfully added a new book!-----");
status = "available";
borrowDate = "none";
returnDate = "none";
borrower = "none";
break;
case 3: //Edit patron name
System.out.println("Enter original patron name: ");
String originalName = input.next();
System.out.println("Enter edited patron name: ");
String editedName = input.next();
//Collections.replaceAll(UserList, originalName, editedName);
if(UserList.contains(originalName))
{
}
case 4: //edit book
case 5: //display all patrons
System.out.println(UserList);
break;
case 6: //display all books
System.out.println(BookList);
break;
case 7: //check out a book
Patron.CheckOutBook();
break;
case 8: //check in a book
Patron.CheckInBook();
break;
}
}
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class Patron
{
Scanner input = new Scanner(System.in);
private String first;
private String last;
int bookCount = 0; //amount books user has in pocket
int books = 0;
//constructor to "add new patron" by entering their name.
public Patron(String f, String l)
{
first = f;
last = l;
}
public String toString()
{
return first + " " + last;
}
public String getName()
{
return first + " " + last;
}
public static void CheckOutBook()
{
System.out.println("Enter book title to be check out: ");
Scanner input = new Scanner(System.in);
String bookCheckOut = input.next();
if(Library.BookList.contains(bookCheckOut))
{
Library.BookList.remove(bookCheckOut);
System.out.println("-----" + bookCheckOut + " has been checked out!-----");
System.out.println ("-------" + bookCheckOut + " is due in 7 days!-------");
}
else
System.out.println(bookCheckOut + " is not in the library. Please enter "
+ "a different book to be checked out");
}
public static void CheckInBook()
{
System.out.println("Enter book title to be checked in: ");
Scanner input = new Scanner(System.in);
String bookCheckIn = input.next();
if(Library.BookList.contains(bookCheckIn))
{
Library.BookList.add(bookCheckIn);
System.out.println("-----" + bookCheckIn + " has been checked in!-----");
}
else
System.out.println(bookCheckIn + " is not in the library. Please enter "
+ "a different book to be checked out");
}
public boolean canBorrow()
{
if(bookCount <= 3)
{
return true;
}
else
{
return false;
}
}
}
Note: This will likely involve some refactoring to your main loop.
Alright so the way I see it, we have three classes at play here: some Patrons, which can check books out and in, some Books, which have statuses like "available" and "checked out," and a Library, which contains books. So, we need 3 classes:
I'll start with Book and use pseudo code to explain the concepts for you to implement.
class Book
{
//private fields
private final String title;
private final String author;
private Status available = true;
//note--i would prefer using an Enum called status for this,
//but a boolean true/false value works adequately
//Constructor
public Book(string title, string author) {}
//accessors for title, author, available
//setter for available--used for Library only--there are better ways to ensure
//Patrons can't set the status of the book, but for now this is the simplest way
}
As you can see, Books have immutable fields that don't need to change, and one field that tracks it status. A better implementation might make Library track book status, as that makes more logical sense and better code, but this a simple implementation.
Next, Library, which needs lots of books:
class Library
{
private final ArrayList<Book> books;
//Constructor
public Library ()
{
books = loadBooks();
}
//some methods
private ArrayList<Book> loadBooks () {}
//however you want to create all your books (file input, whatever)
public bool isBookAvailable (Book b)
{
if b isn't in library: return false
else return (b in books).isAvailable()
}
public Book checkoutBook (Book b)
{ get book (checking availability, possibly returning a null Book), set status to unavailable, return it }
public Book checkinBook (Book b)
{ check that this the book belongs to library, set status to available }
}
As I said earlier, this isn't perfect. I could spend quite some time going on and on about how to improve the design, but for the sake of simplicity won't.
Now, Patrons. One question is, should Patrons have only one library that the visit? Or do they visit multiple libraries? I'll assume they visit more than one, since sometimes a library doesn't have all the books you want.
class Patron
{
private final String name;
private final Book[] books = new Book[3];//you can see I'm limiting them to 3 books
private int index = 0;
//Constructor
public Patron (String name) {}
//methods
public void checkoutBook (Book b, Library l)
{//could be tricky
check books status in l (l.isBookAvailable(b))
if available:
if space (index < 2) Book newBook = l.checkoutBook(b); books[index++] = newBook;
else: no space
else: not available
}
public void checkinBook (int bookIndex, Library l)
{
if bookIndex < 3:
if books[index] != null:
l.checkinBook (books[index]);
books[index--] = null;
else: no book
else: not valid index
}
}
Of course, other utilities like displaying books (library, patron) and toString methods might be useful. But now the responsibility of the main method is to create some patrons, a library, and give patrons the chance to check out and check in books via a menu. You have the heavy lifting done; you can work on input and output now.
Any questions?
A Beginner Level "Student Library Program" in JAVA, which interacts the Students and the Books. This Library Program can do following functions:
1-Adding a Book to Library.
2-Update Book Quantity.
3-Search a Book with its Serial number.
4-Search Books With Author Name.
5-Show all Books and their related Information.
6-Registering a Student.
7-Show All Registered Students.
8-Student can Check Out Book From Library(if registered).
:- Student can not Check Out more than 3 Books
:- You can only borrow a Book If it is Available in Library
9-Student can Check In Book to Library.
10-You can also see the Books which a Student has Checked Out(only while checking in)
Note: At the time it can store only 50 books for simlicity in program
I Have created this program with the maximum skill and knowledge i had in java. As I'm a Beginner so I couldn't do more
Kindly give reviews about Program
Also tell me refinements which are to be made in program
Kindly Tell me the better way to do this Program
package library;
import java.util.Scanner;
public class book {
public int sNo;
public String bookName;
public String authorName;
public int bookQty;
public int bookQtyCopy;
Scanner input = new Scanner(System.in);
public book(){
System.out.println("Enter Serial No of Book:");
this.sNo = input.nextInt();
input.nextLine();
System.out.println("Enter Book Name:");
this.bookName = input.nextLine();
System.out.println("Enter Author Name:");
this.authorName = input.nextLine();
System.out.println("Enter Quantity of Books:");
this.bookQty = input.nextInt();
bookQtyCopy = this.bookQty;
}
}
package library;
import java.util.Scanner;
public class books {
book theBooks[] = new book[50]; // Array that stores 'book' Objects.
public static int count; // Counter for No of book objects Added in Array.
Scanner input = new Scanner(System.in);
public int compareBookObjects(book b1, book b2){
if (b1.bookName.equalsIgnoreCase(b2.bookName)){
System.out.println("Book of this Name Already Exists.");
return 0;
}
if (b1.sNo==b2.sNo){
System.out.println("Book of this Serial No Already Exists.");
return 0;
}
return 1;
}
public void addBook(book b){
for (int i=0; i<count; i++){
if (this.compareBookObjects(b, this.theBooks[i]) == 0)
return;
}
if (count<50){
theBooks[count] = b;
count++;
}
else{
System.out.println("No Space to Add More Books.");
}
}
public void searchBySno(){
System.out.println("\t\t\t\tSEARCH BY SERIAL NUMBER\n");
int sNo;
System.out.println("Enter Serial No of Book:");
sNo = input.nextInt();
int flag = 0;
System.out.println("S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");
for (int i=0; i<count; i++){
if (sNo == theBooks[i].sNo){
System.out.println(theBooks[i].sNo + "\t\t" + theBooks[i].bookName + "\t\t" + theBooks[i].authorName + "\t\t" +
theBooks[i].bookQtyCopy + "\t\t" + theBooks[i].bookQty);
flag++;
return;
}
}
if (flag == 0)
System.out.println("No Book for Serial No " + sNo + " Found.");
}
public void searchByAuthorName(){
System.out.println("\t\t\t\tSEARCH BY AUTHOR'S NAME");
input.nextLine();
System.out.println("Enter Author Name:");
String authorName = input.nextLine();
int flag = 0;
System.out.println("S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");
for (int i=0; i<count; i++){
if (authorName.equalsIgnoreCase(theBooks[i].authorName)){
System.out.println(theBooks[i].sNo + "\t\t" + theBooks[i].bookName + "\t\t" + theBooks[i].authorName + "\t\t" +
theBooks[i].bookQtyCopy + "\t\t" + theBooks[i].bookQty);
flag++;
}
}
if (flag == 0)
System.out.println("No Books of " + authorName + " Found.");
}
public void showAllBooks(){
System.out.println("\t\t\t\tSHOWING ALL BOOKS\n");
System.out.println("S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");
for (int i=0; i<count; i++){
System.out.println(theBooks[i].sNo + "\t\t" + theBooks[i].bookName + "\t\t" + theBooks[i].authorName + "\t\t" +
theBooks[i].bookQtyCopy + "\t\t" + theBooks[i].bookQty);
}
}
public void upgradeBookQty(){
System.out.println("\t\t\t\tUPGRADE QUANTITY OF A BOOK\n");
System.out.println("Enter Serial No of Book");
int sNo = input.nextInt();
for (int i=0; i<count; i++){
if (sNo == theBooks[i].sNo){
System.out.println("Enter No of Books to be Added:");
int addingQty = input.nextInt();
theBooks[i].bookQty += addingQty;
theBooks[i].bookQtyCopy += addingQty;
return;
}
}
}
public void dispMenu(){
System.out.println("----------------------------------------------------------------------------------------------------------");
System.out.println("Enter 0 to Exit Application.");
System.out.println("Enter 1 to Add new Book.");
System.out.println("Enter 2 to Upgrade Quantity of a Book.");
System.out.println("Enter 3 to Search a Book.");
System.out.println("Enter 4 to Show All Books.");
System.out.println("Enter 5 to Register Student.");
System.out.println("Enter 6 to Show All Registered Students.");
System.out.println("Enter 7 to Check Out Book. ");
System.out.println("Enter 8 to Check In Book");
System.out.println("-------------------------------------------------------------
---------------------------------------------");
}
public int isAvailable(int sNo){
//returns the index number if available
for (int i=0; i<count; i++){
if (sNo == theBooks[i].sNo){
if(theBooks[i].bookQtyCopy > 0){
System.out.println("Book is Available.");
return i;
}
System.out.println("Book is Unavailable");
return -1;
}
}
System.out.println("No Book of Serial Number " + " Available in Library.");
return -1;
}
public book checkOutBook(){
System.out.println("Enter Serial No of Book to be Checked Out.");
int sNo = input.nextInt();
int bookIndex =isAvailable(sNo);
if (bookIndex!=-1){
//int bookIndex = isAvailable(sNo);
theBooks[bookIndex].bookQtyCopy--;
return theBooks[bookIndex];
}
return null;
}
public void checkInBook(book b){
for (int i=0; i<count; i++){
if (b.equals(theBooks[i]) ){
theBooks[i].bookQtyCopy++;
return;
}
}
}
}
package library;
import java.util.Scanner;
public class student {
String studentName;
String regNum;
book borrowedBooks[] = new book[3];
public int booksCount = 0;
Scanner input = new Scanner(System.in);
public student(){
System.out.println("Enter Student Name:");
this.studentName = input.nextLine();
System.out.println("Enter Reg Number:");
this.regNum = input.nextLine();
}
}
package library;
import java.util.Scanner;
public class students {
Scanner input = new Scanner(System.in);
student theStudents[] = new student[50];
//books book;
public static int count = 0;
public void addStudent(student s){
for (int i=0; i<count; i++){
if(s.regNum.equalsIgnoreCase(theStudents[i].regNum)){
System.out.println("Student of Reg Num " + s.regNum + " is Already Registered.");
return;
}
}
if (count<=50){
theStudents[count] = s;
count++;
}
}
public void showAllStudents(){
System.out.println("Student Name\t\tReg Number");
for (int i=0; i<count; i++){
System.out.println(theStudents[i].studentName + "\t\t" + theStudents[i].regNum);
}
}
public int isStudent(){
//return index number of student if available
//System.out.println("Enter Student Name:");
//String studentName = input.nextLine();
System.out.println("Enter Reg Number:");
String regNum = input.nextLine();
for (int i=0; i<count; i++){
if (theStudents[i].regNum.equalsIgnoreCase(regNum)){
return i;
}
}
System.out.println("Student is not Registered.");
System.out.println("Get Registered First.");
return -1;
}
public void checkOutBook(books book){
int studentIndex =this.isStudent();
if (studentIndex!=-1){
System.out.println("checking out");
book.showAllBooks();//jjjjjjjjjjjj
book b = book.checkOutBook();
System.out.println("checking out");
if (b!= null){
if (theStudents[studentIndex].booksCount<=3){
System.out.println("adding book");
theStudents[studentIndex].borrowedBooks[theStudents[studentIndex].booksCount] = b;
theStudents[studentIndex].booksCount++;
return;
}
else {
System.out.println("Student Can not Borrow more than 3 Books.");
return;
}
}
System.out.println("Book is not Available.");
}
}
public void checkInBook(books book){
int studentIndex = this.isStudent();
if (studentIndex != -1){
System.out.println("S.No\t\t\tBook Name\t\t\tAuthor Name");
student s = theStudents[studentIndex];
for (int i=0; i<s.booksCount; i++){
System.out.println(s.borrowedBooks[i].sNo+ "\t\t\t" + s.borrowedBooks[i].bookName + "\t\t\t"+
s.borrowedBooks[i].authorName);
}
System.out.println("Enter Serial Number of Book to be Checked In:");
int sNo = input.nextInt();
for (int i=0; i<s.booksCount; i++){
if (sNo == s.borrowedBooks[i].sNo){
book.checkInBook(s.borrowedBooks[i]);
s.borrowedBooks[i]=null;
return;
}
}
System.out.println("Book of Serial No "+sNo+"not Found");
}
}
}
package library;
import java.util.Scanner;
public class Library {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("********************Welcome to the Student Library!********************");
System.out.println(" Please Select From The Following Options: ");
System.out.println("**********************************************************************");
books ob = new books();
students obStudent = new students();
int choice;
int searchChoice;
do{
ob.dispMenu();
choice = input.nextInt();
switch(choice){
case 1:
book b = new book();
ob.addBook(b);
break;
case 2:
ob.upgradeBookQty();
break;
case 3:
System.out.println("Enter 1 to Search with Serial No.");
System.out.println("Enter 2 to Search with Author Name(Full Name).");
searchChoice = input.nextInt();
switch(searchChoice){
case 1:
ob.searchBySno();
break;
case 2:
ob.searchByAuthorName();
}
break;
case 4:
ob.showAllBooks();
break;
case 5:
student s = new student();
obStudent.addStudent(s);
break;
case 6:
obStudent.showAllStudents();
break;
case 7:
obStudent.checkOutBook(ob);
break;
case 8:
obStudent.checkInBook(ob);
break;
default:
System.out.println("CHOICE SHOULD BE BETWEEN 0 TO 8.");
}
}
while (choice!=0);
}
}

How to use method variables in main?

For my school I need to create a method which moves a bug in any direction. I have the following code:
package Test;
//imports
import java.util.Scanner;
import java.util.Random;
public class test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ABug[] BugObj = new ABug[4]; //Creating object BugObj of class ABug
int loop = 1;
int i = 0;
do {
BugObj[i] = new ABug(); //creating instance
System.out.println("Please enter the name of the bug:");
BugObj[i].name = reader.next();
System.out.println("Please enter the species of the bug:");
BugObj[i].species = reader.next();
System.out.println("Please enter the horizontal position of the bug:");
BugObj[i].horpos = reader.nextInt();
System.out.println("Please enter the vertical postion of the bug:");
BugObj[i].vertpos = reader.nextInt();
System.out.println("_______________ Bug " +(+i+1) + " _______________\n" );
System.out.println("Name: " + BugObj[i].name); //Printing bug information out
System.out.println("Species: " + BugObj[i].species);
System.out.println("Horizontal Position: " + BugObj[i].horpos);
System.out.println("Vertical Postion: " + BugObj[i].vertpos + "\n\n");
move();
i++;
System.out.println("Would you like to enter another bug? \n 0-No, 1-Yes\n");
loop = reader.nextInt();
} while(loop == 1);
}
public static void move() {
Scanner reader = new Scanner(System.in);
System.out.println("Would you like this bug to move?\n 0-No, 1-Yes\n");
if (reader.nextInt() == 0) {
System.exit(0);
}
int r = (int) (Math.random() * (2- -2)) + -2;
System.out.println(r);
}
}
class ABug { //ABug class
int horpos, vertpos, energy, id;
char symbol;
String species, name;
}
Basically all I need to do is use the values of the bugs position with the random number generated in the method. I am really new to java and am unsure how to do it or even if its possible.
Since objects are passed by reference in java, you can just pass your ABug object to the move function and change the horpos, vertpos attributes. so
move(BugObj[i]);
and
public static void move(ABug bug){
Scanner reader = new Scanner(System.in);
System.out.println("Would you like this bug to move?\n 0-No, 1-Yes\n");
if (reader.nextInt() == 0)
{
System.exit(0);
}
int r = (int) (Math.random() * (2- -2)) + -2;
int originalHorpos = bug.horpos
int originalVertpos = bug.vertpos
// Now just change the attributes however you see fit. i am just adding r
bug.horpos = originalHorpos + r;
bug.vertpos = originalVertpos + r
/*by the way, we dont need to use variables for the original values. something like this would also work
bug.horpos += r;
bug.vertpos += r;
i just want to explain that in java when you pass objects, they are passed by reference and hence you have access to all of its members.
*/
System.out.println(r);
}
also, you dont need to declare the Scanner object again inside the move function. you can pass that to the move function as well and then read as many times as you like.

Output Should be What is in the Array

I'm doing a library system which once I input a book name, and found inside the array, the out put would be "the book was returned" . But every time I input the name of one the books listed in the array, it still say that "the book is out of order". How can I solve this problem?
import java.util.Scanner;
public class NewClass {
public static void main (String args[]){
Scanner book = new Scanner(System.in);
String [] library = new String [4];
library [0] = "Brazil";
library [1] = "Japan";
library [2] = "China";
library [3] = "India";
String bookEntry = " ";
int day;
int x = 2;
int penalty;
for (int i = 0; i < library.length; i++){
System.out.println("Insert name of the book: ");
bookEntry= book.next();
if (bookEntry == library[i]){
System.out.println("The book was returned");
}else if (bookEntry != library[i]){
System.out.println("The book is out of order");
System.out.println("\n" + bookEntry.toUpperCase()+ " " + "is out since: ");
day = book.nextInt();
if (day > x){
penalty = day*20;
System.out.println("Total fine: " + penalty);
}else{
System.out.println("Not yet due.");
}
}
}
}
}
In Java, you don't compare 2 strings by ==.
Instead you use, .equals() method of class String.
==            -> is a reference comparison, i.e. both objects point to the same memory location
.equals()  -> evaluates to the comparison of values in
the objects
More on this here
Corrected code below :
import java.util.Scanner;
public class NewClass {
public static void main(String args[]) {
Scanner book = new Scanner(System.in);
String[] library = new String[4];
library[0] = "Brazil";
library[1] = "Japan";
library[2] = "China";
library[3] = "India";
String bookEntry = " ";
int day;
int x = 2;
int penalty;
System.out.println("Insert name of the book: ");
bookEntry = book.next();
boolean present = false;
for (int i = 0; i < library.length; i++) {
if (bookEntry.equals(library[i])) {
present = true;
break;
}
}
if (present) {
System.out.println("The book was returned");
} else {
System.out.println("The book is out of order");
System.out.println("\n" + bookEntry.toUpperCase() + " " + "is out since: ");
day = book.nextInt();
if (day > x) {
penalty = day * 20;
System.out.println("Total fine: " + penalty);
} else {
System.out.println("Not yet due.");
}
}
}
}
Working code here
UPDATE : I have changed the code.

How to search through a LinkedList for an object with a certain variable in Java? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have this issue where I can populate a LinkedList with objects which I can manipulate later in this shop system I am designing. The problem is that when I populate the list with more than one Object and then search for that object in the List; my program will tell me that the object I am looking for doesn't exist even though I can list the contents of the list and it will show.
Any help would be appreciated.
import java.io.*;
import java.util.*;
public class Sales extends addVideoGame implements java.io.Serializable{
private static LinkedList<VideoGames> sellGame = new LinkedList<>();
private static String searchTerm;
private static int searchQ;
public static void sellItem(){
sellGame = games;
int listLength = sellGame.size();
searchTerm = IBIO.inputString("What item would you like to sell: ");
for(VideoGames v : sellGame){
if(v.getTitle().contains(searchTerm)){
IBIO.output("Item found: " + searchTerm);
searchQ = v.getQuantity();
IBIO.output("Available Quantity: " + searchQ);
int sellQ = IBIO.inputInt("How much of this item would you like to sell: ");
if(sellQ > searchQ){
IBIO.output("The amount you have specified is greater than the \ncurrent stock.");
sellItem();
} else {
searchQ = searchQ - sellQ;
v.setQuantity(searchQ);
double sellP;
sellP = sellQ * v.getPrice();
IBIO.output("£"+sellP);
String confirm = IBIO.input("This is the price you are selling these items for. Type 'Yes' to complete the order or 'No' to reject it. ");
if(confirm.equalsIgnoreCase("Yes")){
IBIO.output("Order complete!");
try{
int receiptCount = 0;
PrintWriter receipt = new PrintWriter("C:\\Users\\Yemi\\Desktop\\TheStore\\receipt"+ receiptCount +".txt");
receipt.println("Item sold: " + v.getTitle());
receipt.println("Quantity sold: " + sellQ);
receipt.close();
receiptCount = receiptCount + 1;
IBIO.output("Receipt saved to: C:\\Users\\Yemi\\Desktop\\TheStore");
} catch(IOException io){
io.printStackTrace();
}
IBIO.output("Thank you for buying from Gamers Avenue UK!");
} else if(confirm.equalsIgnoreCase("No") && TheStore.privilege){
AccessMenus.adminMenu();
} else {
AccessMenus.userMenu();
}
if(TheStore.privilege){
AccessMenus.adminMenu();
} else {
AccessMenus.userMenu();
}
}
} else {
IBIO.output("The item you are looking for does not exist.");
sellItem();
}
}
}
}
Here are the classes used to navigate the program if anyone needs them:
public class TheStore {
static String password; //Variable created to hold and check the value of password against the correct value.
public static boolean privilege = false; //Variable created to distinguish the difference between a normal user and a user with administrator privileges.
public static void main(String[] args) {
IBIO.output("Welcome to Gamers Avenue UK!");
IBIO.output("Please make sure that you enter the correct password for your given privileges.");
password = IBIO.inputString("Enter password: ");
if(password.equalsIgnoreCase("admin")){ //Checks the entered value against the correct value.
privilege = true; //Sets global boolean value to true, so that admin access is granted.
IBIO.output(" ");
AccessMenus.adminMenu();//If password is correct, loads admin menu.
} else if(password.equalsIgnoreCase("user")){
privilege = false; //Keeps admin access off, so that unauthorised changes cannot be made.
IBIO.output(" ");
AccessMenus.userMenu();//If correct, loads user menu.
} else {
IBIO.output("The password is incorrect. Exiting program.");
System.exit(1); //If an incorrect password is entered, the program will close.
} //close else
}//close main
}//close class TheStore
Access Menus:
public class AccessMenus{
public static int choice;//Variable which will hold the value, which corresponds to an action depending on what value is entered.
public AccessMenus(){ //Null argument constructor, to set values to 0.
AccessMenus.choice = 0;
}
public AccessMenus(int c){ //Single argument constructor.
AccessMenus.choice = c;
}
public static void userMenu(){
IBIO.output("1: Sell a product.");
IBIO.output("2: Register a customer in the Loyalty programme.");
IBIO.output("3: Stock check.");
IBIO.output("4: Log out.");
IBIO.output(" ");
IBIO.output("Please make your choice: ");
choice = IBIO.inputInt();
if(choice == 1){
Sales.sellItem();
} else if(choice == 2){
CustomerRandom.customerMenu();
} else if(choice == 3){
StockCheck.checkStock();
} else if(choice == 4){
IBIO.output("Logging out.");
System.exit(1);
} else {
IBIO.output("Invalid choice. Returning to menu.");
userMenu(); //If the value entered does not correspond to any action, the program will treat it as invalid and return to the menu.
}//close else
}//close userMenu
public static void adminMenu(){
IBIO.output("1: Sell a product.");
IBIO.output("2: Go the Videogame management menu.");
IBIO.output("3: Stock check.");
IBIO.output("4: Register a customer in the Loyalty programme.");
IBIO.output("5: Log out.");
IBIO.output(" ");
IBIO.output("Please make your choice: ");
choice = IBIO.inputInt();
if(choice == 1){
Sales.sellItem();
} else if(choice == 2){
addVideoGame.vgMenu();
}else if(choice == 3){
StockCheck.checkStock();
} else if(choice == 4){
CustomerRandom.customerMenu();
} else if(choice == 5){
IBIO.output("Logging out.");
System.exit(1);
} else {
IBIO.output("Invalid input. Returning to menu.");
adminMenu();
} //end else
}//close AdminMenu
}//close AccessMenus
This class is necessary as it allows you to populate the list:
import java.util.*;
import java.io.*;
public class addVideoGame extends VideoGames implements java.io.Serializable{
public static VideoGames game = new VideoGames();
public static VideoGames eGame = new VideoGames();
public static LinkedList <VideoGames> games = new LinkedList<>();
public static LinkedList <VideoGames> loadList = new LinkedList<>();
private static int vgChoice = 0;
public static int vgCount = 0;
public static int vgAmount = 0;
public static void vgMenu(){
IBIO.output("WARNING: USING OPTION 4 TO LOAD IN A LOCAL FILE WILL ERASE EVERYTHING CONTAINED IN THE CURRENT LIST. \nSave everything in the current list using option 3 before loading in data.");
IBIO.output("1: Add a new videogame to the list.");
IBIO.output("2: View the contents of the list.");
IBIO.output("3: Save the contents of the list to the local area.");
IBIO.output("4: Load in data from a local file.");
IBIO.output("5: Return to the main menu.");
vgChoice = IBIO.inputInt("Make your choice: ");
if(vgChoice == 1){
vgAmount = IBIO.inputInt("How many games would you like to add to the database?: ");
for(int x = 0; x < vgAmount; x = x + 1){
VideoGames vg = new VideoGames();
vg.setTitle(IBIO.inputString("Enter the title of the game: "));
vg.setPublisher(IBIO.inputString("Enter the publisher of the game: "));
vg.setDeveloper(IBIO.inputString("Enter the developer of the game: "));
vg.setAgeRating(IBIO.inputInt("Enter the age rating of the game: "));
vg.setGenre(IBIO.inputString("Enter the genre of the game: "));
vg.setQuantity(IBIO.inputInt("Enter the available quantity of the game: "));
vg.setPrice(IBIO.inputDouble("Enter the recommended retail price: "));
game = vg;
games.add(vg);
IBIO.output(" ");
}
vgMenu();
} else if(vgChoice == 2){
IBIO.output("Current amount of games in the list: " + games.size());
Iterator itr = games.iterator();
while(itr.hasNext()){
Object g = itr.next();
IBIO.output(g + " ");
}
//System.out.println(Arrays.toString(games.toArray()));
vgMenu();
} else if(vgChoice == 3){
try{
ListIterator output = games.listIterator();
while(output.hasNext()){
Object o = output.next();
FileOutputStream fileOut = new FileOutputStream("C:\\Users\\Yemi\\Desktop\\TheStore\\games.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(game);
out.close();
fileOut.close();
IBIO.output("Data saved to C:\\Users\\Yemi\\Desktop\\TheStore\\games.ser");
}
} catch(IOException io){
io.printStackTrace();
}
vgMenu();
} else if(vgChoice == 4){
eGame = null;
try{
ListIterator input = games.listIterator();
while(input.hasNext()){
Object i = input.next();
FileInputStream fileIn = new FileInputStream("C:\\Users\\Yemi\\Desktop\\TheStore\\games.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
eGame = (VideoGames) in.readObject();
in.close();
fileIn.close();
games.clear();
games.add(eGame);
IBIO.output("Item added to list from local file.");
}
} catch (IOException i){
i.printStackTrace();
return;
} catch(ClassNotFoundException c){
IBIO.output("VideoGames class not found");
c.printStackTrace();;
return;
}
vgMenu();
} else if(vgChoice == 5){
IBIO.output("Returning to main menu: ");
AccessMenus.adminMenu();
}
}
}
Again, any help would be greatly appreciated!
I guess the bug is cause by the else-block inside the loop inside sellItem().
Try this (although still I think you should remove the call to sellItem() inside the final if):
import java.io.*;
import java.util.*;
public class Sales extends addVideoGame implements java.io.Serializable{
private static LinkedList<VideoGames> sellGame = new LinkedList<>();
private static String searchTerm;
private static int searchQ;
public static void sellItem(){
sellGame = games;
int listLength = sellGame.size();
searchTerm = IBIO.inputString("What item would you like to sell: ");
boolean foundItem = false;
for(VideoGames v : sellGame){
if(v.getTitle().contains(searchTerm)){
foundItem = true;
IBIO.output("Item found: " + searchTerm);
searchQ = v.getQuantity();
IBIO.output("Available Quantity: " + searchQ);
int sellQ = IBIO.inputInt("How much of this item would you like to sell: ");
if(sellQ > searchQ){
IBIO.output("The amount you have specified is greater than the \ncurrent stock.");
sellItem();
} else {
searchQ = searchQ - sellQ;
v.setQuantity(searchQ);
double sellP;
sellP = sellQ * v.getPrice();
IBIO.output("£"+sellP);
String confirm = IBIO.input("This is the price you are selling these items for. Type 'Yes' to complete the order or 'No' to reject it. ");
if(confirm.equalsIgnoreCase("Yes")){
IBIO.output("Order complete!");
try{
int receiptCount = 0;
PrintWriter receipt = new PrintWriter("C:\\Users\\Yemi\\Desktop\\TheStore\\receipt"+ receiptCount +".txt");
receipt.println("Item sold: " + v.getTitle());
receipt.println("Quantity sold: " + sellQ);
receipt.close();
receiptCount = receiptCount + 1;
IBIO.output("Receipt saved to: C:\\Users\\Yemi\\Desktop\\TheStore");
} catch(IOException io){
io.printStackTrace();
}
IBIO.output("Thank you for buying from Gamers Avenue UK!");
} else if(confirm.equalsIgnoreCase("No") && TheStore.privilege){
AccessMenus.adminMenu();
} else {
AccessMenus.userMenu();
}
if(TheStore.privilege){
AccessMenus.adminMenu();
} else {
AccessMenus.userMenu();
}
}
break;
}
}
if(!foundItem) {
IBIO.output("The item you are looking for does not exist.");
sellItem();
}
}
}
And while this may work I would generally advise to transform searchTerm into an argument to the function and searchQ to the return value of the function. Doing so increases isolation between concurrent processes and clarifies which parameters are needed for the correct execution of the function.

This is my final code i am getting an error on "if(Users[B].substring(0,1) == "1"){ //Find String Cut Char Function" [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Having trouble finding how to solve this error, please help me.
import java.util.Scanner;
import java.io.*;
public class work {
public static void main(String[] args) throws IOException {
String Login;
int A,B,C,D,NumTea,NumStu,PerClass,Teacher,Total,LoginID,LoginType,Choice;
String[] Users = new String[20];
Scanner FileScan;
FileScan = new Scanner(new File("users.txt"));
A = 0;
while (FileScan.hasNext())
{
Users[A] = FileScan.nextLine(); //Find the function to fix this
A++;
}
Scanner reader = new Scanner(System.in);
// Ready to get database of students and teachers
// Arrays for seperating out students from teachers
String[] Teachers = new String[1000];
String[] Students = new String[1000];
Total = A;
System.out.println("Please wait for the system to intilize...");
B=0;
C=0;
//Ready to seperate students from teachers in for loops
for(B=0;B<=A;B++){
if(Users[B].substring(0,1) == "1"){ //Find String Cut Char Function
Students[C] = Users[B];
C=C+1;
}
}
NumStu = C+1;
C=0;
for(B=0;B<=A;B++){
if(Users[B].substring(0,1) == "2"){ //Find String Cut Char Function
Teachers[C] = Users[B];
C=C+1;
}
}
NumTea = C+1;
System.out.println("Each teacher has 1 class a day but each student has 2 classes per day");
System.out.println("There are " + NumTea + " teachers in the school therefore there are " + (NumTea) + " classes");
System.out.println("There are " + NumStu + " students in the school therefore there are " + ((NumStu*2)/NumTea) + " kids per class on average"); //Diving correctly?
PerClass = ((NumStu*2)/NumTea);
int[][] StudentClass = new int[NumStu][2]; //Looks at what classes each student has
int[][] TeacherClass = new int[NumTea][1000]; //Looks at what students each teacher has
for(B=0;B<=(NumStu-1);B++){
Teacher = (int)(Math.random()*NumTea); //Import Math Library and check random function
StudentClass[B][0] = Teacher; //Assigning first class
Teacher = (int)(Math.random()*NumTea);
StudentClass[B][1] = Teacher; //Assigning second class
if(StudentClass[B][0] == StudentClass[B][1]){ //Error checking for same class
Teacher = (int)(Math.random()*NumTea);
StudentClass[B][1] = Teacher;
}
}
//Ready to look at student classes and assign them to teachers
B=0;
C=0;
D=0;
int[] StuClass = new int[NumTea]; //Looks at how many students are in each class
for(B=0;B<=(NumTea-1);B++){
D=0;
for(C=0;C<=(NumStu-1);C++){
if(StudentClass[C][0] == B || StudentClass[C][1] == B){
TeacherClass[B][D] = C;
D=D+1;
}
}
StuClass[B] = D;
}
System.out.println("Classes print out:");
// Going to print out all students and all teachers in each class
A=0;
B=0;
for(A=0;A<=(NumTea-1);A++){
System.out.println(Teachers[A] + "'s class (" + (StuClass[A]+1) + "):");
for(B=0;B<=(StuClass[A]);B++){
System.out.println(" " + Students[(TeacherClass[A][B])]);
}
}
while(1==1){
System.out.println("Welcome to Wayzata WHS's SGS (Scheduling and Grading System)");
System.out.println("Login:");
Login = reader.nextLine();
A = 0;
LoginType = 0;
LoginID = 0;
for(A=0;A<=(NumStu-1);A++){
if(Students[A].toLowerCase() == Login.toLowerCase()){ //Check to see if string lower is correct
System.out.println("Found your account, linking you with the system...");
LoginID = A;
LoginType = 1;
}
}
for(A=0;A<=(NumTea-1);A++){
if(Teachers[A].toLowerCase() == Login.toLowerCase()){ //Check to see if string lower is correct
System.out.println("Found your account, linking you with the system...");
LoginID = A;
LoginType = 2;
}
}
//The user has typed in a name and the system has recognized it and found it in the system the program has logged ethier a student or teacher in
if(LoginType == 1){
System.out.println("Welcome " + Students[LoginID] + "! Signed in as: STUDENT");
System.out.println("What would you like to do today?");
System.out.println("1: See grades");
System.out.println("2: Logout");
Choice = reader.nextInt();
if(Choice == 1){
System.out.println("1: " + Teachers[(StudentClass[LoginID][0])] + "'s Class");
System.out.println("2: " + Teachers[(StudentClass[LoginID][1])] + "'s Class");
Choice = reader.nextInt();
//c.PrintClassGrades(LoginID,Choice); //Add a class for this
}
}else if(LoginType == 2){
System.out.println("Welcome " + Teachers[LoginID] + "! Signed in as: TEACHER");
System.out.println("What would you like to do today?");
System.out.println("1: Do attendance");
System.out.println("2: Look at class grades");
System.out.println("3: Add grade to gradebook");
System.out.println("4: Logout");
Choice = reader.nextInt();
if(Choice == 1){
//c.Attendance(LoginID); //Add a class for this
}else if(Choice == 2){
//c.ClassGrades(LoginID); //Add a class for this
}else if(Choice == 3){
//c.AddGrade(LoginID);//Add a class for this
}
}
}
}
}
(I'd post this as a comment, but I'm not sure it would fit.)
Here are some suggestions for making it easier to get your program working:
Separate out your declarations. Have one purpose for each variable, and have the identifier indicate that purpose.
During debug, use java.util.Random initialized with a fixed seed, not Math.random. With Math.random, you get a different sequence of numbers every time you run.
Look really carefully at the output. Where is the first point at which it did something you did not expect? Add more output between the last time everything was the way you expected and the first time it was not.
Work small versions of your problem with paper and pencil.
Firstly, never use the == operator when comparing strings, always use String.equals().:
if ("1".equals(Users[B].substring(0, 1))
Second. You are passing beyond the last index of the number of strings you have read in. Change (x2):
for (B = 0; B <= A; B++) {
to
for (B = 0; B < A; B++) {
All entries in your array:
String[] Users = new String[20];
will be initialized to null by default, leading to an NullPointerException when you try & access :
Users[B].substring(0, 1)
when B = A.
This mistake is made twice more, change to:
for (A = 0; A < (NumTea - 1); A++) {

Categories

Resources