Generate sequential number whenever user input into a scanner (Java) - java

I'm currently a newbie on Java and im trying to figure out how to generate a sequential number whenever a user inputs into a scanner. Currently I've been baffling between using atomicint and atomiclong for their number generator . However, my point is that whenever a user-entered all the necessary data from the class (Id,name,email,phone..etc) , it will auto-assign that user as Guest_01 at the beginning of the console
(e.g Guest_01: s4842(ID),Jason Schlong(name),JasonSC234#gmail.com(email))
Is there a specific method to illustrate the output above?
(Please keep in mind that i need to generate the sequential number first before putting it into a scanner(sounds dumb but that's how i did it )
public class Main {
private static final int TOTAL_NUMBER_IN_SEQUENCE =20;
private static final int TOTAL_NUMBER_IN_THREAD =50;
public static void main(String[] args) {
Lead lead = new Lead(TOTAL_NUMBER_IN_THREAD,TOTAL_NUMBER_IN_SEQUENCE);
Thread t1 = new Thread(new SequenceGenerator(lead,1),"Lead_");
Thread t2 = new Thread(new SequenceGenerator(lead,3),"Lead_");
Thread t3 = new Thread(new SequenceGenerator(lead,2),"Lead_");
t1.start();
t2.start();
t3.start();
}
public class SequenceGenerator implements Runnable{
public Lead lead;
public int result;
public SequenceGenerator(Lead lead, int result) {
super();
this.lead = lead;
this.result = result;
}
public void run(){
lead.printNumber(result);
}
}
public class Lead {
private int number = 1;
private int NumberofThread;
private int totalNumbersequence;
public Lead(int numberofThread, int totalNumbersequence) {
super();
NumberofThread = numberofThread;
this.totalNumbersequence = totalNumbersequence;
}
public void printNumber(int resutl){
synchronized (this){
while(number < totalNumbersequence-1){
while (number % NumberofThread!= resutl){
try {
wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+" "+number++);
notify();
}
}
}
}

You don't need this multi-threaded approach. You can just maintain an integer and every time you create a guest you simply increment it.
static final class Guest {
private final int sequenceId;
private final String id;
private final String name;
private final String email;
Guest(int sequenceId, String id, String name, String email) {
this.sequenceId = sequenceId;
this.id = id;
this.name = name;
this.email = email;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public int getSequenceId() {
return sequenceId;
}
#Override
public String toString() {
return String.format("Guest_%s: %s, %s, %s",
sequenceId, id, name, email);
}
}
private Guest createGuest(int sequence) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter id:");
String id = scanner.nextLine();
System.out.println("Enter name:");
String name = scanner.nextLine();
System.out.println("Enter email:");
String email = scanner.nextLine();
return new Guest(sequence, id, name, email);
}
public static void main(String[] args) {
GuestGenerator generator = new GuestGenerator();
int sequence = 0;
while (sequence < 2) {
Guest guest = generator.createGuest(sequence++);
System.out.println(guest);
}
}
Guest_0: 0, jason0, email0
Guest_1: 0, jason1, email1

Related

how to increment the id and take a lengthy description in java

I have made a Note class where i want to increment the id. It is not getting incremented. And also i am taking input description from console . how to accept a lengthy description like("This is Hello World") in java from the user.Please help.
public class Note {
private String title;
private static int id;
private static int count = 0;
private String description;
public static int getId() {
return id = ++count;
}
public String getTitle() {
id++;
return title;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description=description;
}
public String toString() {
return ("Id : " + id + "\n Title :" + title + "\n Description :"+ description);
}
}
Note Console class that accepts input from the user. It accepts 1. Add Note where in i want to accept a proper description from the user. Second View note where with the help of toString method i print the output. Third is EXIT
import java.util.ArrayList;
import java.util.Scanner;
public class NoteConsole {
public static void NoteConsole() {
final int ADD_NOTE = 1;
final int VIEW_NOTE = 2;
final int EXIT = 3;
boolean loop = false;
NoteConsole nc = new NoteConsole();
Note note = new Note();
ArrayList<Note> notes = new ArrayList<Note>();
NoteServiceSerialize service1 = new NoteServiceSerialize();
System.out.println("Write to the Console 1.AddNote, 2. ToView 3. Exit");
Scanner in = new Scanner(System.in);
int choice = in.nextInt();
while (!loop) {
switch (choice) {
case ADD_NOTE: {
System.out.println("Enter the title");
String title = in.next();
note.setTitle(title);
System.out.println("Enter the description");
String description = in.next();
note.setDescription(description);
notes.add(note);
service1.noteSerialize(notes);
break;
}
case VIEW_NOTE: {
for (Note note1 : notes) {
System.out.println(note1);
}
break;
}
case EXIT: {
//code
}
}
}
}
public static void main(String[] args) {
NoteConsole();
}
}
NoteServiceSerialize class -
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class NoteServiceSerialize {
public void noteSerialize (ArrayList<Note> list){
try{
FileOutputStream file = new FileOutputStream("D:\\serializable_notes.txt");
ObjectOutputStream obj = new ObjectOutputStream(file);
obj.writeObject(list);
file.close();
obj.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
Make id instance variable and increase count in constructor of class and assign current value of count to the id
public class Note {
private String title;
private int id;
private static int count = 0;
private String description;
public Note(){
count++;
this.id = count;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description=description;
}
public String toString() {
return ("Id : " + id + "\n Title :" + title + "\n Description :"+ description);
}
}
Now every Note object will have separate id.
public class NoteConsole {
//NoteConsole() is not constructor, should avoid same method name and class name
public static void NoteConsole() {
final int ADD_NOTE = 1;
final int VIEW_NOTE = 2;
final int EXIT = 3;
boolean loop = true;
//NoteConsole nc = new NoteConsole();
Note note = new Note();
ArrayList<Note> notes = new ArrayList<Note>();
//NoteServiceSerialize service1 = new NoteServiceSerialize();
Scanner in = new Scanner(System.in);
while (loop) {
System.out.println("Write to the Console 1.AddNote, 2. ToView 3. Exit");
int choice = in.nextInt();
in.nextLine();
switch (choice) {
case ADD_NOTE: {
System.out.println("Enter the title");
//in.nextLine() will read complete line.
String title = in.nextLine();
note.setTitle(title);
System.out.println("Enter the description");
String description = in.nextLine();
note.setDescription(description);
notes.add(note);
//service1.noteSerialize(notes);
break;
}
case VIEW_NOTE: {
for (Note note1 : notes) {
System.out.println(note1);
}
break;
}
case EXIT: {
loop = false;
}
}
}
in.close();
}
public static void main(String[] args) {
NoteConsole();
}
First you should provided the NoteServiceSerialize class too.
for your description problem you should use a in.nextLine() .
and about increment id, doing that in getTitle() is a bad practice.
a better alternative is this way:
private static int lastId;
private int id = nextId();
private static int nextId() {
lastId = ++lastId;
return lastId;
}
and your classes had some other problems too, replace them with this:
public class Note {
private String title;
private String description;
private static int lastId;
private int id = nextId();
private static int nextId() {
lastId = ++lastId;
return lastId;
}
public static int getLastId() {
return lastId;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setTitle(String description) {
this.description = description;
}
#Override
public String toString() {
return ("Id : " + id + "\nTitle :" + title + "\nDescription :" + description);
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class NoteConsole {
final static ArrayList<Note> notes = new ArrayList<Note>();
public static void NoteConsole() {
NoteServiceSerialize service1 = new NoteServiceSerialize();
NoteConsole nc = new NoteConsole();
Note note = new Note();
final int ADD_NOTE = 1;
final int VIEW_NOTE = 2;
final int EXIT = 3;
boolean loop = false;
Scanner in = new Scanner(System.in);
while (!loop) {
System.out.println("Write to the Console 1.AddNote 2. ToView 3. Exit");
int choice = in.nextInt();
switch (choice) {
case ADD_NOTE:
System.out.println("Enter the title :");
String title = in.next();
System.out.println("Enter the description :");
//if you had a problem with description text remove in.next()
in.next();
String description = in.nextLine();
note.setTitle(title);
note.setDescription(description);
notes.add(note);
service1.noteSerialize(notes);
System.out.println("----------------------");
break;
case VIEW_NOTE:
for (Note note1 : notes) {
System.out.println(note1);
System.out.println("----------------------");
}
break;
case EXIT:
loop = !loop;
break;
default:
System.out.println("Not a Valid Option !!!");
}
System.out.println();
}
}
public static void main(String[] args) {
NoteConsole();
}
}
id would remain 0 (default value of primitive) unless your one of the method is called :
public static int getId() {
return id = ++count;
}
public String getTitle() {
id++;
return title;
}
where you actually increment the value of id. Maybe something like :
public String toString() {
return ("Id : " + getId() + "\n Title :" + title + "\n Description :"+ description);
}
Also make sure your count is initialized as :
private static final int count = 0;

convert a integer to array of class type java

I take in a file which has a name (table) and the number of seats:
table1 6
table2 2
table3 4
I have an array of class Reservation which will take in the the name and the seat. I am having trouble converting the number of seats into the array. How do i go about doing so?
public class Reservable {
protected String id;
private Reservation[] arrayRes = new Reservation[10];
public Reservable (Scanner fileIn) {
while(fileIn.hasNext()) {
id = fileIn.next();
for(int i = 0; i < arrayRes.length; i++) {
int seat = fileIn.nextInt();
arrayRes[i] = seat;
}
}
}
here is my Reservation class:
public class Reservation {
private String name;
private int timeSlot;
private Reservable myReservable;
public Reservation(String name, int timeSlot) {
this.name = name;
this.timeSlot = timeSlot;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTimeSlot() {
return timeSlot;
}
public void setTimeSlot(int timeSlot) {
this.timeSlot = timeSlot;
}
public Reservable getMyReservable() {
return myReservable;
}
public void setMyReservable(Reservable myReservable) {
this.myReservable = myReservable;
}
public boolean isActive() {
return false;
}
You can read line by line since your file has a reservation by line.
I propose you to have a Reservation constructor with two parameters (name and nbSeat).
A remark : you array of reservation has a fixed size : 10. If you file has more than 10 elements, a ArrayIndexOutOfBoundsException will be risen.
If the number of reservation may be superior to 10 or is variable, you should use a List rather than a array.
protected String id;
private Reservation[] arrayRes = new Reservation[10];
public Reservable (Scanner fileIn) {
int i=0;
while(fileIn.hasNextLine()) {
String line = fileIn.nextLine();
String[] token = line.split("\\s");
String name = token[0];
int nbSeat= Integer.valueOf(token[1)];
// add in your array
Reservation reservation = new Reservation(name,nbSeat);
arrayRes[i] = reservation ;
}
i++;
}
And Reservation :
public class Reservation{
public Reservation(String name, int nbSeat){
this.name=name;
this.nbSeat=nbSeat;
}
}
You need to show us what your Reservation class looks like, but if it uses the conventional getters and setters this is the correct way:
public Reservable (Scanner fileIn) {
while(fileIn.hasNext()) {
for(int i = 0; i < arrayRes.length; i++) {
int seat = fileIn.nextInt();
arrayRes[i].setSeat(seat);
id = fileIn.next();
arrayRes[i].setId(id);
}
}
}

Can't get the return new Chat to retrive the values

Hi so I have a project for college where I need to build a chat in java that to work only in on computer where you execute the code and you give the name of the two users and a translation value but I am having a problem with the way they want me to do it since I cant use super, arrays , extends, or inherences I am having a problem how it currently is I my Main like this
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Chat ch = null;
boot(in, ch);
menu(in, ch);
}
public static Chat boot (Scanner in, Chat ch){
String name1;
String name2;
int transvalue = 0;
System.out.print("Username 1:");
name1=in.nextLine();
do{
System.out.print("Username 2:");
name2=in.nextLine();
if (name1.equals(name2)){
System.out.println("Names can't be equal");
}
}while(name1.equals(name2));
do{
System.out.print("Translation Value:");
transvalue=in.nextInt();
in.nextLine();
if (transvalue<1 || transvalue>26){
System.out.println("Value Can only be between 0 and 26");
}
}while(transvalue<1 || transvalue>26);
return new Chat(name1,name2,transvalue);
}
So this show be adding the info I put in to my class Chat
public class Chat {
private static final int id1 = 1;
private static final int id2 = 2;
private Users u1;
private Users u2;
private Conversation conv;
public Chat(String name1, String name2, int transvalue){
u1 = new Users(id1,name1);
u2 = new Users(id2,name2);
conv = new Conversation(transvalue);
}
public static int getId1() {
return id1;
}
public static int getId2() {
return id2;
}
public Users getU1() {
return u1;
}
public void setU1(Users u1) {
this.u1 = u1;
}
public Users getU2() {
return u2;
}
public void setU2(Users u2) {
this.u2 = u2;
}
public Conversation getConv() {
return conv;
}
public void setConv(Conversation conv) {
this.conv = conv;
}
}
but when I add the info and try to return it like for example:
System.out.print(ch.getU1());
or
System.out.print(ch.getU1().getName());
I am getting a null am I doing something wrong?
public class Users {
private int id ;
private String name;
private String mess;
public Users(int id,String name){
this.id=id;
this.name=name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
Can anyone find or point out what I'm doing wrong
Thank you in Advance to all that take the time to Help

Where should i declare the field in this code in order for it to compile?

This is not supposed to be a client class. I'm just making a class for others to use. I'm using this for a Highschool. For example i have classes for the address, teacher, students, principal, roomnumber, etc..But its not compiling for some odd reason. I believe its because I'm not declaring a field but not sure.
import java.io.*;
public class HighSchool {
// Constructors
public HighSchool() { }
public HighSchool(String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects ) {
this.title = title;
this.teacher = teacher;
this.roomNumber = roomNumber;
this.period = period;
this.String[] students = students;
this.String address =a ddress;
this.String subjects = subjects;
}
public class Classcourse (String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects
private String period;) {
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getteacher() {
return teacher;
}
public void setteacher(String teacher) {
this.teacher = teacher;
}
public int getroomNumber() {
return roomNumber;
}
public void setroomNumber (int roomNumber) {
this.roomNumber = roomNumber;
}
public String getperiod() {
return getperiod();
}
public void setperiod (String period) {
this.period = period;
}
public String[] getstudents () {
return students[];
}
public void setstudents[] (String[] students
private String address;) {
this.students = students;
}
public String getaddress() {
return address;
}
public void setaddress (String address) {
this.address = address;
}
public String getsubjects() {
return subjects;
}
public void setsubjects (String subjects) {
this.subjects = subjects;
}
}
// modifier method
public void addstudents(String students) {
String[] newstudents = new String[students.length + 1];
for (int i = 0; i < students.length; i++) {
newstudents[i] = students[i];
}
newstudents[students.length] = student;
students = newstudents;
}
public boolean isInClass(String students) {
for (int i = 0; i < students.length; i++) {
if (students[i].equals(students)) {
return true;
}
}
return false;
}
// static creator method
public static HighSchool readFromInput() throws IOException {
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a HighSchool title: ");
HighSchool newHighSchool = new HighSchool(kb.readLine());
String students = null;
do {
System.out.print("Enter a student, or press Enter to finish: ");
students = kb.readLine();
if (students != null){
newHighSchool.addstudents(students);
}
} while (students != null);
return newHighSchool;
}
// Variables (Fields)
private String title;
private String[] students;
}
In addition, you wrote something that doesn't make sense from the point of view of Java Compiler:
private String period;) {
- probably remove ")".
The second thing:
Take a look on the declaration of class Classcourse.
It rather sounds wrong, although it can be an issue of this site's editor or something...
An "overall" hint - java has a very "intelligent" compiler in the most of the cases it can say what's wrong exactly with your code, so, assuming you're a newbie in Java, try to understand what compiler says to you.
Good luck!
Some things I noticed about the code:
public String getperiod() {
return getperiod();
}
This code will cause a endless loop when you call this function.
private String address;) {
this.students = students;
}
The compiler will give an error about the ";)". Change it to "()" to fix this.
Furthermore, you should really tell us more about the errors it's giving you. We can't help you if you don't give us the compiler errors.

How to use more than one method?

So, I've got to write an invoice for a video store that has a Customer class which takes six attributes, the customer name (string), the street address (string), the city(String), the state(string), the zip code(string), and the telephone number. I had to use a parameterized constructor that receives the attributes as parameters as well as provide getters and setters. I believe I did this correctly.
Next I had to make a Video class that had four attributes, the video name (string), the year the video was released(integer), the video copy number(integer), and the daily rental rate(double). I had to do a parameterized constructor and getters and setters for this as well.
The problems start on my Invoice class which is to represent the rental of a video to a given customer, it is not finished, but is supposed to have four attributes, the customer renting the video, the video being rented, the date it was rented(as a inputted string), and the daily rental rate(double). It was also supposed to have three methods, the subtotal, the tax and the total. My problem is I've got the preset methods for the customers and the videos setup, I just have no clue how to effectively use them in an if statement. I don't know what I would put in my fourth test class to allow this to work. I am all but lost at this point, any push in the right direction would be greatly appreciated. here are my classes.
Customer:
public class Customer {
private String customerName;
private String streetAddress;
private String custCity;
private String custState;
private String custZip;
private String custPhone;
public Customer(String customerName, String streetAddress, String custCity, String custState, String custZip,
String custPhone) {
super();
this.customerName = customerName;
this.streetAddress = streetAddress;
this.custCity = custCity;
this.custState = custState;
this.custZip = custZip;
this.custPhone = custPhone;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getCustCity() {
return custCity;
}
public void setCustCity(String custCity) {
this.custCity = custCity;
}
public String getCustState() {
return custState;
}
public void setCustState(String custState) {
this.custState = custState;
}
public String getCustZip() {
return custZip;
}
public void setCustZip(String custZip) {
this.custZip = custZip;
}
public String getCustPhone() {
return custPhone;
}
public void setCustPhone(String custPhone) {
this.custPhone = custPhone;
}
}
Video:
public class Video {
private String videoName;
private int videoYear;
private int copyNum;
private double rentalRate;
public Video(String videoName, int videoYear, int copyNum, double rentalRate) {
super();
this.videoName = videoName;
this.videoYear = videoYear;
this.copyNum = copyNum;
this.rentalRate = rentalRate;
}
public String getVideoName() {
return videoName;
}
public void setVideoName(String videoName) {
this.videoName = videoName;
}
public int getVideoYear() {
return videoYear;
}
public void setVideoYear(int videoYear) {
this.videoYear = videoYear;
}
public int getCopyNum() {
return copyNum;
}
public void setCopyNum(int copyNum) {
this.copyNum = copyNum;
}
public double getRentalRate() {
return rentalRate;
}
public void setRentalRate(double rentalRate) {
this.rentalRate = rentalRate;
}
Invoice (incomplete) :
import java.util.Scanner;
public class Invoice {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
Customer Brandon = new Customer("Brandon James" , "112 Oak Street"
, "CityVille" , "Alabama" , "18229",
"912-2248");
Customer Judy = new Customer("Judy Vermooth" , "8008 Ribbit Ln.",
"Metropolis" , "Pennsylvania" , "24057", "241-8009");
Video Easter = new Video("Easter 2", 2002, 4, 2.49);
Video DareDevil3 = new Video ("Dare Devil 3", 2012, 2, 3.62);
if( Prog4.newRental = "Brandon"){
Customer Brandon = newCust
}
}
}
Prog4(incomplete):
import java.util.*;
public class Prog4 {
private String newRental;
private String vidName;
private String rentalDate;
private String daysRented;
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter Customer Name: ");
String newRental = in.nextLine();
System.out.println("Enter Video Name: ");
String vidName = in.nextLine();
System.out.println("Enter Rental date in mm/dd/yyyy format: ");
String rentalDate = in.nextLine();
System.out.println("Enter Number of Days Rented");
int daysRented = in.nextInt();
}
public String getNewRental() {
return newRental;
}
public void setNewRental(String newRental) {
this.newRental = newRental;
}
public String getVidName() {
return vidName;
}
public void setVidName(String vidName) {
this.vidName = vidName;
}
public String getRentalDate() {
return rentalDate;
}
public void setRentalDate(String rentalDate) {
this.rentalDate = rentalDate;
}
public String getDaysRented() {
return daysRented;
}
public void setDaysRented(String daysRented) {
this.daysRented = daysRented;
}
}

Categories

Resources