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 2 years ago.
This is the 'Lead' class, when I try to call Leads.primeLead() , I get a
"Non-static method cannot be referenced from a static context" error.
I do understand the error, but I do not understand why when I defined a constructor and initilized an object, I cannot apply the method primeLead() on object lead1 .
How do I solve this?
import java.util.ArrayList;
import java.util.Scanner;
public class Lead extends Main{
String nameLead;
int ageLead;
int phoneLead;
String cityLead;
String email;
String otherNotes;
int indexOfLead = 0;
int i = indexOfLead;
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> ages = new ArrayList<Integer>();
ArrayList<Integer> phones = new ArrayList<Integer>();
ArrayList<String> cities = new ArrayList<String>();
ArrayList<String> emails = new ArrayList<String>();
ArrayList<String> notes = new ArrayList<String>();
Scanner leads = new Scanner(System.in);
Lead(){
i = 0;
// Need to create an ArrayList that has all the Arraylists above.
}
Lead lead1 = new Lead();
/* public mainMenuLead(){
System.out.println("Please choose one of the following options");
} */
public static void primeLead(){
i = 0;
System.out.println("============================================");
System.out.println(" Please enter by the following order : ");
System.out.println(" Name, age, phone , city, mail ");
System.out.println("============================================");
System.out.println("Please enter the name of the Lead : ");
names.add(leads.nextLine());
System.out.println("Age? : ");
ages.add(Integer.parseInt(leads.nextLine()));
System.out.println("Phone number? ");
phones.add(Integer.parseInt(leads.nextLine()));
System.out.println("Would you like to add ... ");
System.out.println("1) City? ");
System.out.println("2) Email? ");
System.out.println("3) Notes? ");
if(leads.nextLine().equals("1")){
System.out.println("Please add City: ");
cities.add(leads.nextLine());
} else if (leads.nextLine().equals("2")){
System.out.println("Please add email : ");
emails.add(leads.nextLine());
} else if(leads.nextLine().equals("3")){
System.out.println("Please add any other notes you may have: ");
notes.add(leads.nextLine());
}
}
}
public void primeLead(){
i = 0;
System.out.println("============================================");
System.out.println(" Please enter by the following order : ");
System.out.println(" Name, age, phone , city, mail ");
System.out.println("============================================");
System.out.println("Please enter the name of the Lead : ");
names.add(leads.nextLine());
System.out.println("Age? : ");
ages.add(Integer.parseInt(leads.nextLine()));
System.out.println("Phone number? ");
phones.add(Integer.parseInt(leads.nextLine()));
System.out.println("Would you like to add ... ");
System.out.println("1) City? ");
System.out.println("2) Email? ");
System.out.println("3) Notes? ");
if(leads.nextLine().equals("1")){
System.out.println("Please add City: ");
cities.add(leads.nextLine());
} else if (leads.nextLine().equals("2")){
System.out.println("Please add email : ");
emails.add(leads.nextLine());
} else if(leads.nextLine().equals("3")){
System.out.println("Please add any other notes you may have: ");
notes.add(leads.nextLine());
}
}
}
second file(Where Lead.primeLead() is called:
import java.util.Scanner;
public class Main {
boolean exit = false;
public void runMenu(){
printHeader();
while(!exit){
mainMenu();
int choice = getInput();
performAction(choice);
}
}
private void performAction(int choice){
switch(choice){
case 1:
new Lead();
Lead.primeLead();
case 2:
case 3:
case 4:
case 5:
exit = true;
System.out.println("Bye!");
break;
}
}
public void printHeader(){
System.out.println("===========================================");
System.out.println(" Hello user! ");
System.out.println(" Welcome to our lead ");
System.out.println(" Management tool ");
System.out.println("===========================================");
}
public void mainMenu(){
System.out.println("\nPlease select one of the following options: ");
System.out.println("1) Create a new lead");
System.out.println("2) View all the leads");
System.out.println("3) Connect ");
System.out.println("4) View statistics");
System.out.println("5) Exit ");
}
private int getInput(){ // Scanner takes input from user, returns his choice.
Scanner kb = new Scanner(System.in);
int choice = -1;
while(choice < 0 || choice > 5){
try{
System.out.print("\nEnter your choice: ");
choice = Integer.parseInt(kb.nextLine()); // What is Integer.parseInt ? what is . next line ?
}
catch(NumberFormatException e){
System.out.println("Invalid selection, please try again.");
}
}
return choice;
}
public static void main(String[] args){
Main menu = new Main();
menu.runMenu();
}
}
You create a Lead object and do not use it:
new Lead();
Lead.primeLead();
Instead, you should use the lead object you created:
Lead lead=new Lead();
lead.primeLead();
If you call <ClassName>.<methodName>(<parameters>);, you call a static method that has nothing to do eith the object.
If you call <objectOfTheClass>.<methodName>(<parameters>);, you call a non-static method that is part of the object.
And, as #Andreas points out in the comments, every open curly brace needs to have a closing curley brace at the appropriate position any the other way round.
Related
I am trying to create a pet app that allows user input to enter a pet name, update the pet name and delete the pet name. Here is what I have so far. I have made an array for the create method but I can't figure out how to use it in the update or delete methods.
import java.util.Scanner;
import java.io.*;
public class Menu2 {
static Scanner scan = new Scanner(System.in);
public static void main(final String[] args) {
showMainMenu();
}
public static void showMainMenu(){
System.out.println("--- MAIN MENU ---");
System.out.println("1. Create Pet");
System.out.println("2. Update Pet");
System.out.println("3. Delete Pet");
System.out.println("4. Exit");
System.out.print("Enter your Choice : ");
int option = scan.nextInt();
switch(option){
case 1:
createPet();
break;
case 2:
updatePet();
break;
case 3:
deletePet();
break;
case 4:
System.exit(0);
break;
default:
System.out.println("Invalid option!");
showMainMenu();
}
}
public static void createPet(){
Scanner myObj = new Scanner(System.in);
//String newPet = myObj.nextLine();
System.out.print("Enter Pet Name: ");
String newPet = myObj.nextLine();
String newPetArray[] = newPet.split(" ");
// newPet = scan.nextLine();
System.out.println("Pet Name is " + newPet);
// use for READ
for (int i = 0; i < newPetArray.length; i++){
System.out.println(newPetArray[i]);
}
showMainMenu();
}
public static void updatePet() {
}
public static void deletePet() {
}
}
If your goal is to store the pets in an array, for updating you would loop through the array (such as with a "for" or "while" loop), identify the index of the entry to be updated and update it. This could also be done with filters, but that would be a more advanced approach.
In order to delete the pet, you would need to find the pet (like you would in the update portion) and then shift all the remaining pets forward, so newPetArray[x] gets the value of newPetArray[x+1] and the last pet gets removed.
This task is easier with other datastructures, like ArrayList's, that support removing and inserting items directly.
As you haven't mentioned the details about the update function, I am assuming it is going to update the name of the pet present in the list. As ArrayList is more flexible when it comes to array in terms of addition of deletion and since you havent specified that you need to use array in particular, I'm providing the solution with ArrayList.
Logic for Updation
You iterate through the list and when the element matches, you simply update the name
Logic for Deletion
You iterate through the list and when the element matches, you simply remove the element present at that index.
import java.util.ArrayList;
import java.util.Scanner;
public class Menu2 {
static Scanner scan = new Scanner(System.in);
static ArrayList<String> petList;
public static void main(final String[] args) {
showMainMenu();
scan.close();
}
public static void showMainMenu() {
System.out.println("--- MAIN MENU ---");
System.out.println("1. Create Pet");
System.out.println("2. Update Pet");
System.out.println("3. Delete Pet");
System.out.println("4. Exit");
System.out.print("Enter your Choice : ");
int option = scan.nextInt();
switch (option) {
case 1:
createPet();
break;
case 2:
updatePet();
break;
case 3:
deletePet();
break;
case 4:
System.exit(0);
break;
default:
System.out.println("Invalid option!");
showMainMenu();
}
}
public static void createPet() {
Scanner myObj = new Scanner(System.in);
System.out.print("Enter Pet Name: ");
String newPet = myObj.nextLine();
String newPetArray[] = newPet.split(" ");
petList = new ArrayList<>();
// use for READ
for (int i = 0; i < newPetArray.length; i++) {
petList.add(newPetArray[i]);
}
System.out.println("pets in list are " + petList);
showMainMenu();
}
public static void updatePet() {
System.out.println("Enter the name of the pet to be updated");
String name = scan.next();
System.out.println("Enter the updated name");
String newName = scan.next();
for (int i = 0; i < petList.size(); i++) {
if (petList.get(i).equals(name)) {
petList.set(i, newName);
break;
}
}
System.out.println("pets in list after updating the pet " + petList);
showMainMenu();
}
public static void deletePet() {
System.out.println("Enter the name of the pet to be deleted");
String name = scan.next();
for (int i = 0; i < petList.size(); i++) {
if (petList.get(i).equals(name)) {
petList.remove(i);
break;
}
}
System.out.println("pets in list after deleting the specific pet " + petList);
showMainMenu();
}
}
and the output is as follows:
--- MAIN MENU ---
1. Create Pet
2. Update Pet
3. Delete Pet
4. Exit
Enter your Choice : 1
Enter Pet Name: buddy max mac
pets in list are [buddy, max, mac]
--- MAIN MENU ---
1. Create Pet
2. Update Pet
3. Delete Pet
4. Exit
Enter your Choice : 2
Enter the name of the pet to be updated
mac
Enter the updated name
macKing
pets in list after updating the pet [buddy, max, macKing]
--- MAIN MENU ---
1. Create Pet
2. Update Pet
3. Delete Pet
4. Exit
Enter your Choice : 3
Enter the name of the pet to be deleted
max
pets in list after deleting the specific pet [buddy, macKing]
--- MAIN MENU ---
1. Create Pet
2. Update Pet
3. Delete Pet
4. Exit
Enter your Choice : 4
Im still learning java and i want to understand more about array. Im still in school and we were asked to create an asean phonebook which can store, edit, delete, and view/search the information that are inputted. Im still doing the storing of information block of code and im struggling how to save multiple input in an array that is limited only to 100 contacts and can be searched later in the code. Can someone help me with my task and make me understand??
import java.util.Scanner;
public class Phonebook
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
int i = 0;
String studentNumber, surName, firstName, occuPation, countryCode, areaCode, numBer;
char genDer;
do
{
Menu();
System.out.println(" ");
System.out.print("Go to: ");
String choice = input.next();
if (choice.equals("1") || choice.equals("2") || choice.equals("3") || choice.equals("4") || choice.equals("5"))
{
i++;
switch(choice)
{
case "1":System.out.println("Enter student number: ");
studentNumber = input.next();
System.out.println("Enter surname: ");
surName = input.next();
System.out.println("Enter first name: ");
firstName = input.next();
System.out.println("Enter occupation: ");
occuPation = input.next();
System.out.println("Enter gender (M for male, F for female): ");
genDer = input.next();
System.out.println("Enter counter code: ");
countryCode = input.next();
System.out.println("Enter area code: ");
areaCode = input.next();
System.out.println("Enter number: ");
numBer = input.next();
break;
case "2":System.out.println("2");break;
case "3":System.out.println("3");break;
case "4":System.out.println("4");break;
case "5":System.out.println("5");break;
}
}
else
{
System.out.println("Invalid keyword, Please try again");
}
}
while (i < 1);
}
static void Menu()
{
System.out.println("[1] Store to ASEAN phonebook");
System.out.println("[2] Edit entry in ASEAN phonebook");
System.out.println("[3] Delete entry from ASEAN phonebook");
System.out.println("[4] View\\search ASEAN phonebook");
System.out.println("[5] Exit");
}
}
I'm creating a simple program that gets name, age and favorite number/s. The problem is that this exception appears when user chooses to input more than 1 favorite number.
Please help me to solve this problem that still uses ellipse in testing class --> favnum2 method.*
testing class
import java.util.Scanner;
public class testing{
public static Scanner input;
public static void main(String[] args){
boolean choicerepeat=true;
int favnumoftimes;
while(choicerepeat==true){
input = new Scanner(System.in);
testing2 obj1 = new testing2();
String name="";
int age=0;
favnumoftimes=0;
double favnum=0, favnumarr[]=new double[999];
boolean choice1;
System.out.print("What is your name? ");
name = input.nextLine();
System.out.print("What is your age? ");
age = input.nextInt();
obj1.message1(name);
obj1.message2(age);
System.out.print(name+" do you only have one favorite number? (If yes type 'true' else 'false' - NOTE: lowercase only) ");
choice1 = input.nextBoolean();
if(choice1==true)
favnum1();
else{
System.out.println("How many favorite numbers do you have "+name+"? ");
favnumoftimes = input.nextInt();
for(int a=0;a<favnumoftimes;a++){
System.out.print("Enter favorite number "+ (a+1) +": ");
favnumarr[a]=input.nextDouble();
}
for(int a=0;a<favnumarr.length;a++){
favnum2(favnumoftimes, favnumarr[a]);
}
}
System.out.println();
System.out.println("Do you want to restart the program? (true(Yes) else false(No)) ");
choicerepeat = input.nextBoolean();
}
}
public static void favnum1(){
System.out.print("Enter favorite number: ");
double favnumholder1 = input.nextDouble();
System.out.println("Your favorite number is "+favnumholder1+" ." );
}
public static double favnum2(int favnumoftimesholder,double...favtemphold2){
System.out.print("Your favorite numbers are ");
for(int a=0;a<=favnumoftimesholder;a++){
System.out.print(favtemphold2[a]+", ");
}
return 0;
}
}
testing2 class
public class testing2{
public static String message1(String nameholder){
for(int a=0;a<nameholder.length();a++){
char strholder = nameholder.charAt(a);
if(Character.isDigit(a)){
System.out.println("Names don't have numbers... ");
break;
}
else continue;
}
System.out.println("\nHi "+nameholder+"! Welcome to my simple program. ");
return nameholder;
}
public static int message2(int ageholder){
System.out.println("Your age is "+ageholder+" years old? Oh my goodness. ");
System.out.println();
return ageholder;
}
}
The problem is that varargs create new arrays with a length equal to the number of parameters passed. Thus double...favtemphold2 will create a new array favtemphold2 and since you only pass 1 element (favnum2(favnumoftimes, favnumarr[a]);) that array will have length 1.
You might want to either pass more elements or the entire array, i.e. favnum2(favnumoftimes, favnumarr);. Since double... is basically syntactic sugar for double[] they are equal and passing a double array for a double vararg will work.
A warning for future use of varargs though: be carefull with Object... since arrays are objects as well.
import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> game = new ArrayList<String>();
ArrayList<Integer> score = new ArrayList<Integer>();
ArrayList<Integer> time = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
String answer = "yes";
{
do {
System.out.print("Please enter your username: ");
name.add(scanner.nextLine());
System.out.println("Please enter the game: ");
game.add(scanner.nextLine());
System.out.println("Please Enter Achievement Score: ");
score.add(scanner.nextInt());
System.out.println("Please Enter Playtime: ");
time.add(scanner.nextInt());
System.out.print("Any letter to continue alternatively type quit to Quit.");
answer = scanner.next();
} while (!answer.equals("quit"));
if (answer.equals("quit")); //want it to go back to start another direcotry here
else {
System.out.println("Thanks for adding to the database.");
for (int i = 0; i < name.size(); i++) {
System.out.print("Username:" +name.get(i)+"\n");
System.out.print("~~~~~~~~~~~~" +"\n");
System.out.print("Game:" +game.get(i)+"\t");
System.out.print("Score:" +score.get(i)+"\n");
System.out.print("Minutes played:"+time.get(i));
System.out.println("");
}
}
}
}
}
The problem with this is that the program is not quitting upon typing Quit but it is continuing and placing two questions on one line, shown below. how can I solve this problem?
Please enter your username: abc123
Please enter the game:
GTA V
Please Enter Achievement Score:
1200
Please Enter Playtime:
120
Any letter to continue alternatively type quit to Quit.Quit
Please enter your username: Please enter the game:
The issue is that you are comparing upper and lower case values of quit. You need to set them to the same case type for them to be equal and quit the program.
change your check to
while (!answer.toLowerCase().equals("quit"));
if (answer.toLowerCase().equals("quit"));
and that will change your input to lowercase which is what your are comparing it to.
I don't see any problem except that you have not closed the scanner. You can run this and you can see that the scanner is closed and go to normal execution after word quit.
import java.util.ArrayList;
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> game = new ArrayList<String>();
ArrayList<Integer> score = new ArrayList<Integer>();
ArrayList<Integer> time = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
String answer = "yes";
{
do {
System.out.print("Please enter your username: ");
name.add(scanner.nextLine());
System.out.println("Please enter the game: ");
game.add(scanner.nextLine());
System.out.println("Please Enter Achievement Score: ");
score.add(scanner.nextInt());
System.out.println("Please Enter Playtime: ");
time.add(scanner.nextInt());
System.out.print("Any letter to continue alternatively type quit to Quit.");
answer = scanner.next();
} while (!answer.equals("quit"));
if(answer.equals("quit")){
System.out.println("you have just quit");
scanner.close();
} //want it to go back to start another direcotry here
else {
System.out.println("Thanks for adding to the database.");
for (int i = 0; i < name.size(); i++) {
System.out.print("Username:" +name.get(i)+"\n");
System.out.print("~~~~~~~~~~~~" +"\n");
System.out.print("Game:" +game.get(i)+"\t");
System.out.print("Score:" +score.get(i)+"\n");
System.out.print("Minutes played:"+time.get(i));
System.out.println("");
}
}
System.out.print("You are done with scanner");
}
}
}
I just tried your program and it does quit if you type "quit" (all lowercase) like your command line instruction suggest:
System.out.print("Any letter to continue alternatively type quit to Quit.");
If you want your quit instruction to be case-insensitive you should replace this line:
} while (!answer.equals("quit"));
with this:
} while (!answer.equalsIgnoreCase("quit"));
I hope that helped!
Your quit information System.out.print("Any letter to continue alternatively type quit to Quit."); says that you need to put quit all lowercase word to end.
Also change answer = scanner.next(); to answer = scanner.nextLine();
EDIT:
As you don't have any error control you can consider this code:
do {
System.out.print("Please enter your username: ");
name.add(scanner.nextLine());
System.out.println("Please enter the game: ");
game.add(scanner.nextLine());
System.out.println("Please Enter Achievement Score: ");
score.add(Integer.valueOf(scanner.nextLine()));
System.out.println("Please Enter Playtime: ");
time.add(Integer.valueOf(scanner.nextLine()));
System.out.print("Any letter to continue alternatively type quit to Quit.");
answer = scanner.nextLine();
} while (!answer.equals("quit"));
I changed scanner.nextInt() to Integer.valueOf(scanner.nextLine()). Using nextLine() helps scanner to flush all data before your code goes to the next line.
Hi, I'm very new to java and I'm currently trying to create a student name and mark menu but I'm having trouble with my add method, I think it's something to do with my Arrays but I can't figure it out, any help would be appreciated.
Below is my unitResult method
public class UnitResults
{
private String unitTitle;
private String [] fName;
private String [] surname;
//private String [] UnitResults;
private int [] Marks;
private int Mark;
private int pointer ;
private static String course = "HND Computing";
public UnitResults(int Size,String title)
{
this.fName = new String [Size];
this.surname = new String [Size];
this.Marks = new int [Size];
pointer = 0;
fName[pointer] = "Daniel";
surname[pointer] = "Scullion";
Marks[pointer] = 60;
unitTitle = title;
pointer ++;
}
public Boolean add( String tempfName, String tempsName, int newGrade)
{
if (pointer == fName.length)
{
System.out.println("The Students Database is full");
return false;
}
else
{
fName [pointer] = tempfName;
surname [pointer] = tempsName;
Marks[pointer] = newGrade;
pointer ++;
return true;
}
}// end Add
but when I try to add this using a menu system below
int option = 0;
option = menuSystem();
while (option != 6)
{
System.out.println("");
switch(option)
{
case 1:
System.out.println(" Please Enter The Students First Name");
String tempfName = keyb.nextLine();
System.out.println("Please Enter The Students Last Name");
String tempsName = keyb.nextLine();
System.out.println(" Please Enter The Students Mark");
int newGrade = keyb.nextInt();
myUnit.add(tempfName, tempfName,newGrade);
break;
When I enter my option 1 the output that I get is :
Please Enter The Students First Name
Please Enter The Students Last Name
Any ideas what's wrong here been searching for a long time, probably something simple but I've no idea :/
Edit: below is my menu class
import java.util.Scanner;
public class MenuResults {
static Scanner keyb = new Scanner(System.in);
public static int menuSystem()
{
System.out.println("*********************************");
System.out.println(" ");
System.out.println("1.Add New Student");
System.out.println("2.Display Students Details");
System.out.println("3.Delete a Students");
System.out.println("4.Update Student Details");
System.out.println("5.Sort Students By Mark");
System.out.println("6.Sort Students By Surname");
System.out.println("7.Search For A Student");
System.out.println(" ");
System.out.println("**********************************");
System.out.print("\n Enter choice:");
int option = keyb.nextInt();
return option;
}
public static void main(String[] args) {
UnitResults myUnit = new UnitResults(3, "Java");
int option = 0;
option = menuSystem();
while (option != 6)
{
System.out.println("");
switch(option)
{
case 1:
System.out.println(" Please Enter The Students First Name");
String tempfName = keyb.nextLine();
System.out.println("Please Enter The Students Last Name");
String tempsName = keyb.nextLine();
System.out.println(" Please Enter The Students Mark");
int newGrade = keyb.nextInt();
myUnit.add(tempfName, tempsName,newGrade);
break;
case 2:
myUnit.display();
break;
case 3:
break;
case 4:
break;
case 5:
case 6:
break;
default:
System.out.println(" Invalid Entry");
}//end switch
}
}
}
There is my whole menu class as asked for.
EDIT: when I forget the user input and hard input it using: myUnit.add("John","tommy",12);
I get "Student Database is full" about one hundred times..
Wild guess, when you use your menu and type 1 then ENTER a carriage return (\n) for the ENTER is still present in your Scanner after nextInt() is called.
So next call to readLine() will use the \n (remaining ENTER) for the line and will not wait for user input.
Possible correction:
public static int menuSystem()
{
final Scanner keyb = new Scanner(System.in);
// ...
}
public static void main(String[] args) {
final UnitResults myUnit = new UnitResults(3, "Java");
int option = menuSystem();
while (option != 6) {
final Scanner keyb = new Scanner(System.in);
// ...
option = menuSystem();
}
}
And removal of the static kbd declaration
A better solution is to simply call keyb.nextLine() after calling keyb.nextInt() to handle the end of line token. Quite simply change this:
System.out.println(" Please Enter The Students Mark");
int newGrade = keyb.nextInt();
myUnit.add(tempfName, tempsName,newGrade);
to this:
System.out.println(" Please Enter The Students Mark");
int newGrade = keyb.nextInt();
keyb.nextLine(); // ****** add this *******
myUnit.add(tempfName, tempsName,newGrade);