This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 7 years ago.
Currently I am working on an assignment within BlueJ.
The question I have is simple (I hope). The method I wish to use within the while loop is "getRearWheelDrive()" which checks how many Lamborghinis within the ArrayList< Lamborghini > inventory have rear wheel drive. rearWheelDrive is a boolean variable.
Also I can not use a for-loop for this question, otherwise I would as it would be much easier. I am limited to the while loop.
The error message I receive is: "non-static method getIsRearWheelDrive() cannot be referenced from a static context" -I tried to create a static method but it didn't work either.
//
How do I check all the Lamborghini objects within the ArrayList library and then return an int value of how many total have rearWheelDrive? Also with the current code I have, would it cause the loop to finish once it got to the end of the index, or would it infinitely loop?
public int howManyAreRearWheelDrive()
{
int indexPlace = 0;
int number = 0;
int i = 0;
while(indexPlace <= inventory.size())
{
indexPlace++;
inventory.get(i);
i++;
if(Lamborghini.getIsRearWheelDrive() == true) {
number++;
}
}
return number;
}
Without seeing the rest of the relevant classes in play here:
while(indexPlace < inventory.size())
{
if(inventory.get(indexPlace++).getIsRearWheelDrive() == true) {
number++;
}
}
You need to call getIsRearWheelDrive from an instance of the Lambroghini class not from the class itself. Only static variables can be called using the class name which is not the case here.
In this example it would be
inventory.get(i).getIsRearWheelDrive();
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I'm writing a program which utilizes OOP. The program I am creating is supposed to recruit applicants to a team. In my Team.java, I created a method which is supposed to accept members and add it to the team. This is a snippet of my code:
public int maxMembers;
public Member members[] = new Member[maxMembers];
public int memberCount = 0;
public void addMember(Member newMember) {
members[maxMembers] = newMember;
memberCount++;
}
I have tried this code but the line,
members[maxMembers] = newMember;
keeps throwing an error java.lang.ArrayOutOfBoundsException: 2
I have tried using a for loop in adding a new member but it does not do what I expected. Can anyone assist me in finding a solution?
You have to assign maxMembers a value in the first line, otherwise your array will have 0 elements.
public int maxMembers = 10;
Firstly, you did not initialize the variable maxMembers.Also, in the code, the line members[maxMembers] = newMember; would always put your entry in the end of the array, I think thats not the intended use of your method, public void addMember(Member newMember)
Rewriting your method would look like,
public int maxMembers=somePositiveInteger;
public Member members[] = new Member[maxMembers];
public int memberCount = 0;
public void addMember(Member newMember) {
members[memberCount] = newMember;//here
memberCount++;
}
Initialize the array with a value so that number of elements in array can be decided.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm trying to make a for loop that loops through an array, comparing the user input to each object using a method called getID() that returns the stored user IDs for various employees. The data is not saved between runs, so on the first loop, all objects (I believe) should be null. With that being said, I get a nullPointerException on the line that's supposed to compare the strings retrieved by getID() and the userInput string. The array is initialized as follows:
Salesperson[] staffList;
staffList = new Salesperson[20];
Here is the loop in question, the if statement is the line that throws the NPE:
for(i = 0; i < staffList.length; i++)
{
if(staffList[i].getID().equals(idNum))
{
duplicateID = true;
}
}
Here is the class for the Salesperson array:
public class Salesperson
{
private String name;
private String idNum;
private double annSales;
//Various getter and setter methods here
}
If I missed anything please let me know. I've used Stack Overflow in the past but have never asked a question myself. I've tried searching around here but have yet to find anything that helped me. Thanks in advance!
You can update your code something like below to avoid NPE.
Salesperson[] staffList;
staffList = new Salesperson[20];
for(int i = 0; i < staffList.length; i++)
{
Salesperson salesPerson = staffList[i]; // staffList[i] i.e salesPerson = null.... null.getId throws NPE.
System.out.println("sales =" + sales); // sales = null
if(sales != null) {
if (sales.getId().equals(idNum)) {
//Do something..
}
}
}
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 6 years ago.
I am trying to write a program, but my client might not type in the information in the correct format. How do I tell if a String is an int in Java (so I can throw an error message that I write and allows them to retry)? I.e., is there a method in java that will allow me to check if String str is of type int?
String input=kb.nextLine();
if(input.(isInteger method)&&(int)input==otherint)
do stuff inside here;
else
do different stuff;
An answer should include the imports needed (if any) and basic method. Also, as simple as possible would be very good. If this is actually a copy of a question, post the link (I looked for a while but couldn't find anything on google or here that seemed like it would solve my problem).
Create a methode in a class say IntegerCheck.java:
public Boolean isInteger (String s)
{
try
{
Integer.parseInt(s);
return true;
} catch (Exception e)
{
return false;
}
}
Then use it in your program:
First import the class:
import <package name>.IntegerCheck;
Inside the required function:
IntegerCheck obj=new IntegerCheck();
String input=kb.nextLine(); //Get user input using Scanner or any other method, make sure the return type is string.
if(obj.isInteger(input))
{
//Success.
}
else
{
//throw an error message that I write and allows them to retry
}
package main.java;
public class Test {
public static boolean isNumeric(String s){
// 11 Because might be negative, but 32bit integer overflow is
// 10 characters long.
if (s.length() > 11) return false;
int i = 0;
if (s.startsWith("-")) i++;
for(; i < s.length(); i++){
if (!Character.isDigit(s.charAt(i))) return false;
}
return true;
}
public static void main(String[] args){
System.out.println(Test.isNumeric("100"));
System.out.println(Test.isNumeric("aa"));
System.out.println(Test.isNumeric("12a"));
System.out.println(Test.isNumeric("1002"));
System.out.println(Test.isNumeric("-11232"));
System.out.println(Test.isNumeric("999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999"));
System.out.println(Test.isNumeric("4294967294"));
}
}
Edit I forgot to include negative numbers.
Edit Rough way to handle integer overflow.
Mind you this will only work with integers. Regular expressions seem a bit overkill for this, but aren't a bad solution. You should not use exceptions to control program flow as per this question: Why not use exceptions as regular flow of control?
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm new in Java and I find it very complicated because of the errors that I come across with. So I have a problem with this piece of code:
Main Class:
public class Main {
public static void main(String[] args){
Answer a = new Answer();
String ans = null;
while(ans != "A"){
ans = a.create();
System.out.print(ans + "\n");
}
}
}
Answer class:
import java.util.Scanner;
public class Answer {
public String create(){
Scanner s = new Scanner(System.in);
return s.next();
}
}
I want the program to allow me to write something. Then, if what I've written hasn't been the letter A, the program must allow me to write something else, otherwise has to stop. But, even though I write "A", the program is still keeping on, allowing me to write something else. What's wrong with the code?
String can't be compared properly using the != operator. Instead you should use while(!ans.equals("A")). Secondly, try not to recreate the Scanner object in the create method. This is a resource waste.
This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 9 years ago.
When i try to use the move i.e. Slide.move(1,0) i get the error: non-static method move(int,int) cannot be referenced from a static context
This is my code at the moment, which i have no idea whats wrong.
public void move(int row, int col) {
char [][] temp= new char [cells.length][];
for (int i= 0; i< cells.length; i++) {
int destRow = (i+row)%cells.length;
temp[destRow] = new char [cells[i].length];
for (int j= 0; j < cells[i].length; j++)
temp[destRow][(j+col)%cells[i].length] = cells[i][j];
}
cells= temp;
}
}
The error means exactly what it says.
Your move method is not static. It requires an instance of an object to be called, e.g.:
Slide s = new Slide();
s.move(...);
You are calling it, as it says, from a static context, i.e. a place with no this, perhaps another static method or directly via Slide.move(...). You will need to not do that.
These fail:
Slide.move(...); // error: move requires an instance
// and
class Slide {
void move (...) {
...
}
static void method () {
move(...); // error: method is static, there is no instance
}
}
These do not fail:
Slide s = new Slide();
s.move(...);
// or
class Slide {
void move (...) {
...
}
void method () {
move(...);
}
}
// or
class Slide {
static void move (...) {
...
}
static void method () {
move(...);
}
}
So either call it from a non-static context, or make it a static method.
As for recommending somewhere to read more about these things (which you asked in a comment), try the official Java tutorial at http://docs.oracle.com/javase/tutorial/ (take a look at the "Learning the Java Language" trail (in particular: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html).
As for your output problems, since that's a separate question, you'd want to post a separate question for it.
Well that is because you defined the move method as a non-static method by saying public void to make it static you need to write public static void instead.
Also be aware that variable names are case sensitive, if you write Slide.move() you clearly call upon your Slide class because your variable was named slide.