Fixing java.lang.nullpointException [closed] - java

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
Hi there I am trying to create an array of records in java in which you have to enter 3 details, the name of a town, the population and the county in which is resides. Before then outputting all the data on a county which you have asked for. I was wondering if anyone could show me why a null.point.exception occurs if I enter the population of a town when does not occur when i enter another one.
import java.util.*;
public class CathedralTowns
{
public static String name;
String population;
String county;
public static int count = 0;
public static int continuation = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int loop1 = 0;
while (loop1 <= 0) {
System.out.println("Please enter the name of the town. ('no' to end)");
String nameEntered = input.nextLine();
System.out.println("Please enter the county in which the town resides. ('no' to end)");
String countyEntered = input.nextLine();
System.out.println("Please enter the population of the town. ('no' to end)");
String populationEntered = input.nextLine();
if (nameEntered.equals("no") || populationEntered.equals("no") || countyEntered.equals("no") ) {
loop1 = 5;
System.out.println("Thank you for entering your county.");
continuation = 1;
}
WorkingDemCathedrals(nameEntered, populationEntered, countyEntered);
}
}
public static void WorkingDemCathedrals(String nameEntered, String populationEntered, String countyEntered) {
Scanner input = new Scanner(System.in);
CathedralTowns[] allTowns = new CathedralTowns[50];
allTowns[count] = new CathedralTowns();
int loop2 = 0;
int loop3 = 0;
while (loop2 == 0){
allTowns[count].name = nameEntered;
allTowns[count].population = populationEntered; //the error relates back to here according to bluej
allTowns[count].county = countyEntered;
if (continuation == 1) {
loop2 = 1;
System.out.println("please enter the name of a county for which you wish to know the details.");
String countyOfChoice = input.nextLine();
while (loop3 > 0){
if ((allTowns[loop3].county).equals(countyOfChoice)){
System.out.println(allTowns[loop3].name);
System.out.println(allTowns[loop3].population);
loop3 = -2;
}
loop3 = loop3 +1;
}
}
count = count + 1;
}
}
}

Elements in an Object array are null by default. Initialialise the elements prior to attempting to access them
for (int i=0; i < allTowns.length; i++) {
allTowns[i] = new CathedralTowns();
}

This lines is very suspicious
allTowns[count] = new CathedralTowns();
You allocate only one object in the array while you have a line before allocated an array of the length 50.
CathedralTowns[] allTowns = new CathedralTowns[50];
Not to mention that it is prone to ArrayIndexOutOfBoundsException if count is equal or more that 50
Then you start to loop and increment count and that's where it happens!
your should loop over the entire array and allocate an object in each slot.

The NullPointerException occurs at "population" and not at "name" is because the "name" field is static, whereas the "population" is non-static.
Also the allocation of the array of CathedralTowns has to be done as per the first answer.
The while (loop2 == 0) could end up in a infinite loop. There is no end condition for this while loop, if the user wants to enter details of more than one county.

Related

How do i reference something in an array that the user has created

At the start of the code the user determines a number of keywords and the keyword strings themselves, they place this into an array. Lets say the user says 3 keywords and they are "music", "sports" and "memes". After all this, say the user inputs in the program "I like sports". I simply want the program to respond with "Let's talk about sports" after recognising that the user said sports which is in the array that the user has essentially created.
I want to reference a string the user has predetermined then print it along with a message
I can see the potential of this working using for loops and going through every article until you find a match, I haven't done much work with booleans yet so I just need some assistance punching out the code then learning from it
this all has to happen inside a while loop so when that's done they can use a different keyword and get the same boring response
thanks
note: I don't actually have any of this code I want in my program yet, this code is just to show you kind of how it fits into the greater scheme of things.
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
String kwArray[];
String UserMessage;
String Target = "";
int numKw = 0;
Scanner input = new Scanner(System.in);
System.out.println("How many keywords do you want?");
numKw = input.nextInt();
kwArray = new String[numKw];
System.out.print(System.lineSeparator());
input.nextLine();
for (int i = 0; i < numKw; i++) {
System.out.println("Enter keyword " + (i + 1) + ": ");
kwArray[i] = input.nextLine();// Read another string
}
for (int i = 0; i < numKw; i++) {
kwArray[i] = kwArray[i].toLowerCase();
}
int x = 0;
while (x == 0) {
System.out.println("Hey I'm a chatbot! Why don't you say something to me!");
System.out.println("These are the keywords you gave me");
for (String i : kwArray) {
System.out.print(i);
System.out.print(", ");
}
System.out.print(System.lineSeparator());
System.out.println("Or you can terminate the program by typing goodbye");
UserMessage = input.nextLine();
// Gives the user opportunity to type in their desired message
UserMessage = UserMessage.toLowerCase();
if (UserMessage.contains("?")) {
System.out.println("I will be asking the questions!");
}
if (UserMessage.contains("goodbye")) {
x = 1;
}
}
input.close();
}
}
If I am getting the question right, you want to check whether an element exists in the submitted keywords and want to reference it back if you further processing.
For this, instead of an array you could use a HashSet which can check the existence any element in O(1).
Updated the code, but I still feel your query is the same what I understood, putting the exact example of your use case below:
Scanner input = new Scanner(System.in);
Set<String> set = new HashSet<String>();
int keywords = input.nextInt();
for (int i=0; i<keywords; i++) {
//add to set set like:
set.add(input.readLine());
}
String userComment = input.readLine();
String[] userCommentWords = userComment.split(" ");
//you can iterate over the words in comment and check it in the set
for (int i=0; i<userCommentWords.length; i++) {
String word = userCommentWords[i];
if (set.contains(word)) {
System.out.println("Let's talk about "+word);
}
}

Why is my substring causing an error in my program? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
When I run this program, an error comes up, saying that it is due to "String.substring(int, int)line: not available. However, it outputs the correct answer (with a number of 123 and a target of 2, the final should be 35). Any help would be great, thanks!
import java.util.Scanner;
public class Math{
public static void main(String[] args) {
for (int i=1; i<=5; i++) {
System.out.println("Please enter your number:");
Scanner input = new Scanner(System.in);
String number= input.nextLine();
System.out.println("Please enter your target:");
int target= input.nextInt();
// input.close();
String outcome= "0";
long final = Long.parseLong(outcome);
for (int h=0; h<=((number.length())-target+1); h++) {
String result = number.substring(h, (target+h));
long output = Long.valueOf(result);
final = final + result;
System.out.println(final);
}
}
}
}
You have several problems here:
final is a reserved keyword, and cannot be a variable name. You must rename it
You are trying to add a String to a long in the line:
final = final + result;
You have a index out of bounds error when you call substring. You are looping one more time then necessary. Change <= to <:
Code:
String outcome= "0";
long finalVar = Long.parseLong(outcome);
for (int h=0; h<((number.length())-target+1); h++) {
String result = number.substring(h, (target+h));
long output = Long.valueOf(result);
finalVar = finalVar + output;
}
System.out.println(finalVar);
Input/Output:
Please enter your number:
123
Please enter your target:
2
35

Java not continuing a loop [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 am making a simple for loop to go through an ArrayList and add objects to them but when I enter my first object nothing happens. It looks like the program isn't continuing the loop. Here is what I have:
for (int i = 0; i < (numPlayers.nextInt()-1); i++){
System.out.println("what is player " + (i + 1) + " name?");
Scanner namePlayer = new Scanner(System.in);
String playerName = namePlayer.nextLine();
playerList.add(new Player(playerName));
}
The player object constructor is very simple as well
public Player(String name) {
this.name = name
}
public static void main(String[] args)
{
Scanner numPlayers = new Scanner(System.in);
ArrayList<Player> playerList = new ArrayList<>();
int input = numPlayers.nextInt();
for (int i = 0; i < input; i++){
System.out.println("what is player " + (i + 1) + " name?");
String playerName = numPlayers.next();
playerList.add(new Player(playerName));
}
}
You should have declared scanner object outside the for the loop. The problem with your code was each time after taking a string input your code was needed to provide an integer for (int i = 0; i < (numPlayers.nextInt()-1); i++) and that's why if you provide anything but an integer it gives InputMismatchException. So you have to initialize the input constant outside the for loop otherwise execution will vary dynamically.
You need to define the limits of your loop only once, if possible:
int numberOfPlayers = numPlayers.nextInt()-1;
for (int i = 0; i < numberOfPlayers; i++){
System.out.println("what is player " + (i + 1) + " name?");
Scanner namePlayer = new Scanner(System.in);
String playerName = namePlayer.nextLine();
playerList.add(new Player(playerName));
}
You will need to make sure that you are iterating the loop as many times as you want.

I can't print my array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I tried to print my array using to Arrays.toString(array)); but still it gave me errors... And also ELEMENT IS FOUND is false statement but it mixes with the true statement when i tried to search an element in my array,
for example.....
I searched 4 in my array: 4 , 2, 3 ,5
but ELEMENT IS FOUND is still showing.
import java.util.Scanner;
public class linee {
public static void main(String[] args) {
int String;
int value;
Scanner in = new Scanner(System.in);
System.out.print("Input the Number of Element: ");
String n = in.nextLine();
int num = Integer.parseInt(n);
String array[] = new String[num];
for (int i = 0; i < array.length; i++) {
System.out.print("Input the Number at array index " + i + ": ");
array[i] = in.nextLine();
}
Linear(array);
System.out.print("\nDo you want to continue? YES = 1, NO = 2: ");
value = in.nextInt();
if (value == 1) {
main(args);
} else if (value == 2) {
System.out.println("\nThank you for using the program.");
}
}
public static void Linear(String[] array) {
boolean flag = false;
String key = "";
int index = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number that you want to search: ");
key = in.nextLine();
for (int i = 0; i < array.length; i++) {
if (array[i].equals(key)) {
flag = true;
index = i;
}
}
if (flag == true) {
System.out.println("Elements: " + Arrays.toString(array));
System.out.println("ELEMENT IS FOUND AT INDEX " + index);
} else {
System.out.println("ELEMENT IS NOT FOUND");
}
}
}
From the Object.toString(Object[] a) spec:
Returns a string representation of the contents of the specified
array. If the array contains other arrays as elements, they are
converted to strings by the Object.toString() method inherited from
Object, which describes their identities rather than their contents.
That is, you may want to print your elements in another way. An option is:
System.out.println("Elements: ");
for(String str: array) {
System.out.println(str);
}

Using while loops to print out vaules [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 8 years ago.
Improve this question
I'm currently doing a college lab on while loops and I'm stuck and would appreciate any help available. I have to write a program as follows
Write a program MaxNum that reads in a sequence of 10 positive integers, and
outputs the maximum of the sequence
Now I could just make 10 ints and make the user input a value but I'm not sure how to do that with a while loop?
Here is the code I have at the moment :
import java.util.Scanner;
public class SumTenNumbers{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int Num1= 0;
System.out.println("Please enter 10 integers");
do
{
for(Num1 = 0; Num1 < 10; Num1++);
{
Num1 = in.nextInt();
}
}
while(Num1 > 0);
}
}
Since you can't use array, you just use a max to check if the number entered is bigger than the previous number entered. You don't need a while loop, at least your do-while is not really needed in this case.
Edit: don't modify num1, you will be messing around with your for-loop
import java.util.Scanner;
public class SumTenNumbers{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int Num1= 0;
int max = 0;
int userInput = 0;
System.out.println("Please enter 10 integers");
for(Num1 = 0; Num1 < 10; Num1++);
{
userInput = in.nextInt();
if(num1 == 0){//you set your first number as the maximum
max = userInput;
}else if(max < userInput){
max = userInput;//here you set the number to max
}
}
}
}
Here is something you could do since you explicitly saying you are learning the while loop. You can keep getting user's input until you have enough number of Integers entered, since you mentioned you only want Integer. And you can use Collections.max at the end.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
while (list.size() < 10 && scanner.hasNext()) {
if (scanner.hasNextInt()) {
list.add(scanner.nextInt());
} else {
scanner.next();
}
}
Integer max = Collections.max(list);
System.out.println(max);
}

Categories

Resources