Cannot resolve nullpointerexception [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
System.out.println("Welcome to the Personal Contact Assistant!");
System.out.println("How can I help you?");
System.out.println("(add) (get) (quit)");
String option = input.nextLine();
Contact[] Contacts;
Contacts = new Contact[500];
int index = 0;
boolean finished = false;
while(finished==false){
switch (option) {
case "add":
System.out.println("You have selected add.");
Contact newContact = new Contact();//constructs new contact object called newContact
newContact.setNewInfo();//gathers input for newContact
System.out.println("Contact Will be Saved as:");
newContact.print();//prints gathered information
Contacts[index] = newContact;//saves contact to array
index++;//advances index
System.out.println("Can I do something else for you? (add) (get) (quit)");
option = input.nextLine();
break;
case "get":
System.out.println("You have selected get.");
System.out.println("Enter the contact's first name:");
String tempName;
tempName = input.nextLine();
for(int i=0; i<499; i++){
System.out.println(":"+i);
if(Contacts[i].getFirstName().equals(tempName)){
System.out.println("Contact Found:");
Contacts[i].print();}
}
System.out.println("Can I do something else for you? (add) (get) (quit)");
option = input.nextLine();
break;
These are add and get segments for a contact app I am working on. My Contact class contains methods for setting and getting name, address etc of contacts. I receive no compiler errors but while running the program I get a nullpointerexception error at the for loop. additionally the output will only print 1 number from the System.out.println(":"+i); line (which I added to find out how many loop iterations were actually happening), unless it finds a contact with that first name, in which case it returns the full contact information for each contact and then errors out. I just want it to complete the loop, print ever contact with that first name, and then go back to the main outer loop. Help?

If you run get() before manually adding 500 contacts, ghis line will throw when i exceeds the number of contacts you've added, since we go to 499 regardless of the number you have added.
if(Contacts[i].getFirstName().equals(tempName)){
Even if it finds the one you're looking for, it will continue on through 499. There are a few ways to fix it.
If it's expected that you'll always find it, stop when you find it.
Change the loop to:
for (i = 0; i < index; i++)
Use an ArrayList or other collection class, which manages size for you. Then your search can become:
for (Contact contact : Contacts) {

Related

Stack and Queue java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have to create a program that follow this instructions. create a Java stack consisting of four (4) book titles entered by the user. Pop the stack's elements one by one; each popped element will be added to a queue. Then, print the content of the queue.
and here is the code I have come up but yet didn't got the desired output.
import java.util.Scanner;
import java.util.Queue;
import java.util.Stack;
import java.util.LinkedList;
public class books {
public static void main(String[] args) {
Queue book = new LinkedList < String > ();
Stack < String > Title = new Stack < > ();
Scanner user = new Scanner(System.in);
System.out.println("Enter four book titles.");
int b = 4;
for (int i = 1; i <= b; i++) {
System.out.print("Book " + i + ":");
String Enter = user.nextLine();
Title.push(Enter);
Title.pop();
book.offer(Title);
}
System.out.println("New order of books:");
System.out.println(book);
}
}
The output is something like this
Enter four book titles.
Book 1:b1
Book 2:b2
Book 3:b3
Book 4:b4
New order of books:
[b1, b2, b3, b4]
What you were doing was every time enque the whole Title stack to the queue because pop method returns the fist element to be removed from the stack
Also ....
You have to first put ALL elements in the stack and then create one more loop to add them to the queue because this way you add the first element to the stack also as first element in the queue
After int b=4 this should be your code:
for(int i=1; i<=b;i++){
System.out.print("Book " + i + ":");
String Enter = user.nextLine();
Title.push(Enter);
}
for(int i=1;i<=b;i++){
book.offer(Title.pop);
}
instead off offer (which returns booolean) you could also use add() which throws exception if the capacity of the container is full , but your programm here is really simple so there is no way this will happen

Projekt Hangman game [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am a beginner in Java and I am working right now with a small projekt, a hangman game. One of the functions I am working on right now is a method where it takes a char input, check if the input is already added to the list or not, if it is, a message will show up saying "You have already used that character!" and the user will have to guess again, otherwise the input will be added to the list. My issue right now is that nothing is happening, inputs are not added to the list at all.
This is what I have done so far:
Any advice/help would be appreciated!
public static ArrayList<Character> getGuesses(ArrayList<Character> allGuesses, char input){
for (int i = 0; i < allGuesses.size(); i++) {
if (allGuesses.get(i) == input) {
System.out.println("You have already used that character!");
}else {
allGuesses.add(input);
}
}
return allGuesses;
}
You are adding the input character on each iteration as you search the collection. You should only add it after you have searched the collection and not found it.
for (int index = 0 ; index < allGuesses.size() ; ++index) {
if (allGuesses.get(index) == input) {
System.out.println("You already used that character!");
return allGuesses;
}
}
allGuesses.add(input);
return allGuesses;
However, this can be simplified by using the Collection contains method such that you do not employ a loop.
if (allGuesses.contains(input)) {
System.out.println("You already used that character!");
return allGuesses;
}
allGuesses.add(input);
return allGuesses;
If possible, consider switching the type of allGuesses to a Set implementation (e.g. HashSet). A Set seems to better match how you are using your collection and allows you to reduce this method to...
if (! allGuesses.add(input)) {
System.out.println("You already used that character!");
}
return allGuesses;

Homework problem on Java: I'm trying to run my program, it shows no error however when I try to run it it doesn't work? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My homework is to create a program that tells how many calories you consumed depending on the numbers of cookies you ate. But when I run the program, it doesn't show anything and I need it to work for my homework.
Here's the code for more context:
package cookie.calories;
import java.util.Scanner;
public class CookieCalories {
public static void main(String[] args) {
Scanner ob = new Scanner(System.in);
int TotalNumberOfCookiesPerBag = 40;
int CaloriesPerServing = 300;
int ServingsPerBag = 10;
//The next equation represent the number of cookies per servings
int NumberOfCookiesPerServings = TotalNumberOfCookiesPerBag/ServingsPerBag;
//number of calories per cookies
int CaloriesPerCookies =CaloriesPerServing/NumberOfCookiesPerServings;
Scanner ob2 = new Scanner(System.in);
System.out.println("This programm can determined how many calories you ate depending on the number of cookie you ate.");
//Below this sentence, the amount of calories will be determined
System.out.println("Enter the number of cookies you ate");
int Cookies = ob.nextInt(4);
int TotalCaloriesConsumed = CaloriesPerCookies*Cookies;
System.out.println(TotalCaloriesConsumed + "for the amount of cookies you ate");
}
}
The program shows me that I didn't made any error in the way I wrote my program but when I play it, it doesn't show anything in the output. Why?
When I run your program I get this output
This programm can determined how many calories you ate depending on the number of
cookie you ate.
Enter the number of cookies you ate
when I enter (for example) 4 and press enter I get this error
Exception in thread "main" java.util.InputMismatchException: For input string: "4"
under radix 4
at java.base/java.util.Scanner.nextInt(Scanner.java:2264)
at testasdf.Testasdf.main(Testasdf.java:38)
Not really sure why you have "ob.nextInt(4);" instead of "ob.nextInt();" should change your code to be nextInt();
So I am unsure of why nothing is showing up for you, are you sure you have a output screen set up?
What IDE are you using?
Remove the '4' from the nextInt method params.
int Cookies = ob.nextInt();
Also you don't need another Scanner object, you can use the same one to get input from the user multiple times, so you can remove this from your code.
Scanner ob2 = new Scanner(System.in);

Can't reach information Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm writing a program with 3 options. So the first one is about the employee- (create / remove / update / get information about employee / save to file). Before creating a new employee I have to choose his type(programmer or qa)(difference between them is that programmer have a specific programming language and qa have amount of worked hours). So moving forward when I create a new user I have to enter name / surname / age / prog.language;
The second option in my program is that I can create a team which must be made from 3 employees. So from a list of employees you select one for team lead and other 2 for 'workers'.
And the last one is that you can create a task.
(you need to give a name for task, specific language which is required from a second team member and amount of worked hours from a third member). So this task can be later assigned to a specific team.
So lets talk about my problem right now:
Creating new employees, making new teams works 100%, also creating new tasks works fine as well, but when I try to check does my selected team meets requirements for tasks I'm receiving tons of errors. I've tried to select specific member from a team and check his programming language and receiving null. However, after debugging I saw that information comes,but when i try to reach exactly that language appears null.
Here's my code how looks my programmer class:
package com.wep;
public class Programuotojas extends Darbuotojas {
protected String programavimoKalba;
#Override
public String toString() {
return "Programuotojas: " + vardas + ",pavarde " + pavarde + ",amzius " + amzius + ",programavimo kalba " + programavimoKalba;
}
public Programuotojas(String vardas, String pavarde, int amzius, String programavimoKalba) {
super(vardas, pavarde, amzius);
this.programavimoKalba = programavimoKalba;
}
Programuotojas(){}
public String getProgramavimoKalba() {
return programavimoKalba;
}
public void setProgramavimoKalba(String programavimoKalba) {
this.programavimoKalba = programavimoKalba;
}
}
And here's my try to check his language:
KomanduValdymas.getInstance().komanduArray.get(0).getPirmasDarbuotojas(programuotojas.getProgramavimoKalba());
KomanduValdymas is a class where I create new teams. If u need more code from there let me know. Thanks, hope you guys got my problem
private void pridetiDarbuotoja() {
System.out.println("[1] Pridėti programuotoją");
System.out.println("[2] Pridėti testuotoją");
Scanner SI = new Scanner(System.in);
int userSelects = Integer.parseInt(SI.nextLine());
if (userSelects == 1) {
System.out.println("Iveskite:");
System.out.println("Varda, pavarde, amziu, darbine programavimo kalba");
String enters[] = SI.nextLine().split(" ");
darbuotojuArray.add(new Programuotojas(enters[0], enters[1], Integer.parseInt(enters[2]), enters[3]));
System.out.println("Darbuotojas itrauktas i sarasa");
} else {
System.out.println("Iveskite:");
System.out.println("Varda, pavarde, amziu, isdirbtas testavimo valandas");
String enters[] = SI.nextLine().split(" ");
darbuotojuArray.add(new Testuotojas(enters[0], enters[1], Integer.parseInt(enters[2]), Integer.parseInt(enters[3])));
}
darbuotojuValdiklis();
}
You appear to be under the impression that creating a new Programuotojas will update the value of your variable programuotojas automatically. That is not the case.
You need a statement that starts with programuotojas = in order to affect such a change.

Syntax error in calling a method java (newbie) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The 2 answers posted both fixed it. thank you very much and i am embarrassed by how simple it was.
sorry for posting such a basic question and thank you for your time.
From the menu method at the top i wish to call 2 different methods to complete an action based on the input. i cannot find anywhere how to call a void method.
I don't know why the second one wont work as i used a similar thing earlier on.
public void CheckOutMenu(ArrayList basket )
{
choice = 0;
while ( choice !=4 ) {
Scanner in = new Scanner ( System.in);
{
switch(in.nextInt()){
//print the number of items in the basket
case 1:
//working
break;
case 2:
//dont know how to call on option 2 the listBasket method
break;
case 3:
//to call the method
//error and wont compile
double totalCost = CalcTotalCost(totalCost = 0);
//printing what the method returns
System.out.print("The total price of your basket is £" );
break;
case 4:
choice = 4;
break;
default:
System.out.println("please enter a whole number that represents you're choice");
}
}
}
}
protected void listBasket(ArrayList basket )
{
//code inside works fine
}
public double CalcTotalCost(double total, ArrayList basket)
{
//code inside works fine
return total;
}
you can call a void method like any other method, except that you don't have to do anything with the return value because there isn't one.
case 2:
listBasket(basket);
break;
for your third case, you have to pass in both a double and an ArrayList if you want to pass 0 as your double, than you can just post a double literal.
case 3:
/* if you don't want totalCost to go out of scope right away,
* declare it above the switch statement */
double totalCost = CalcTotalCost(0.0, basket);
...
break;
Your error is here, as I'm sure you know:
double totalCost = CalcTotalCost(totalCost = 0);
However, your CalcTotalCost method is defined thus:
public double CalcTotalCost(double total, ArrayList basket)
You've sent it the total, but you haven't sent it a basket.

Categories

Resources