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);
Related
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.
I am trying to make an address book that prompts you enter the first, last, street address, city, State, and zip code for three people.
Then be able to search for any of the info the user inputs and then display all of the info for that person.
I have managed to get it to prompt the user for adding the info but I can't seem to figure out how to search the arraylist for the info.
for (int count = 0; count < 3; count++)
{
aBook.add(new YAAddressBook());
aBook.get(count).addEntry();
System.out.println();
}
int foundIndex = YAAddressBook.search(aBook);
System.out.println();
if (foundIndex > -1)
aBook.get(foundIndex).display();
System.out.println("Found");
else
System.out.println("No Entry Found");
}
}//end YoungAndrewChapter10
import java.util.ArrayList;
import java.util.Scanner;
public class YAAddressBook
{
private static String first;
private static String last;
private static String choice;
private static String searchA;
private static Scanner keybd = new Scanner(System.in);
private String street;
private String cityState;
private String zip;
private int answer = 0;
public static int search(ArrayList<YAAddressBook> aBook)
{
System.out.print("Search Menu: \n1. Search First Name \n2. Search Last
Name\n3.Search Street Address \n4.Search City, State \n5.Search Zip Code \n\n");
System.out.print("Please Enter Field to Search: ");
choice = keybd.nextLine();
System.out.print("Please Enter Value to Search For: ");
searchA = keybd.nextLine();
switch (choice)
{
case "1":
break;
case "2":
break;
case "3":
break;
case "4":
break;
case "5":
break;
default:
break;
}
return -2;
}
public void addEntry()
{
YAAddressBook aBook = new YAAddressBook();
System.out.print("Please Enter First Name: ");
first = keybd.nextLine();
System.out.print("Please Enter Last Name: ");
last = keybd.nextLine();
System.out.print("Please Enter Street Address: ");
street = keybd.nextLine();
System.out.print("Please Enter City, State: ");
cityState = keybd.nextLine();
System.out.print("Please Enter Zip Code: ");
zip = keybd.nextLine();
}
}//end YAAdreesBook
Depending on the field chosen, you would have to loop throughout all the arraylist until you find the correct item, for example if FirstName is chosen:
for (int i = 0; i< addressbook.size(); i++)
{
if (addressbook.get(i).FirstName == "Tom" )
return addressbook.get(i);
}
return null;
this will return the first element that matches the search, or null if nothing matches.
I have a trouble with my program. I should to create a program like a dictionary. So I probably did it but it does not work. I have a menu so it should add/edit/delete word in file. please can you help me with my program, i think there are all understandable in my code. the problem is it can not find words in file in function
editWord, deleteWord. and serachTranslation
import java.util.*;
import java.io.*;
public class Dictionary{
public static Hashtable<String, String> dictionary = new Hashtable<String, String>();
public static void main(String []args)throws InputMismatchException, IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("dict.in")));
String line = null;
while((line = br.readLine())!= null ){
String [] words = line.split("\\s+");
String kaz = words[0];
String eng = words[1];
Dictionary.dictionary.put(kaz,eng);
}
menu();
}
public static void menu(){
//Runtime.getRuntime().exec("clear");
System.out.println("1 - Add/Edit/Delete word");
System.out.println("2 - Search translation");
//System.out.println("3 - Switch language");
Scanner sc = new Scanner(System.in);
System.out.println("Enter your choice: ");
int choose = sc.nextInt();
switch(choose){
case 1: secondMenu();
break;
case 2: searchTranslation();
break;
//case 3: System.out.print("It works 3 case");
//break;
default: menu();
break;
}
}
public static void secondMenu() throws InputMismatchException{
System.out.println("1 - Add");
System.out.println("2 - Edit");
System.out.println("3 - Delete");
System.out.println("4 - Back");
Scanner sc = new Scanner(System.in);
System.out.println("Enter your choice: ");
int choose = sc.nextInt();
switch(choose){
case 1: addWord();
break;
case 2: editWord();
break;
case 3: deleteWord();
break;
case 4: menu();
break;
default: secondMenu();
break;
}
}
public static void addWord(){
Scanner w = new Scanner(System.in);
System.out.println("Enter word in Kazakh language: ");
String kaz = w.next();
System.out.println("Enter word in English language: ");
String eng = w.next();
Dictionary.dictionary.put(kaz,eng);
System.out.println("Sucsess");
menu();
}
public static void editWord(){
Scanner w = new Scanner(System.in);
System.out.println("Enter word which you want to change: ");
String word = w.next();
Iterator s = Dictionary.dictionary.keySet().iterator();
while (s.hasNext()) {
String key = (String) s.next();
Object value = Dictionary.dictionary.get(key);
if(word==key){
System.out.println("Enter new meaning of this word: ");
String newWord = w.next();
Dictionary.dictionary.remove(key);
Dictionary.dictionary.put(word,newWord);
menu();
}
if(word==value){
System.out.println("Enter new meaning of this word: ");
String newWord = w.next();
Dictionary.dictionary.remove(value);
Dictionary.dictionary.put(newWord,word);
menu();
}
}
}
public static void deleteWord(){
Scanner w = new Scanner(System.in);
System.out.println("Enter word which you want to delete: ");
String word = w.next();
Iterator s = Dictionary.dictionary.keySet().iterator();
while (s.hasNext()) {
String key = (String) s.next();
Object value = Dictionary.dictionary.get(key);
if(word==key){
Dictionary.dictionary.remove(key);
menu();
}
if(word==value){
Dictionary.dictionary.remove(value);
menu();
}
}
}
public static void searchTranslation(){
Scanner w = new Scanner(System.in);
System.out.println("Enter word which you want to translate: ");
String word = w.next();
Iterator s = Dictionary.dictionary.keySet().iterator();
while (s.hasNext()) {
String key = (String) s.next();
Object value = Dictionary.dictionary.get(key);
if(word==key){
System.out.println(word+" : "+Dictionary.dictionary.get(value));
menu();
}
if(word==value){
System.out.println(word+" : "+Dictionary.dictionary.get(key));
menu();
}
}
}
}
The whole point of a Hashtable (you should use HashMap, by the way), is to be able to find a value by key without iterating. Use its get() method to find the meaning of a word, put() to insert/update a meaning of a word, and delete() to delete a word with its meaning.
The problem is that you're using == to compare Strings, instead of equals(), but you shouldn't even have to compare anything if you used to map as it should be used, since the map would do the comparisons for you.
I am trying to write hashmap to file and read it back. Initially, my file is empty. so, when i try to read using readObject(), it throws EOFException. I caught it and proceed with normal execution. Then, I input details of a student. Insert the details in hashmap using rollnumber as key. Then, i write the hashmap to the file using writeObject(). I check the file and it had something written in it.
I close the program and execute it again.
This time it should have read the hashmap that i had written. But, instead it clears the file and still throws EOFException.
Help me.. how should i do it???
Student.java
package student;
public class Student implements java.io.Serializable {
private String name;
private int age;
class Address implements java.io.Serializable{
String house;
String street;
String city;
String state;
int pin;
Address(String house,String street,String city,int pin,String state){
this.house = new String(house);
this.street = new String(street);
this.city = new String(city);
this.state = new String(state);
this.pin = pin;
}
}
private Address addr;
private int rollnumber;
private String courses[];
public Student(String name,int age,String house,String street,String city,String state,int pin,int roll, String courses[]){
this.name = new String(name);
this.age = age;
this.addr = new Address(house,street,city,pin,state);
this.rollnumber = roll;
this.courses = new String[4];
System.arraycopy(courses, 0, this.courses, 0, 1);
System.out.println("NEW STUDENT CREATED..");
}
public String toString(){
String s = rollnumber +" "+name+" "+age+"\n";
return s;
}
int getRollNumber(){
return rollnumber;
}
}
I have made both classes Student and inner class Address serializable. Tell me if there is any trouble here.
StudentRunner.java
package student;
import java.io.*;
import java.util.*;
public class StudentRunner {
public static void main(String [] args) throws java.io.IOException, ClassNotFoundException{
String file = "student.txt";
StudentProcessor sp = new StudentProcessor();
FileOutputStream fout = new FileOutputStream(file);
FileInputStream fin = new FileInputStream(file);
ObjectOutputStream out = new ObjectOutputStream(fout);
ObjectInputStream in = new ObjectInputStream(fin);
HashMap<Integer, Student> hm= new HashMap<Integer, Student>();
Student stud=null;
try{
hm = (HashMap<Integer, Student>)in.readObject();
///////// TROUBLE IN THE ABOVE LINE ///////////
}catch(EOFException eof){
System.out.println("sfdasfasfas");
}
Scanner scanner = new Scanner(System.in);
int option=0;
do{
System.out.println("(1) Add User Details");
System.out.println("(2) Display User Details");
System.out.println("(3) Delete User Details");
System.out.println("(4) Save User Details");
System.out.println("(5) Exit");
try{
option = scanner.nextInt();
}catch(InputMismatchException ime){
System.out.println("Error!!! provide valid option(1-5).");
continue;
}
switch(option){
case 1:
try{
scanner.nextLine();
System.out.println("Enter full name: ");
String name = scanner.nextLine();
System.out.println("Enter age: ");
int age = scanner.nextInt();
System.out.println("Enter rollnumber: ");
int rollnumber = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter Address:");
System.out.println(" Enter house number ");
String house_num = scanner.nextLine();
System.out.println(" Enter street: ");
String street = scanner.nextLine();
System.out.println(" Enter city: ");
String city = scanner.nextLine();
System.out.println(" Enter state: ");
String state = scanner.nextLine();
System.out.println(" Enter pin: ");
int pin = scanner.nextInt();
String courses[] = new String[4];
System.out.println("Enter four courses(A-F)");
System.out.println(" Enter first course: ");
courses[0] = scanner.next();
System.out.println(" Enter second course: ");
courses[1] = scanner.next();
System.out.println(" Enter third course: ");
courses[2] = scanner.next();
System.out.println(" Enter fourth course: ");
courses[3] = scanner.next();
boolean flag = Validator.validateStudent(name, age, rollnumber, house_num, street, city,
state, pin, courses);
stud= new Student(name,age,house_num,street,city,state,pin,rollnumber,courses);
if(flag){
hm.put(rollnumber, stud );
}
}catch(InputMismatchException ime){
System.out.println("Error!!! Provide numeric value..");
continue;
}
break;
case 2:
Set set = hm.entrySet();
Iterator itr = set.iterator();
while(itr.hasNext()){
Map.Entry<Integer, Student> m =(Map.Entry<Integer, Student>) itr.next();
System.out.println(m.getValue());
}
break;
case 3:
break;
case 4:
out.writeObject(hm);
break;
case 5:
break;
default:
System.out.println("Error!!! provide valid option(1-5).");
continue;
}
if(option>=5)
break;
}while(true);
}
}
hm.readObject() in StudentRunner.java, is where i am reading the content. But it clears the already written content and throws EOFException.
Remember always to call the close method on the OutputStream you are using to write. The accepted idiom to do so is to do it inside a finally {} block so you make totally sure you are closing the OutputStream (and thus actually flushing the buffer into disk)
Why when I run my program and enter 5, it allows me to enter my records, but when the main menu runs again and I enter 6, the changePhoneNumber method is not run and it goes back to the main menu. Is the while(true) loop somehow messing things up?
I have a class called Record that looks like:
public static void main(String[] args) {
BankMethods method = new BankMethods();
Scanner input = new Scanner(System.in);
int optionSelected = 0;
while(true){
System.out.println("5. Add a New Record");
System.out.println("6. Change the Phone Number in the Current Record");
optionSelected = input.nextInt();
if (optionSelected == 5){
Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = getRecord.nextLine();
System.out.println("Enter Last Name: ");
String lastName = getRecord.nextLine();
System.out.println("Enter Phone Number: ");
String phoneNumber = getRecord.nextLine();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6){
System.out.println("What would you like to change your phone "
+ "number to? ");
String newNumber = input.nextLine();
method.changePhoneNumber(newNumber);
}
and the other class...BankMethods:
public class BankMethods {
LinkedList recordInformation = new LinkedList();
Bankdata mainMenu = new Bankdata();
public void addNewRecord(String firstName, String lastName,
String phoneNumber){
recordInformation.add(firstName); recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber){
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
The problem is that you are using 2 Scanners to read the one InputStream. When you open the second Scanner you will not be able to read using the original one as the second will have exclusive access to it.
For this application you could easily use a single Scanner.
See: Do not create multiple buffered wrappers on a single InputStream
The correct way is to use one read(scanner) for a input stream. Edited the previous answer to use single read option
Complete program that works is given below
package com.stackoverflow.framework;
import java.util.LinkedList;
import java.util.Scanner;
public class Record {
static Scanner input = new Scanner(System.in);
public static String readData() {
return (input.nextLine());
}
public static void main(String[] args) {
BankMethods method = new BankMethods();
int optionSelected = 0;
while (true) {
System.out.println("5. Add a New Record");
System.out
.println("6. Change the Phone Number in the Current Record");
optionSelected = Integer.parseInt(readData());
if (optionSelected == 5) {
// Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = readData();
System.out.println("Enter Last Name: ");
String lastName = readData();
System.out.println("Enter Phone Number: ");
String phoneNumber = readData();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6) {
System.out.println("What would you like to change your phone "
+ "number to? ");
// Scanner getRecord = new Scanner(System.in);
String newNumber = readData();
method.changePhoneNumber(newNumber);
}
}
}
}
class BankMethods {
LinkedList recordInformation = new LinkedList();
public void addNewRecord(String firstName, String lastName,
String phoneNumber) {
recordInformation.add(firstName);
recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber) {
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
}