Adding 3 string into 3 variable - java

My Account class have 3 variable to store name, id and password
and my method addAcount() get 3 parameter and pass all into the 3 variable.
The problem is i cant pass the 3 parameter item into the 3 variable.
my 3 variable declaration :
private String[] id = new String[100];
private String[] pass = new String[100];
private String[] name = new String[100];
here's my method:
public void addAccount(String id, String pass, String name){
for(int i=0; i < this.id.length;i++){
if(this.id[i]==null){
this.id[i]=id;
for(int a = 0; a <this.pass.length;a++){
if(this.pass[a]==null){
this.pass[a]=pass;
for(int b=0;b<this.name.length;b++){
if(this.name[b]==null){
this.name[b]=name;
break;
}
}
}
}
}
}
Any Help will be Appreciated

To access all elements
Your method header shoud be :-
public void addAccount(String[] id, String[] pass, String[] name){
//your code here
// By looping over array you can get the strings in it
for(int i = 0 ; i < id.length ; i++){
String str_id = id[i];
}
}
And to call it :-
addAccount(id,pass,name);
To access specific string at specific position :-
String str_pass = pass[5];//by his you will get the 6th element(zero base indexing )
But be aware if you direct access the array if the index you use greater than array.length you will get array out of boundary exception

In this situation you can use this:
public void addAccount(String id, String pass, String name)
{
//These for loops look up the first empty spot in the array and
//insert the chosen parameter in that spot once
//Add ID to array
for (int i = 0; i < this.id.length; i++)
{
if (this.id[i] == null)
{
this.id[i] = id;
i = this.id.length;
}
}
//Add Pass to array
for (int a = 0; a < this.pass.length; a++)
{
if (this.pass[a] == null)
{
this.pass[a] = pass;
a = this.pass.length;
}
}
// Add name to array
for (int b = 0; b < this.name.length; b++)
{
if (this.name[b] == null)
{
this.name[b] = name;
b = this.name.length;
}
}
}
Edit: changed the code so the array length won't matter

Related

Java - Problem at sorting array list using bubblesort

I have a problem at the moment I have a college assignment and we need to list a file that contain books and should be sorted A to Z,
My sort algorithm is a bubble sort and at the moment is not sorting alphabetically but don't give errors, I cant see where I should change to make it work as the coding seems correct to me.
We are not allowed to use collections so that is the reason I am not using sort().
package Book;
public class AlphabeticalOrderTitle{
//Global variables
public static String input;
public static int bookId;
public static String bookTitle;
public static String authorName;
public static boolean isAvailable;
public static void main(String[] args)
{
ArrayList<Book> books = BubbleSort();
System.out.println(linearSearch(books));
}
public static ArrayList<Book> loadData() {
//Creating an array list;
ArrayList<Book> books = new ArrayList<>();
try {
//Here we start reading our file
BufferedReader br = new BufferedReader(new FileReader("Book.txt"));
//This header string will allow to skip the header so does not mismatch with getter and setters.
String header = br.readLine();
//This string will read the lines.
String contentLine = br.readLine();
//Giving our array name data;
String [] data;
//Here we loop to continue the reading of data for each array box.
while (contentLine != null) {
data = contentLine.split(",");
bookId = Integer.parseInt(data[0]);
bookTitle = data[1];
authorName = data[2];
isAvailable = Boolean.parseBoolean(data[3]);
books.add(new Book(bookId, bookTitle, authorName, isAvailable));
contentLine = br.readLine();
}
}catch (IOException ex) {
Logger.getLogger(SearchBookAuthor.class.getName()).log(Level.SEVERE, null,ex);
}
return books;
}
public static int linearSearch(ArrayList<Book> array){
//Variables for holding values
int n;
String temp;
// Going one by one the elements in the array
for(int g = 0; g < array.size(); g++){
//Getting the array size from the file and giving the array name a size
n = array.size();
String names[] = new String[n];
//Load all the names
for(int i = 0; i < n; i++) {
names[i] = array.get(g).getBookTitle();
}
//Bubble sort starts
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j]) > 0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
//Print sorted
System.out.println(names[n-1]);
}
return -1;
}
}
Outpout:
Captains
Romeo
Don
-1
and what I am aiming is Captains, Don, Romeo.
My book.txt contains is like this:
book
Any suggestion for me to fix it ? Thank you very much.
Bubble Sort Example
I linked a bubble sort example. You can click on Java to see a version in Java. And you can see there are differences between yours and theirs, even though they are very similar.
What I would do is do it manually. That is, grab some paper, write down what your array looks like then actually pretend you're the computer and see what you end up with. It will be a good exercise for you, and you'll probably figure out what you're doing wrong.
First of all, BubbleSort() is not an appropriate name for this method as all it does is reading the file and storing the content inside the list.
If this course is not an upper-level algorithms class, you could probably use java libraries to sort your list instead.
Something like this should work and produce the needed result:
Collections.sort(books);
Also, I usually just do the following:
List books = new ArrayList<>();
In case you have to implement bubble sort, please use the following link which shows how to use bubble sort to sort string arrays: https://www.geeksforgeeks.org/sorting-strings-using-bubble-sort-2/
For array A of 'n' elements A[n], then the first loop in bubble sort always ends with n-1.
The idea of bubble sort is to compare the adjacent elements and then swap if the are not in order (increasing / decreasing depending on the use case).
So, when i=n-1, as you mentioned in your first for loop=>j=n-1. We are basically comparing A[i=n-1] to A[j=n-1].
//Bubble sort starts
for (int i = 0; i < n-1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j]) > 0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
you can try a quick dry-run whenever you are stuck in such problems by substituting with small numbers and writing the loop content on paper. Helps a lot to learn and to build logic. :)
So after a couple days working on it I have come with a working solution thanks to everyone.
public class Alphabetical_Order {
//Global variables
public static String input;
public static int bookId;
public static String bookTitle;
public static String authorName;
public static boolean isAvailable;
//Creating an array list;
public static ArrayList<Book> books = new ArrayList<>();
public static void main(String[] args)
{
loadData();
int n = 0;
String temp;
//Scanner s = new Scanner(System.in);
System.out.print("Enter number of names you want to enter:");
//get size of arraylist
for (int g = 0; g < books.size(); g ++) {
n = books.size();
}
String names[] = new String[n];
//Names to be get from user
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
for(int i = 0; i < n; i++)
{
names[i] = books.get(i).getAuthorName();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j])>0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(names[i] + ",");
}
System.out.print(names[n - 1]);
}
public static void loadData() {
try {
//Here we start reading our file
BufferedReader br = new BufferedReader(new FileReader("Book.csv"));
//This header string will allow to store the header so does not mistach with getter and setters.
String header = br.readLine();
//This string will read the lines.
String contentLine = br.readLine();
//Giving our array name data;
String [] data;
//Here we loop to continue the reading of data for each array box.
while (contentLine != null) {
data = contentLine.split(",");
bookId = Integer.parseInt(data[0]);
bookTitle = data[1];
authorName = data[2];
isAvailable = Boolean.parseBoolean(data[3]);
books.add(new Book(bookId, bookTitle, authorName, isAvailable));
contentLine = br.readLine();
}
}catch (IOException ex) {
Logger.getLogger(SearchBookAuthor.class.getName()).log(Level.SEVERE, null,ex);
}
}}

Sorting array of names alphabetically using compareTo()

I am trying to sort an array of names alphabetically by using compareTo() and a method String addSort(String name) but I get an error when compiling at the line "return name", saying that my "variable "name" may not be initialized" when it already is.
I've made the method and the code for sorting alphabetically which I think should be correct when using compareTo() as a way of sorting the array. (The array "moreFriends" is a new array which doubles the size of the original array "friends" when it gets full) (Note this is not all of the code)
public class SimpleDataStructure{
private String [] friends;
private String [] moreFriends;
private int counter;
public SimpleDataStructure()
{
friends= new String[5];
counter=0;
}
public String addSort(){
String name;
for(int i = 0; i < moreFriends.length; i++){
for(int j = i + 1; j < moreFriends.length; j++){
if(moreFriends[i].compareTo(moreFriends[j]) > 0){
String temp = moreFriends[i];
moreFriends[i] = moreFriends[j];
moreFriends[j] = temp;
}
}
}
System.out.println("Names in sorted order:");
for(int i = 0; i < moreFriends.length -1; i++){
System.out.println(moreFriends[i]);
}
return name;
}
public static void main( String [] arg){
SimpleDataStructure sortedfriends = new SimpleDataStructure();
System.out.println(sortedfriends.addSort(name));
}
This is the error message I get when i try to compile the program:
SimpleDataStructure.java:85: error: variable name might not have been initialized
return name;
^
1 error
When I expect the output to eventually be:
(unsorted)
Kalle
Bob
Carl
Alice
Lewis
(sorted)
Alice
Bob
Carl
Kalle
Lewis
You need declare youre function like this:
public String addSort(String name){
and delete the string declaration:
String name;
and you don't put value for name.
You can solved your problem using this:
String [] a="a","v","b";
Arrays.sort(a);
The reason that you are getting the compile error is because you never set a value to the String name before trying to use it.
You should be passing in the value like you have in your description addSort(String name). This will remove that error.
I do not see a reason why you are returning the String in your function.
This function does not appear to add the passed in name either.
Hope this helps!
import java.util.*;
class SimpleDataStructure {
public String[] addSort(String moreFriends []) {
for (int i = 0; i < moreFriends.length; i++) {
for (int j = i + 1; j < moreFriends.length; j++) {
if (moreFriends[i].compareTo(moreFriends[j]) > 0) {
String temp = moreFriends[i];
moreFriends[i] = moreFriends[j];
moreFriends[j] = temp;
}
}
}
return moreFriends;
}
public static void main(String[] arg) {
Scanner input=new Scanner(System.in);
SimpleDataStructure sortedFriends = new SimpleDataStructure();
String [] name =new String[5];
System.out.println("Enter name(s): ");
for (int i = 0; i < name.length; i++) {
name[i]=input.nextLine();
}
System.out.println("Unsorted:");
System.out.println(Arrays.toString(name));
System.out.println("Sorted:");
System.out.println(Arrays.toString(sortedFriends.addSort(name)));
}
}
And if you want the names to print out line by line, just create a for loop instead of Arrays.toString
Or you could even use Arrays.sort , which is much simpler
import java.util.Arrays;
class SimpleDataStructure {
public String[] addSort(String moreFriends []) {
for (int i = 0; i < moreFriends.length; i++)
Arrays.sort(moreFriends);
return moreFriends;
}
public static void main(String[] arg) {
SimpleDataStructure sortedFriends = new SimpleDataStructure();
String [] name ={"Kalle", "Bob","Carl","Alice", "Lewis"};
System.out.println("Unsorted:");
System.out.println(Arrays.toString(name));
System.out.println("Sorted:");
System.out.println(Arrays.toString(sortedFriends.addSort(name)));
}
}
I changed my arrays "friends" and "moreFriends" to static in my class.
Now my code looks something like this when im calling my method in my main:
SimpleDataStructure sorted = new SimpleDataStructure();
System.out.println("Sorted:");
System.out.println(Arrays.toString(sorted.addSort()));
And this is my method:
public String[] addSort() {
for (int i = 0; i < moreFriends.length; i++) {
for (int j = i + 1; j < moreFriends.length; j++) {
if (moreFriends[i].compareTo(moreFriends[j]) > 0) {
String temp = moreFriends[i];
moreFriends[i] = moreFriends[j];
moreFriends[j] = temp;
}
}
}
return moreFriends;
}
However i get this error message now:
Unsorted:
Kalle Bob Carl Alice Lewis
Sorted:
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(Unknown Source)
at SimpleDataStructure.addSort(SimpleDataStructure.java:75)
at SimpleDataStructure.main(SimpleDataStructure.java:108)
You need to include your variable name, that holds the names, inside addSort
SimpleDataStructure sorted = new SimpleDataStructure();
System.out.println("Sorted:");
System.out.println(Arrays.toString(sorted.addSort(**HERE**)));

Return strings in array that begin with the initial passed

I have a .txt file which has data for states as given below:
AL,Alab,4860
AK,Alas,7415
AZ,Ariz,6908
AR,Arka,2988
I have made a function which counts how many states there are that start with the initial passed as such:
public int CInitial(char initial) {
int total = 0;
for(int i = 0; i < states.length; i++) { //states is an array which includes all states present in the .txt file
String testString = states[i].getName(); // getName gets the name of the states present in the .txt file
char[] stringToCharArray = testString.toCharArray();
for (char output : stringToCharArray) {
if(initial == output) {
total++;
}
}
}
return total;
}
This would return the number 4 if "A" is passed and 0 if any other initial is passed as there are 4 states that begin with the letter "A".
Now how can I create a new function that passes a character and returns the name of all the states that begin with that character? For Instance this is the initial return type needed for this, however I'm having troubles starting this. Is the process identical to the countStatesCountByInitial function I created?
public State[] CByInitial(char initial) {
return new State[] {}; //to be completed
}
Yes, it will be very similar to the countStatesCountByInitial. The main difference is each time you find a match, you want to add the state into the array. Since we don't know the size of the array beforehand, we may want to use a List instead.
public State[] getStatesCountByInitial(char initial) {
ArrayList<State> found = new ArrayList<>();
// this is the same as before
for(int i = 0; i < states.length; i++) {
String testString = states[i].getName();
char[] stringToCharArray = testString.toCharArray();
for (char output : stringToCharArray) {
if(initial == output) {
// except here when you find a match, you add it into the list
found.add(states[i]);
}
}
}
// return as array
return found.toArray(new State[found.size()]);
}
As suggested by Patrick, we can avoid using List by using countStatesCountByInitial to initialize the size of the states.
public State[] getStatesCountByInitial(char initial) {
int matchSize = countStatesCountByInitial(initial);
States[] found = new States[matchSize];
int foundIndex = 0;
// this is the same as before
for(int i = 0; i < states.length; i++) {
String testString = states[i].getName();
char[] stringToCharArray = testString.toCharArray();
for (char output : stringToCharArray) {
if(initial == output) {
// except here when you find a match, you add it into the array
found[foundIndex] = states[i];
foundIndex++;
}
}
}
// return the array
return found;
}
You can done both operations simply by one method.
public static ArrayList<State> getStatesCountByInitial(char initial) {
ArrayList selectedStates = new ArrayList<State>();
for(int i = 0; i < states.length; i++) {
if(states.charAt(0) == initial){
selectedStates.add(states[i]);
}
}
return selectedStates;
}
This method will return a arraylist.
If you want to get the count, call this method and get the size of the array.
ArrayList<State> statesNew = getStatesCountByInitial('A');
int count = statesNew.size();

Sort Array by Alphabetical order using SelectionSort without Array.sort

I am referencing my code to mathebits website on SelectionSorting, changing the variables accordingly from int to String for my case, and adding in sort by alphabetical order as well.
Below is my current code for SelectionSort of students by lastName:
public static void SelectionSort(Student[] st) {
int i, j, first;
String temp;
String jLastName = "";
String firstLastName = "";
String iLastName ="";
for (i = st.length - 1; i > 0; i--) {
first = 0;
for (j = 1; j <= i; j++)
{
if (st[j].getLastName() != null) {
jLastName=st[j].getLastName();
if (st[first].getLastName() != null) {
firstLastName = st[first].getLastName();
if ((jLastName.compareToIgnoreCase(firstLastName)) > 0) {
first = j;
}
}
}
}
iLastName = st[i].getLastName();
temp = firstLastName;
firstLastName = iLastName;
iLastName = temp;
}
}
The code does not give me error. However, the output does not show that it has been sorted according to alphabetical order.
You cant compare two String like number, instead use compareTo method in String like:
if (st[..].getLastName().compareTo(..) < 0) {..
Also to change value, you need to have new Setter method in Student like:
public void setLastName(String name) {
this.name = name;
}
And then you could call it like:
st[..].setName(st[i].getName());

Set Method And Get Method Of A Fixed Size Array

I'm a bit mixed up on how to apply the 'sets' and 'gets' methods for a fixed array. Here is some of my work in Netbeans:
//creating 5 fixed arrays of size 10
private String [] itemnames = new String [10];
private String [] itemcodes = new String [10];
private String [] category = new String [10];
private String [] quantity = new String [10];
private Double [] sellingprice = new Double [10];
//initialising each array to null in the class constructor
for (int i = 0; i < 10; i++){
itemnames[i] = "";
}
for (int i = 0; i < 10; i++){
itemcodes[i] = "";
}
for (int i = 0; i < 10; i++){
category[i] = "";
}
for (int i = 0; i < 10; i++){
quantity[i] = "";
}
for (int i = 0; i < 10; i++){
(Double.parseDouble(sellingprice[i])) = 0;
}
Now, i'm stuck in the set method and the get method of each array. Any help please?
Thanks :)
You make set and get methods according to what you want to do (or later be able to do) with the arrays.
If you want to be able to retrieve an array into another class, you could make a get method like this:
public String[] getItems()
{
return itemnames;
}
If on the other hand you only want other classes to get the specific items in your arrays, one method might look like this:
public String getItemMatchingCode(String code)
{
for(int i = 0; i < ARR_LENGTH; i++)
{
if(code.equals(itemcodes[i]) return itemnames[i];
}
}
Or you might want to set and get the different values based on ideces:
public String getItemnameAt(int i)
{
return itemnames[i];
}
public void setItemnameAt(int i, String newItemname)
{
itemnames[i] = newItemname;
}
Sidenotes:
You are not "//initialising each array to null in the class constructor", they are that by default. What you are doing is filling them with empty strings, which in most cases is unnecessary.
When iterating through the arrays and filling them with values you can do them all in one loop.
for (int i = 0; i < 10; i++)
{
itemnames[i] = "";
itemcodes[i] = "";
category[i] = "";
}
Edit:
Also consider using a constant when declaring the size of the arrays, like so:
private static final int ARR_SIZE = 10;
private String[] array = new String[ARR_SIZE];

Categories

Resources