i am not an expert in java, but i need to solve this problem/activity for my course subject, that's why i really need your help guys. I have a programming problem. thing is i can't figure out what method or java codes should i use for this problem:
Create a class address book that can contain 100 entries of Name, Address, contact number and email address.
You should provide the following methods for the address book:
Add entry, Delete entry, View all entries and Update an entry
UPDATE: this is the codes I got so far
I am thinking i could use 2d array for this but, as soon as i start coding i can't really continue further, I don't know if its possible to use array or not in this kind of activity. I tried searching for other java codes but the more I learned new techniques or codes that might be possible, the more i got confused on WHAT codes must I use!
if anyone can help me build the coding for this activity I would really apprecaite and will surely study how the hell will/can YOU do it! because im really interested in learning Java, I just need some help to realize how should i DO this. thanks in advance!
THIS ARE THE CODES I'VE GOT SO FAR:
the capability of these program is only for adding editing viewing and deleting NAMES, iam still figuring out how to add dimensions to my array or should I add? or if not array? HoW? how am I supposed to answer this activity prior tto its REQUIREMENTS :(
package javaactivities;
import java.util.*;
import java.util.Scanner;
public class AddressBook {
static List<String> l=new ArrayList<String>();
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
boolean y=true;
do{
System.out.println("Enter \n1 to add an entry\n2 to edit entry");
System.out.println("3 to delete an entry\n4 to view entries\n5 to exit");
System.out.print("enter your choice: ");
int choice=in.nextInt();
switch(choice)
{
case 1:
insert();
break;
case 2:
edit();
break;
case 3:
delete();
break;
case 4:
print();
break;
case 5:
toexit();
break;
default:
System.out.println("bad input");
break;
}
System.out.println("want to process more? y/n");
String x=in.next();
char ch=x.charAt(0);
if( ch=='n')
y=false;
}
while(y!=false);
}
static public void insert(){
Scanner in=new Scanner(System.in);
boolean y=true;
do{
System.out.println("enter name to add in list");
String entry=in.next();
l.add(entry);
System.out.println("want to insert more?y/n");
String x=in.next();
char ch=x.charAt(0);
if( ch=='n')
y=false;
}
while(y!=false);
}
static public void print(){
if(l.isEmpty())
System.out.println("list is empty ");
else
System.out.println("members of lists are:");
for(int i=0 ; i<l.size();i++)
System.out.println("Entry "+i+" : "+ l.get(i)+" ");
}
static public void edit(){
Scanner in=new Scanner(System.in);
String num2;
System.out.println("enter name you want to add");
num2=in.next();
try{
System.out.println("enter entry # of the name you want to edit");
int num1=in.nextInt();
l.set(num1, num2);
}catch(IndexOutOfBoundsException e){
System.err.println("caught IndexOutOfBoundsException: specified position is empty "+e.getMessage());
}
}
static public void delete(){
Scanner in=new Scanner(System.in);
System.out.println("enter entry # you want to delete");
int num=in.nextInt();
l.remove(num);
}
static public void toexit(){
System.exit(0);
}
}
First, implement all the required classes, two in your case:
AddressBook
Entry
The skeleton could be something like that
public final class AddressBook {
public static final class Entry {
private String name;
private String address;
private String contactNumber;
private String email;
private Entry(String name, String address, String contactNumber, String email) {
this.name = name;
this.address = address;
this.contactNumber = contactNumber;
this.email = email;
}
public String getName() {return name;}
public String getAddress() {return address;}
public String getContactNumer() {return contactNumber;}
public String getEmail() {return email;}
}
private ArrayList<Entry> entries = new ArrayList<Entry>();
public AddressBook() {;}
public int size() {return entries.size();}
public int get(int index) {return entries.get(index);}
...
public Entry add(String name, String address, String contactNumber, String email) {
Entry entry = new Entry(name, address, contactNumber, email);
entries.add(entry);
return entry;
}
...
}
In order to implement viewAll() you could choose to override toString() methods in both classes, to delete() it seemes that you have to implement find() as well etc. Then just use these classes
public final class Main {
private static AddressBook book = new AddressBook();
public static void main(String[] args) {
...
switch(choice) {
case 1:
book.add(...);
break;
case 2:
book.delete(...);
break;
...
}
System.out.println(book.toString());
...
}
}
As you have several entries to store my suggestion is a linked list. Linked list is a data structure where you can store multiple entries.Java provide a
http://www.mycstutorials.com/articles/data_structures/linkedlists
this link will help you with linked list.
Related
I'm learning the AP CSA course and tried to print these arrays. It keeps saying "can't find symbol" and not gonna lie I have absolutely no idea what that means.
//ArrayList:
public class al{
public static void main(String[] args){
List l = new ArrayList();
System.out.print(l.size());
}
}
//2DArray:
public class arrays{
public static void main(String[] args){
int[][] arry = {{1,2,3},
{1,2,3},
{1,2,3}};
printArray(arry);
}
}
In your first program to print the ArrayList, it is failing because you need to import the List and ArrayList in your program, please try this
import java.util.ArrayList;
import java.util.List;
public class al{
public static void main(String[] args){
List l = new ArrayList();
System.out.print(l.size());
}
}
In the second program the printArray method you called is missing in definition, i.e you have to define the printArray method in your class, you are using it from method main then you need to declare it static like below
static void printArray(int[][] arr){
for(int i=0; i<arr.length; i++){
String row = "";
for(int j=0; j<arr[0].length;j++){
row+=arr[i][j]+" ";
}
System.out.println(row);
}
}
Also while you are learning, please also read about the naming conventions in java (i suppose you are learning java), like a Class name should start from a capital letter.
I have converted a list of JSON objects to a generic list.
The Data structure on the items is as following
public class Person
{
private string Name;
private int Age;
private string Weightloss;
}
The Weightloss string is of type "109-102" and I need to calculate how much each person has lost in weight since they signed up. I my examlpe it'd be 7. How to I, using LINQ Method syntax, calculate each weight loss (or gain). I assume I'll need to split up the string but I'm not really sure how
Rather odd question, but if Linq is what you want, here is how one can go about it:
Create a function inside your class to calculate the weight difference:
public class Person
{
//Constructor
public Person(string name, int age, string weightLoss)
{
Name = name;
Age = age;
Weightloss = weightLoss;
}
public string Name;
private int Age;
private string Weightloss;
/// <summary>
/// Calculates the weight difference from the WeightLoss property.
/// </summary>
/// <returns></returns>
public int GetWeightLoss()
{
//Get the values
var parts = Weightloss.Split('-')
.Select(value => Convert.ToInt32(value))
.ToArray();
//Calculate the difference
var difference = parts[0] - parts[1];
return difference;
}
}
Not clean and I personally dislike it but it's homework so...
I added a constructor for initialization and changed the Name field to public so you can output it:
var list = new List<Person>()
{
new Person("Juan", 30, "109-102"),
new Person("Max", 35, "119-103"),
new Person("John", 40, "109-105"),
};
//Figure out the largest loss
var maxLossPerson = list.OrderByDescending(p => p.GetWeightLoss()).First();
Console.WriteLine($"{maxLossPerson.Name} lost the most with {maxLossPerson.GetWeightLoss()} pound(s)");
Output:
Max lost the most with 16 pound(s)
You're either going to use a string split or a regular expression.
Assuming your string is always formatted "Weight1-Weight2", a string split would be fairly simple:
public int[] ParseWeights(string weightString) {
var weights = weightString.Split('-');
var beginningWeight = Convert.ToInt32(weights[0]);
var endingWeight = Convert.ToInt32(weights[1]);
return new int[] {beginningWeight, endingWeight};
}
Add another property to Person:
public class Person
{
private string Name;
private int Age;
private string Weightloss;
public int WeightLost
{
get
{
int[] values = Weightloss.Split('-').Select(i => int.Parse(i)).ToArray();
return values[0] - values[1];
}
}
}
If you look for a even more Linq way, you can use the follow way:
private string Weightloss;
public int WeightLossInt => Weightloss
.Split('-')
.Select((value, index) => index == 0 ? int.Parse(value) : -int.Parse(value))
.Sum();
}
im very new to this, working on some ap comp sci problems
i want to store user inputs into an array list of strings, but when i print the array im trying to fill, i just get something like [, , , ] how can i fix this?
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter words, followed by the word \"exit\"");
Scanner in = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
WordList test = new WordList(words);
while(!in.next().equals("exit"))
{
words.add(in.nextLine());
}
System.out.println(words);
The problem you have is that in the while loop condition you read what the user typed in the input, and then inside the while you read am empty line.
You need to read the line only inside the while, and break the loop if the user typed 'exit'. As follows:
public static void main(String[] args) {
System.out.println("Enter words, followed by the word \"exit\"");
Scanner in = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
while (true) {
String str = in.nextLine();
if ("exit".equals(str)) {
break;
}
words.add(str);
}
System.out.println(words);
}
Ive had a deeper look at the storage system now, but I just can't get it to work properly. The data seems to be saved, the saved data is definitely not empty and I am still getting a java.lang.NullPointerException.
So here is my Class i want to saved and later read to the Storage.
Band is a trivial Class with name and genre String.
public class Band implements Externalizable{
String name;
String genre;
public Band(String bnd, String gen){
this.name = bnd;
this.genre = gen;
}
public Band() {
}
public String getName(){
return this.name;
}
public String getGenre() { return this.genre; }
public void setName(String name) {
this.name = name;
}
public void setGenre(String genre) {
this.genre = genre;
}
#Override
public String toString(){
String s;
s = this.name;
return s;
}
public int getVersion(){
return 1;
}
#Override
public void externalize(DataOutputStream out) throws IOException {
Util.writeUTF(name, out);
Util.writeUTF(genre, out);
}
#Override
public void internalize(int version, DataInputStream in) throws IOException {
name = Util.readUTF(in);
genre = Util.readUTF(in);
}
public String getObjectId(){
return "Band";
}
}
BandList is just a Class with an ArrayList the Bands are added to.
public class BandList implements Externalizable{
List <Band> bandList;
public List getBandList(){
return this.bandList;
}
public BandList(){
bandList = new ArrayList<Band>();
}
public void setBandList(List<Band> bandList) {
this.bandList = bandList;
}
public int getVersion(){
return 1;
}
#Override
public void externalize(DataOutputStream out) throws IOException {
Util.writeObject(bandList, out);
}
#Override
public void internalize(int version, DataInputStream in) throws IOException {
bandList = (ArrayList<Band>) Util.readObject(in);
}
public String getObjectId(){
return "BandList";
}
}
So, in some other class where the user filled in some TextFields, the band gets added to the BandList and therefore I call saveListsToStorage();
public void saveListsToStorage(){
Storage.getInstance().clearStorage();
Storage.getInstance().writeObject("Bands", bandList);
}
So now, when starting the App, the App is looking for Data in the Storage, if found, it will return the BandList Object stored, otherwise it will return a new BandList Object.
Before that, I regist the Classes with
Util.register("Band", Band.class);
Util.register("BandList", BandList.class);
and finally call this method in the main at the beginning:
public BandList loadSavedBandList() {
String[] temp = Storage.getInstance().listEntries();
for (String s : temp) {
if (s.equals("Bands") == true) {
BandList tempBand = (BandList) Storage.getInstance().readObject("Bands");
return tempBand;
}
}
return new BandList();
}
After saving and then loading it throws the NullPointer exception and I have no clue why. I now used ArrayList instead of LinkedList as Shai told me and I implemented the Externalizable Interface as told in the guide.
Maybe some of you can tell me whats wrong here.
Edit:
Here is the Exception:
java.lang.NullPointerException
at com.rosscode.gehma.Menu_Form.updateBandContainer(Menu_Form.java:95)
at com.rosscode.gehma.Menu_Form.<init>(Menu_Form.java:73)
at com.rosscode.gehma.main.start(main.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.codename1.impl.javase.Executor$1$1.run(Executor.java:106)
at com.codename1.ui.Display.processSerialCalls(Display.java:1152)
at com.codename1.ui.Display.mainEDTLoop(Display.java:969)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
Edit 2, Line 95:
if(bandList.getBandList().isEmpty() == false) {
for (int i = 0; i < bandList.getBandList().size(); i++) {
Button temp = new Button(bandList.getBandList().get(i).toString());
temp.addActionListener((e) ->
nextStep()
);
listCont.add(temp);
}
menuForm.revalidate();
}
NullPointerExceptions are pretty amazing things, because not only are they easy to figure out, they even show you the exact line where they happen. All you have to do is look at anything left of a . and check if it's null. As soon as you find it, you find the problem.
So let's look at your code. Sadly I don't know which of those lines is line 95 but I'm guessing it's the one starting with if.
That means either bandList is null or bandList.getBandList() returns null. A quick look into getBandList() shows that it won't be null, as you initialize the list in the constructor of your BandList class. Which only leaves bandList.
Sadly you didn't post where you got that from, but I'm gonna assume you just did something like:
BandList bandList = loadSavedBandList();
So let's look into that method. (btw: I say a bit more about where you have to look if you didn't do this at the end of this answer).
If you couldn't find your key, it would return a new BandList, which couldn't be null. So it has to find something, meaning the key exist but the value is null.
So let's take another step and look at how you save things in the first place.
public void saveListsToStorage(){
Storage.getInstance().clearStorage();
Storage.getInstance().writeObject("Bands", bandList);
}
Now "in some other class" doesn't really explain much. But since you read a null, it means you are writing a null here. Which would mean in this "other class", at least in this method, bandList = null.
With the code you gave, it's impossible for me to look deeper into this issue, but it seems like in "that other class", you got a class attribute named bandList but fail to put anything inside it.
Or maybe you saved everything right, but didn't call
BandList bandList = loadSavedBandList();
in some form or another before your if, which would also pretty much explain the problem. I mean... if you never load the bandList, it will obviously be null...
Just wondering, is it not allowed to use Starts/EndsWith functions with Scanner? I'm trying to make a simple program where some elements from the set of array that I will provide will be printed out using those functions. But obviously there is an error that I don't know where it is. Please help
import java.util.Scanner;
public class test {
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
String[] animals = new String[5];
System.out.println("Enter animal type");
for (String j : animals){
if (j.startsWith("do"))
System.out.println(j);
}
}
}