// The section below is what raises the error, I am modifying a simple banking application i found online. I am very new to Java, about 3 days I've been dabbling in it, and thought this would be a good little activity to do to get me used to the syntax of the code and methods etc. I have been looking at this problem for about a day now and cant figure out what exactly the problem is. The only thing that would come to mind would be that the showMenu() method is possibly out of scope for the main section im referring it in, however im not to sure.
P.S. If i have missed anything out that could be of us, i apologise as i have never posted on here before!
EDIT - The new error is:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The constructor BankApplication.BankAccount(String, String) is undefined
The method showMenu() is undefined for the type BankApplication.BankAccount
at BankApplication.main(bank.java:9)
public static void main(String[] args)
{
BankAccount obj1 = new BankAccount("Ye Ma", "X Æ A-12");
obj1.showMenu();
}
//The showMenu code
void showMenu()
{
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the Bank");
System.out.println("Your Customer ID is: " + cID);
System.out.println("");
System.out.println("1. To view you Bank Balance.");
System.out.println("2. To make a deposit.");
System.out.println("3. To make a withdrawel.");
System.out.println("4. To view your previous transaction.");
System.out.println("5. To exit.");
do
{
System.out.println("----------------------------------------------------------------------");
System.out.println(" Choose an option ");
System.out.println("----------------------------------------------------------------------");
System.out.println("");
option = sc.nextInt();
if(option == 1)
{
System.out.println("----------------------------------------------------------------------");
System.out.println(" Your bank balance is: " + balance);
System.out.println("----------------------------------------------------------------------");
break;
}
else if(option == 2)
{
System.out.println("----------------------------------------------------------------------");
System.out.println("How much would you like to deposit?");
System.out.println("----------------------------------------------------------------------");
int amount = sc.nextInt();
deposit(amount);
break;
}
else if(option == 3)
{
System.out.println("----------------------------------------");
System.out.println(" How much would you like to withdraw?: ");
System.out.println("----------------------------------------------------------------------");
int amount = sc.nextInt();
withdraw(amount);
break;
}
else if(option == 4)
{
System.out.println("----------------------------------------------------------------------");
System.out.println("Your previous transaction was: " + getPreviousTransaction(amount));
System.out.println("----------------------------------------------------------------------");
System.out.println("");
}
else if(option == 5)
{
System.out.println("**********************************");
System.out.println(" END OF APPLICATION ");
System.out.println("**********************************");
}
else
{
System.out.println("Invalid option, please choose a valid option.");
}
}while(option != 5);
i think you are trying to call showMenu() which is not available in BankAccount class.
Related
I'm very new at coding and I'm having some issues. I'd like to display the followers of followers of ..... of followers of some specific users in Twitter. I have coded this and I can set a limit for the depth. But, while running the code with a small sample, I saw that I run into the same users again and my code re-display the followers of these users. How can I avoid this and skip to the next user? You can find my code below:
By the way, while running my code, I encounter with a 401 error. In the list I'm working on, there's a private user, and when my code catches that user, it stops. Additionally, how can I deal with this issue? I'd like to skip such users and prevent my code to stop.
Thank you for your help in advance!
PS: I know that I'll encounter with a 429 error working with a large sample. After fixing these issues, I'm planning to review relevant discussions to deal with.
public class mainJava {
public static Twitter twitter = buildConfiguration.getTwitter();
public static void main(String[] args) throws Exception {
ArrayList<String> rootUserIDs = new ArrayList<String>();
Scanner s = new Scanner(new File("C:\\Users\\ecemb\\Desktop\\rootusers1.txt"));
while (s.hasNextLine()) {
rootUserIDs.add(s.nextLine());
}
s.close();
for (String rootUserID : rootUserIDs) {
User rootUser = twitter.showUser(rootUserID);
List<User> userList = getFollowers(rootUser, 0);
}
}
public static List<User> getFollowers(User parent, int depth) throws Exception {
List<User> userList = new ArrayList<User>();
if (depth == 2) {
return userList;
}
IDs followerIDs = twitter.getFollowersIDs(parent.getScreenName(), -1);
long[] ids = followerIDs.getIDs();
for (long id : ids) {
twitter4j.User child = twitter.showUser(id);
userList.add(child);
getFollowers(child, depth + 1);
System.out.println(depth + "th user: " + parent.getScreenName() + " Follower: " + child.getScreenName());
}
return userList;
}
}
I guess graph search algorithms can be implemented for this particular issue. I chose Breadth First Search algorithm because visiting root user's followers at first would be better. You can check this link to additional information about algorithm.
Here is my implementation for your problem:
public List<User> getFollowers(User parent, int startDepth, int finalDepth) {
List<User> userList = new ArrayList<User>();
Queue<Long> queue = new LinkedList<Long>();
HashMap<Long, Integer> discoveredUserId = new HashMap<Long, Integer>();
try {
queue.add(parent.getId());
discoveredUserId.put(parent.getId(), 0);
while (!queue.isEmpty()) {
long userId = queue.remove();
int discoveredDepth = discoveredUserId.get(userId);
if (discoveredDepth == finalDepth) {
continue;
}
User user = twitter.showUser(userId);
handleRateLimit(user.getRateLimitStatus());
if (user.isProtected()) {
System.out.println(user.getScreenName() + "'s account is protected. Can't access followers.");
continue;
}
IDs followerIDs = null;
followerIDs = twitter.getFollowersIDs(user.getScreenName(), -1);
handleRateLimit(followerIDs.getRateLimitStatus());
long[] ids = followerIDs.getIDs();
for (int i = 0; i < ids.length; i++) {
if (!discoveredUserId.containsKey(ids[i])) {
discoveredUserId.put(ids[i], discoveredDepth + 1);
User child = twitter.showUser(ids[i]);
handleRateLimit(child.getRateLimitStatus());
userList.add(child);
if (discoveredDepth >= startDepth && discoveredDepth < finalDepth) {
System.out.println(discoveredDepth + ". user: " + user.getScreenName() + " has " + user.getFollowersCount() + " follower(s) " + (i + 1) + ". Follower: " + child.getScreenName());
}
queue.add(ids[i]);
} else {//prints to console but does not check followers. Just for data consistency
User child = twitter.showUser(ids[i]);
handleRateLimit(child.getRateLimitStatus());
if (discoveredDepth >= startDepth && discoveredDepth < finalDepth) {
System.out.println(discoveredDepth + ". user: " + user.getScreenName() + " has " + user.getFollowersCount() + " follower(s) " + (i + 1) + ". Follower: " + child.getScreenName());
}
}
}
}
} catch (TwitterException e) {
e.printStackTrace();
}
return userList;
}
//There definitely are more methods for handling rate limits but this worked for me well
private void handleRateLimit(RateLimitStatus rateLimitStatus) {
//throws NPE here sometimes so I guess it is because rateLimitStatus can be null and add this conditional expression
if (rateLimitStatus != null) {
int remaining = rateLimitStatus.getRemaining();
int resetTime = rateLimitStatus.getSecondsUntilReset();
int sleep = 0;
if (remaining == 0) {
sleep = resetTime + 1; //adding 1 more second
} else {
sleep = (resetTime / remaining) + 1; //adding 1 more second
}
try {
Thread.sleep(sleep * 1000 > 0 ? sleep * 1000 : 0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
in this code HashMap<Long, Integer> discoveredUserId is used to prevent program checking same users repeatedly and storing in which depth we faced with this user.
and for private users, there is isProtected() method in twitter4j library.
Hope this implementation helps.
I'm Developing windows phone 8 application.
In my application i'm using listbox.I bind listbox value form Webservice. Webservice return json format data's.
The webservice return 40 to 50 records.I bind all the values into listbox.
Everthing work fine.Only on first time run.
For example:-
My project page structure.
1.welcomepage
2.Menu Page (it contain six buttons. click on any one particular button it's redirect to sub-menupage)
3.Sub-menupage(Six different page present)
In menu page Hotels button is present . if hotels button is clicked it's navigate to Hotels Page.
Now my problem is:-
First Time - welcomepage -> Menu Page -> HotelSubmenu [List of hotels is bind in listbox from webservice]
Now I goback to Menupage by click on hardwareback button.Now it's in Menu page
If i click again the same Hotels button
It show me the error
e.ExceptionObject {system.OutofMemoryException:Insufficient memory to continue the execution of the program.
[System.outofmemoryException]
Data {system.Collections.ListDictionaryInternal}
HelpLink null
Hresult -2147024882
Message "insufficient memory to continue the execution of the program"
My C# code for bind values in listbox
public void commonbind()
{
try
{
this.loadimg.Visibility = System.Windows.Visibility.Visible;
loadcheck();
string common_url = "http://xxxxxx.com/Service/bussinesscitynamesub.php?bcatid=" + businessid + "&cityname=" + cityname + "&bsubid=" + filterid;
WebClient common_wc = new WebClient();
common_wc.DownloadStringAsync(new Uri(common_url), UriKind.Relative);
common_wc.DownloadStringCompleted += common_wc_DownloadStringCompleted;
}
catch (Exception ex)
{
}
}
void common_wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
lbbusiness.Items.Clear();
var common_val = e.Result;
if (common_val != "null\n\n\n\n")
{
lbopen = 2;
var jsonconvertvalue = JsonConvert.DeserializeObject<List<common_bindclass>>(common_val);
List<common_bindclass> ls = new List<common_bindclass>();
ls = jsonconvertvalue;
for (int i = 0; i < ls.Count; i++)
{
lbbusiness.Items.Add(ls[i]);
}
this.loadimg.Visibility = System.Windows.Visibility.Collapsed;
loadcheck();
}
else
{
if (lbopen == 0)
{
MessageBoxResult resultmsg = MessageBox.Show("No Result present based on your current Location! " + System.Environment.NewLine + "Now showing result without Location based", "Sorry!", MessageBoxButton.OK);
if (resultmsg == MessageBoxResult.OK)
{
lbbusiness.Items.Clear();
cityname = "";
**commonbind();**
}
else
{
NavigationService.GoBack();
}
}
else if (lbopen == 1)
{
MessageBox.Show("No Result Present In this Categories");
LPfilter.Open();
}
else if (lbopen == 2)
{
MessageBox.Show("No Result Present In this City");
Lpcity.Open();
}
}
}
catch (Exception ex)
{
}
}
I try with following method for solve the memory exception
Try1:-
Clear the List box value before bind every time.
Try2:-
Create the new list every time
common_bindclass bind = new common_bindclass();
foreach (common_bindclass bind in jsonconvertvalue)
{
lbbusiness.Items.Add(bind);
}
I change the above code to
List<common_bindclass> ls = new List<common_bindclass>();
ls = jsonconvertvalue;
for (int i = 0; i < ls.Count; i++)
{
lbbusiness.Items.Add(ls[i]);
}
MY Output For single List
But my try's not help for me .
any one tell me how to solve it. or alternate way .
How to find in which line the error occur .[I try with break point but it's not help me]
import java.util.Scanner;
public class RPS
{
public void show()
{
int i;
System.out.println("1 - Rock 2 - Paper 3 - Scissor");
Scanner in = new Scanner(System.in);
i = in.nextInt();
double x = Math.random();
int y;
if(x<=0.33)
{
y=1;
}
else if(x>0.33 && x<0.67)
{
y=2;
}
else if(x>=0.67)
{
y=3;
}
for(;;)
{
if(i==y)
System.out.println("It's a draw!");
else if(i==1 && y==2)
System.out.println("Computer wins!");
else if(i==1 && y==3)
System.out.println("You win!");
else if(i==2 && y==1)
System.out.println("You win!");
else if(i==2 && y==3)
System.out.println("Computer wins!");
else if(i==3 && y==1)
System.out.println("Computer wins!");
else if(i==3 && y==2)
System.out.println("You win!");
else
System.out.println("Error!");
}
}
}
Whats wrong?
It gives an error that variable y might not have been intialised in the if's in the for loop.
I have assigned a value to y in the previous if-else section.
so why isnt it getting intialised?
javac is not smart enough to realize that the way your conditions are constructed, one of them will always be true.
You can rewrite your if-statements to make javac realize one branch will always be triggered:
int y;
if(x<=0.33)
{
y=1;
}
else if(x>0.33 && x<0.67)
{
y=2;
}
else // This only triggers when x >= 0.67, so no need to check
{
y=3;
}
Now javac sees that if the first two don't trigger, the last will, so y will always have a value.
You can alternatively add an else branch with an error, in case someone breaks the conditions:
int y;
if(x<=0.33)
{
y=1;
}
else if(x>0.33 && x<0.67)
{
y=2;
}
else if(x >= 0.67)
{
y=3;
}
else
{
// This should never happen
throw new IllegalArgumentException("Something's gone terribly wrong for " + x);
}
This also compiles, and if someone later decides to skew the numbers and turns the first condition into x <= 0.2 but forgets to update the other condition, you'll get an exception at runtime.
Ok this is the code for one section of my switch statement:
case 1: {
System.out.print("Member ID: ");
int key = in.nextInt();
while(members.findItemByKey(key) == -1){
System.out.print("That is an invalid member ID!\nEnter a new one: ");
key = in.nextInt();
}
System.out.print("ISBN: ");
int book = in.nextInt();
while(books.findItemByKey(book) == -1){
System.out.println("That book is not in the system.\nPlease make a new choice: ");
book = in.nextInt();
}
while(stock.findItemByKey(book) != -1){
try {
m = members.get(members.findItemByKey(key));
t = books.get(books.findItemByKey(book));
} catch (Exception e) {
e.printStackTrace();
}
if(m.checkOut(t) == true){
stock.removeItem(t);
}
}
}
Here is the method that is calling:
public int findItemByKey(int key){
for(E e: list)
{
if(e.getKey() == key){
return findItem(e);
}
}
return -1;
}
public int findItem(E item){
if (item == null){
for (int i = 0; i < numElements; i++)
if(list[i]==null)
return i;
}else {
for( int i = 0; i < numElements; i++)
if (item.equals(list[i]))
return i;
}
return -1;
}
Ok, I know there's a lot to look at here, but here's what's happening. When I enter an invalid member ID, it functions properly and keeps asking the user for a new member ID until a valid one is entered. Now when I enter a book, regardless of whether I enter a valid or invalid book, I am getting a null pointer exception thrown by this line:
if(e.getKey() == key)
books, members, and stock are all arraylists defined the same way in my code. I don't understand why I'm having this exception thrown with books and not with the members. The classes for book and member are defined the same way, both have the same getKey method within them.
Maybe there's just too much going on in this question for anyone to be able to really see what's going on. Basically I just can't understand why I get a null pointer exception with the one and not with the other.
Edit: Decided I should post the getKey() method for each class.
public int getKey()
{
return ISBN;
}
Is the one for books
public int getKey()
{
return memberId;
}
Is the one for members.
ISBN is the identifier for books and memberId is the identifier for my members. Everything looks like it's calling the same things, but it errors for books and not for members. Just don't get it.
Either this e is null or the value returned from the statement e.getKey() is null.
You have to make sure that the list doesn't contain a null element and then their keys should also be not-null.
If you want to ignore these values being null, you can do like:
if(e!=null && e.getKey()!=null && e.getKey() == key){
//statements here.
}
Another data structure I wrote under interview conditions. It is essentially a generic linked list that tracks the head and tail of the list (probably just for academic exercise, in RL life you'd just use List). Does anyone see any possible flaws or optimizations?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SingleLinkedHeadAndTail
{
class SingleListEntry<T>
{
public T Data { get; set; }
public SingleListEntry<T> Next {get; set;}
public SingleListEntry(T data)
{
Data = data;
}
}
public class SingleListExample<T>
{
private SingleListEntry<T> head;
private SingleListEntry<T> tail;
public int length { get; set; }
public T Head
{
get
{
if (head != null)
{
return head.Data;
}
return default(T);
}
}
public T Tail
{
get
{
if (tail != null)
{
return tail.Data;
}
return default(T);
}
}
public void Insert(T data)
{
if (head==null)
{
head = new SingleListEntry<T>(data);
tail = head;
length++;
}
else
{
tail.Next = new SingleListEntry<T>(data);
tail = tail.Next;
length++;
}
}
public void InsertAfter(T data, int position)
{
if (position < 0)
{
throw new Exception("no soup for you - position must be 0 or higher");
}
if (head == null)
{
throw new Exception("sorry, you cannot insert after nothing, the list is empty.");
}
if (position >= length) //we could allow this stuff and padd out the list etc, but for now...no soup.
{
throw new Exception("Position requested is > then the length of the list.");
}
if (position == length - 1) //just an inswer
{
Insert(data);
return;
}
SingleListEntry<T> newElement = new SingleListEntry<T>(data);
SingleListEntry<T> temp = GetElementAt(position);
newElement.Next = temp.Next;
temp.Next = newElement;
length++;
}
public T GetElement(int position)
{
return GetElementAt(position).Data;
}
private SingleListEntry<T> GetElementAt(int position)
{
SingleListEntry<T> temp = head;
//pop down N levels until position
int counter = 0;
while (counter < position)
{
temp = temp.Next;
counter++;
if (temp == null && counter < position) //should have been caught
{
throw new Exception(String.Format("{0} elements do not exist", position));
}
}
return temp;
}
public void Remove(int position)
{
if (position < 0)
{
throw new Exception("no soup for you - position must be 0 or higher");
}
if (head == null)
{
throw new Exception("sorry, you cannot remove from nothing, the list is empty.");
}
if (position >= length) //we could allow this stuff and padd out the list etc, but for now...no soup.
{
throw new Exception("Position requested is > then the length of the list.");
}
if (position == 0) //head
{
head = head.Next;
length--;
return;
}
SingleListEntry<T> temp;
temp = GetElementAt(position - 1);
if (position == length-1)
{
tail = temp;
tail.Next = null;
length--;
return;
}
temp.Next = temp.Next.Next;
length--;
}
}
class Program
{
static void Main(string[] args)
{
Test1();
Test2();
Test3();
}
public static void Test1()
{
SingleListExample<string> myList = new SingleListExample<string>();
myList.Insert("joe");
myList.Insert("mike");
myList.Insert("adam");
if (myList.Head != "joe") throw new Exception("fail");
if (myList.Tail != "adam") throw new Exception("fail");
if (myList.GetElement(1) != "mike") throw new Exception("fail");
}
public static void Test2()
{
SingleListExample<string> myList = new SingleListExample<string>();
myList.Insert("joe");
myList.Insert("mike");
myList.Insert("adam");
myList.InsertAfter("paul", 1);
myList.InsertAfter("john", 0);
myList.InsertAfter("nichole", 4);
if (myList.Tail != "nichole") throw new Exception("fail");
if (myList.Head!= "joe") throw new Exception("fail");
if (myList.GetElement(0) != "joe") throw new Exception("fail");
if (myList.GetElement(1) != "john") throw new Exception("fail");
if (myList.GetElement(2) != "mike") throw new Exception("fail");
if (myList.GetElement(3) != "paul") throw new Exception("fail");
if (myList.GetElement(4) != "adam") throw new Exception("fail");
if (myList.GetElement(5) != "nichole") throw new Exception("fail");
}
public static void Test3()
{
SingleListExample<string> myList = new SingleListExample<string>();
myList.Insert("joe");
myList.Insert("mike");
myList.Insert("adam");
myList.InsertAfter("paul", 1);
myList.InsertAfter("john", 0);
myList.InsertAfter("nichole", 4);
myList.Remove(0);
if (myList.Head != "john") throw new Exception("fail");
myList.Remove(myList.length-1);
if (myList.Tail != "adam") throw new Exception("fail");
myList.Remove(1);
if (myList.Head != "john") throw new Exception("fail");
if (myList.Tail != "adam") throw new Exception("fail");
if (myList.GetElement(0) != "john") throw new Exception("fail");
if (myList.GetElement(1) != "paul") throw new Exception("fail");
if (myList.GetElement(2) != "adam") throw new Exception("fail");
}
}
}
Implement an iterator. Your GetElementAt method is begging people to walk the list using Schlemiel the Painter's Algorithm.
To clarify: For each element in the list, GetElementAt has to start from the beginning and count out entries to the index of the entry you want. So getting the entries from 1 to...say..a million would (internally) involve running through the list a million times. Walking the list becomes an O(N^2) operation, which defeats one of the purposes of a list -- fast sequential access. Contrast that with an iterator, which would keep track of its place in the list and just get the next entry each time, avoiding the 0..n loop and making traversal a whole lot faster.
It looks fundamentally sound code (ignoring the design considerations of using Collection interafces like enumeration, indexers, etc)
All the validity checks could be put into a 'CheckValid' method that is simply called from your other methods. The compiler should have no problem inlining it, so you shouldn't see a performance degradation as a result (and of course, if performance is key, you'd use asserts, not runtime checks)
GetElementAt checks if it should throw the exception on every iteration. It could just check that the position value is within the list length before starting to enumerate items. (It will also crash if the list is empty and a nonzero position is passed in). It should really validate that position >= 0 too.
The code for Remove and InsertAfter could use a common method which returns the items at position and position-1. THis would reduce the code needed and halve the amount of testing required, although it would add a tiny 'avoidable overhead' to InsertAfter.
I'd tend to name Insert "Add" or "Append" myself, because it's not inserting.
You might consider returning the data from the item you Remove - otherwise you have to search the whole list twice to read a value and then remove it.