About generating unique random numbers - java

public String generateCustomerID(String id, int digit)//Customer Class
randomGenerator = new Random();
String index = "";
for(int i = 1; i <= digit; i++)
{
index += randomGenerator.nextInt(10);
}
return id + index;
public void storeCustomer(Customer customer)//Shop Class
{
customerList.add(customer);
HashSet<String> set = new HashSet<>();
String number = customer.generateCustomerID("AB", 1);
set.add(number);
customer.setCustomerID(number);
}
How can i make sure that only customers with unique id are stored. For example, if customer A got id "AB-1", then customer B should have a different id like "AB-8". I tried to use Hashset but but i am not sure this is the right method to solve this problem. I do not think i need to use UIDD.

consider this solution
static Set<String> taken = new HashSet <>();
public static void main(String [] args)
{
Scanner scan = new Scanner (System.in);
while (true) {
System.out.println("enter id ");
String id = scan.nextLine();
if (taken.contains(id)) {
System.out.println("already taken");
continue;
}
taken.add (id);
System.out.println("another [y/n]? ");
if (scan.nextLine().equals("n"))
break;
}
}
the key point being that set is a field and it is checked using contains

place
while(set.contains(number)){
number = customer.generateCustomerID("AB", 1);
}
before
set.add(number);customer.setCustomerID(number);

Related

random Strings in ArrayList

I bought Head First Java book, and i am trying to do the exercise sink a startup.
After a while the book introduce ArrayList, and show how to use it in the class and its' method.
Problem is once i change everything with arraylist, the MAIN doesn't work, becasue at start i used simple INT, in the array location, now it need array.
How can i change the values of INT into a type that i can put inside the array ?
thx for help, and here the code.
the class with the method:
private ArrayList<String> locationCells;
private int numOfHits = 0;
public void setLocationCells(ArrayList<String> locationCells)
{
this.locationCells = locationCells;
}
public String checkYourself(String guess) {
// creazione stringa miss
String result = "miss";
int index = locationCells.indexOf(guess);
if (index >= 0) {
locationCells.remove(index);
}
if (locationCells.isEmpty()) {
result = "kill";
numOfHits ++;
}else
result = "hit";
System.out.println(result);
return result;
}
and here the MAIN:
public static void main(String[] args) {
java.util.Random randomGenerator = new java.util.Random();
Scanner scan = new Scanner(System.in);
StartUpCorretta dot = new StartUpCorretta();
int manyGuesses = 0;
boolean isAlive = true;
int randomNumbers = randomGenerator.nextInt(5) +1;
int randomNumb = (int) (Math.random() * 5);
ArrayList<String> location = {randomNumbers,randomNumbers +1,randomNumbers +2};
dot.setLocationCells(location);
while(isAlive) {
System.out.println("enter a number");
int guess = scan.nextInt();
String result = dot.checkYourself(guess);
manyGuesses ++ ;
if (result.equals("kill")) {
isAlive = false;
System.out.println("you took" + " " + manyGuesses + " " + "guesses");
}
}
}
Seems, you are taking your input from console as int from this statement
int guess = scan.nextInt();
So, my answer is based on your input data type.
Please, changed your arraylist generic type String to Integer
And Secondly, this is not how you can initialized the arraylist
ArrayList<String> location = {randomNumbers,randomNumbers +1,randomNumbers +2};
Correct way to create collection using new operator like this
ArrayList<Integer> location = new ArrayList<>();
and correct way to add element into arraylist like this
location.add(randomNumbers);
location.add(randomNumbers+1);
location.add(randomNumbers+2);
Hope, it will work for you.

how can I remove objects by attribute within a Linked List?

How could I remove an object inside a Linkedlist. I have a class account with studentId and studentName. I enter the objects inside the list, but when I try to remove I do not know how to do it. Because every time you remove an element from the middle of the list it gets organized, meaning the indexes change. So how can I get the studentId attribute and remove the object inside the linkedList.
Sample:
LinkedList: Account{studentId = 1, studentName = nome1} = index = 0 ,
LinkedList: Account{studentId = 2, studentName = nome2} = index = 1 ,
LinkedList: Account{studentId = 3, studentName = nome3} = index = 2.
what I would like was for the user to insert the studentId that he wants to delete and I can do a code that searches and deletes that object.
public Account{
private int studentID;
private String StudentName;
}
public static void main(String[] args){
int accountNumber;
LinkedList<Account> linkedAccount = new LinkedList<>();
Account obj1;
System.out.println("Type the acc number: ");
accountNumber = in.nextInt();
obj1 = linkedAccount.remove(accountNumber);
System.out.println("The " + obj1 + " has been deleted");
}
Every time I delete an object from the middle it changes the index of the linkedList. Rearranging. So i do not know how to do it can you help me?
If you don't need to keep a reference to the object you remove, you can just
linkedAccount.removeIf(acc -> acc.getStudentID() == accountNumber);
If you want to keep a reference to the element you remove you can
for (Account acc : linkedAccount) {
if (acc.getStudentID() == accountNumber) {
obj1 = acc;
linkedAccount.remove(acc);
break;
}
}
// OR
for (int i = 0; i < linkedAccount.size(); i++) {
if (linkedAccount.get(i).getStudentID() == accountNumber) {
obj1 = linkedAccount.remove(i);
break;
}
}
Notice that in most case and basiclly an ArrayList is sufficient When to use LinkedList over ArrayList in Java?
Currently, you're using accountNumber as the index which is incorrect, instead loop over the list and find the index of the object and then remove:
for (int i = 0; i < linkedAccount.size(); i++) {
if (linkedAccount.get(i).getStudentID() == accountNumber) {
obj1 = linkedAccount.remove(i);
break;
}
}
Further, why are you using a LinkedList instead of an ArrayList? the latter is almost always favourable.
I think the best option is to search the account in the list by the studentID and then remove it.
public Account{
private int studentID;
private String StudentName;
public int getStudentID() {
return this.studentID;
}
}
public static void main(String[] args){
int accountNumber;
LinkedList<Account> linkedAccount = new LinkedList<>();
Account obj1;
System.out.println("Type the acc number: ");
accountNumber = in.nextInt();
for (int i = 0; i < linkedAccount.size(); i++) {
if (accountNumber == linkedAccount.get(i).getStudentID()) {
System.out.println("The student " + linkedAccount.get(i).getStudentID() + " has been deleted");
linkedAccount.remove(i);
break; // This is to exit for loop, but if you want to delete every instance in the list with this ID you can skip this break
}
}
}

Returning and displaying contents of ArrayList in different class?

I'm working on a project where I will tally a Student's choices and add them to a count array (still working on this part). For now, I'm trying to retrieve the choices that have been sent and added to a Student ArrayList in my Student class.
Student class:
public class Students {
private String name;
private ArrayList<Integer> choices = new ArrayList<Integer>();
public Students(){
name = " ";
}
public Students(String Name){
name = Name;
}
public void setName(String Name){
name = Name;
}
public String getName(){
return name;
}
public void addChoices(int Choices){
choices.add(Choices);
}
public ArrayList<Integer> getChoices(){
return choices;
}
Here is my main driver class:
public class P1Driver {
public static void main(String[] args) throws IOException{
ArrayList<Students> students = new ArrayList<Students>();
String[] choices = new String[100];
int[] count;
Scanner scan1 = new Scanner(new File("Choices.txt"));
Scanner scan2 = new Scanner(new File("EitherOr.csv"));
// Scan the first file.
int choicesIndex = 0;
while(scan1.hasNextLine()){
String line = scan1.nextLine();
choices[choicesIndex] = line;
choicesIndex++;
}
scan1.close();
// Scan the second file.
int studentIndex = 0;
while(scan2.hasNextLine()){
String line = scan2.nextLine();
String [] splits = line.split(",");
students.add(new Students(splits[0]));
for(int i = 1; i < splits.length; i++){
students.get(studentIndex).addChoices(Integer.parseInt(splits[i]));
}
studentIndex++;
}
scan2.close();
// Instantiate and add to the count array.
int countIndex = 0;
for(int i = 0; i < students.size(); i++){
if(students.get(i).getChoices(i) == -1){
}
}
The last part is where I am now. It's nowhere near done obviously (I'm right in the middle of it) but during my construction of a for loop to get the choices from the students, I'm getting an error that says, "The method getChoices() in the type Students is not applicable for the arguments (int)." Can someone explain what this means, where me error is, and possibly how to fix it? Thanks all.
getChoices(int i) is not a method you've defined.
if(students.get(i).getChoices(i) == -1){
}
getChoices() returns a list, so you can just use the get method on the list:
if(students.get(i).getChoices().get(i) == -1){
}
Alternatively, make a getChoice method:
public Integer getChoice(int i){
return choices.get(i);
}
Have you tried getChoices()[i] instead of getChoices(i)

CompareTo bubble sort

I am attempting to sort the values in my program using the Bubble Sort method. I believe that my code in the organisedRoom method is correct. However when I run the code, add some customers and then attempt to sort them, the program crashes. If anyone can please point me in the right direction I would greatly appreciate it.
package test;
import java.io.IOException;
import java.util.Scanner;
public class Test {
private class Customer implements Comparable<Customer>{
private String name;
public Customer(String name) {
this.name = name;
}
//Override to stop the program returning memory address as string
#Override
public String toString() {
return name;
}
#Override
public int compareTo(Customer c) {
return name.compareTo(c.name);
}
}
//Array to store customers
public Customer[] customers;
public Scanner input = new Scanner(System.in);
public Test(int nRooms) throws IOException {
customers = new Test.Customer[nRooms];
System.out.println("Welcome to the Summer Tropic Hotel\n");
chooseOption();
}
final JFileChooser fc = new JFileChooser();
// Call new Hotel with int value to allocate array spaces
public static void main(String[] args) throws IOException {
Test t = new Test(11);
}
// New procedure to return User input and point to next correct method
private String chooseOption() throws IOException {
// Set to null, this will take user input
String choice;
//Menu options
System.out.println("This is the Hotel Menu. Please choose from the following options:\n");
System.out.println("A: " + "This will add a new entry\n");
System.out.println("O: " + "View booked rooms, in order of customers name.\n");
System.out.println("X: " + "Exit the program\n");
// Take user input and assign it to choice
choice = input.next();
// Switch case used to return appropriate method
switch (choice.toUpperCase()) {
case "A" :
System.out.println("");
addCustomer();
return this.chooseOption();
case "O" :
System.out.println("");
organisedRoom();
return this.chooseOption();
case "X":
System.exit(0);
}
return choice;
}
// Add a new customer to the Array
public void addCustomer() throws IOException {
// New variable roomNum
int roomNum = 1;
// Loop
do {
// Take user input as room number matching to array index - 1
System.out.println("Please choose a room from 1 to 10");
roomNum = input.nextInt() - 1;
// If room is already booked print this
if (customers[roomNum] != null) {
System.out.println("Room " + roomNum + 1 + " is not free, choose a different one.\n");
this.addCustomer();
}
// Do until array index does not equal to null
} while (customers[roomNum]!= null);
System.out.println("");
// User input added to array as name replacing null (non case-sensetive)
System.out.println("Now enter a name");
customers[roomNum] = new Customer(input.next().toLowerCase());
// Customer (name) added to room (number)
System.out.println(String.format("Customer %s added to room %d\n", customers[roomNum], roomNum + 1));
}
private void organisedRoom() {
boolean flag = true;
Customer temp;
int j;
while (flag) {
flag = false;
for (j = 0; j < customers.length - 1; j++) {
if (customers[j].compareTo(customers[j+1]) < 0) {
temp = customers[j];
customers[j] = customers[j + 1];
customers[j + 1] = temp;
flag = true;
}
}
}
}
}
I think this is because the initialisation of the array adds null to all the array index places.
The stack trace is as follows:
Exception in thread "main" java.lang.NullPointerException
at test.Test$Customer.compareTo(Test.java:34)
at test.Test.organisedRoom(Test.java:133)
at test.Test.chooseOption(Test.java:83)
at test.Test.chooseOption(Test.java:79)
at test.Test.chooseOption(Test.java:79)
at test.Test.<init>(Test.java:46)
at test.Test.main(Test.java:55)
Java Result: 1
It fails because you create Customer[] which will be initialized with11 null references. If you want to order them all elements in the array will be compared. Which lead into the java.lang.NullPointerException.
Store the Customer in an ArrayList. Then you should be able to prevent this error.
edit
If you really need to stick as close as possible to your current code. The following would fix your sorting. (don't use this solution for a real life project)
private void organisedRoom() {
for (int i = customers.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (customers[j + 1] == null) {
continue;
}
if (customers[j] == null ||customers[j + 1].compareTo(customers[j]) < 0) {
Customer temp = customers[j + 1];
customers[j + 1] = customers[j];
customers[j] = temp;
}
}
}
System.out.println("show rooms: " + Arrays.toString(customers));
}
edit 2
To keep most of your current code, you might store the room in the Customer instance (which I personally would not prefer).
// change the constructor of Customer
public Customer(String name, int room) {
this.name = name;
this.room = room;
}
// change the toString() of Customer
public String toString() {
return String.format("customer: %s room: %d", name, room);
}
// store the Customer like
customers[roomNum] = new Customer(input.next().toLowerCase(), roomNum);
Your implementation of Bubble Sort is incorrect. It uses nested for loops.
for(int i = 0; i < customers.length; i++)
{
for(int j = 1; j < (customers.length - i); j++)
{
if (customers[j-1] > customers[j])
{
temp = customers[j-1];
customers[j-1] = customers[j];
customers[j] = temp;
}
}
}

Issue adding elements to an ArrayList from a different class

Is it possible to do such a thing? Say I wanted to add the values I gave values to in CountriesTest and add them to the ArrayList in Countries. Also how could I reference aCountries to print for option 2, seeing that I created it inside option 1 I can't access it anywhere else.
Here is my interface
public interface CountriesInterface
{
public String largestPop();
public String largestArea();
public String popDensity();
}
Here is the Countries class
import java.util.*;
public class Countries implements CountriesInterface
{
private final List<CountriesInterface> theCountries = new ArrayList<>();
private String cName;
private String finalPopName;
private String finalAreaName;
private String finalDensityName;
private int cPop = 0;
private int cArea = 0;
private int popDensity = 0;
private int popCounter = 0;
private int areaCounter = 0;
private int densityCounter = 0;
public Countries(String cName, int cPop, int cArea, int popDensity)
{
this.cName = cName;
this.cPop = cPop;
this.cArea = cArea;
this.popDensity = popDensity;
}
public String largestPop()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(cPop > popCounter)
{
popCounter = cPop;
finalPopName = cName;
}
}
return finalPopName;
}
public String largestArea()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(cArea > areaCounter)
{
areaCounter = cArea;
finalAreaName = cName;
}
}
return finalAreaName;
}
public String popDensity()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(popDensity > densityCounter)
{
densityCounter = popDensity;
finalDensityName = cName;
}
}
return finalDensityName;
}
}
Here is the CountriesTest class
import java.util.*;
public class CountriesTest
{
public static void main(String[] args)
{
int population = 0;
int area = 0;
int density = 0;
Scanner myScanner = new Scanner(System.in);
boolean done = false;
do
{
System.out.println("1. Enter a country \n2. Print countries with the largest population, area, and population density \n3. Exit");
int choice = Integer.parseInt(myScanner.nextLine());
if (choice == 1)
{
System.out.print("Enter name of country: ");
String input1 = myScanner.nextLine();
System.out.print("Enter area of country in square kilometers: ");
String input2 = myScanner.nextLine();
population = Integer.parseInt(input2);
System.out.print("Enter population of country: ");
String input3 = myScanner.nextLine();
area = Integer.parseInt(input3);
density = population/area;
Countries aCountries = new Countries(input1, population, area, density);
}
else if(choice == 2)
{
System.out.println("The country with the largest population: " );
System.out.println("The country with the largest area: " );
System.out.println("The country with the largest population density is: " );
}
else if(choice == 3)
{
done = true;
}
else
System.out.println("Invalid Choice");
}
while (!done);
System.exit(0);
}
}
OK, there's some mix-up in your code.
You are using the "Countries" class at the same time for an individual Country AND the list of countries. I won't recommand it, but at least you should make "static" members and methods which are for the list of countries. Or you could declare List theCountries = new ArrayList<>(); inside the main method instead.
You are never adding the new "Countries" object to the list of countries. So, if you've declared theCountries in the main method, just uste "theCountries.add(aCountries)" right after the "new Countries(...)".
your seach methods (like largestPop) won't work because they are never searching through the content of the "theCountries" ArrayList. (the "i" variable is just iterating through the indices, but never actually used to get a countent from this ArrayList).
and btw, System.exit(0) is not needed (it's implied)

Categories

Resources