Mooc Helsinki Part 1 Week 4 Exercise 18 Java Weird Occurrence - java

Having a problem here with this error which the solution to is simply beyond me.
FAIL: PersonalInformationCollectionTest testInputFirst
Something weird occurred. It could be that the void main (String[] args) method of the class class PersonalInformationCollection has disappeared or your program crashed due to an exception. More information: java.util.NoSuchElementException.
It then says the same thing but for testInputSecond as well.
Can't find any reason for whats wrong. Looked online at a correct solution and perhaps it's just my poor eye sight but i couldn't see a single difference between my somehow incorrect code and their correct code.
Thanks for any help in advance.
import java.util.ArrayList;
import java.util.Scanner;
public class PersonalInformationCollection {
public static void main(String[] args) {
// implement here your program that uses the PersonalInformation class
ArrayList<PersonalInformation> infoCollection = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("First name: ");
String firstName = scanner.next();
if (firstName.isEmpty()){
break;
}
System.out.println("Last name: ");
String lastName = scanner.next();
System.out.println("Identification number: ");
String idNumber = scanner.next();
infoCollection.add(new PersonalInformation(firstName, lastName, idNumber));
}
for (PersonalInformation personalInfo : infoCollection){
System.out.println(personalInfo.getFirstName() + " " + personalInfo.getLastName());
}
}
}

Solved by using scanner.nextLine() rather than scanner.next(). No idea how that made such a difference in this case

Use the more general type for your variables as you can, because it doesn't change the logic if you would use an LinkedList instaed of an Arraylist and also it has the same methods you are using.
For strings use scanner,nextLine()
numberId or simply id should be a number integer would be great so use scanner.nextInt() to get only integer in here
implement/override the toString methode in your class PersonalInformation to have the string reprensetation at one point
class PersonalInformation
public class PersonalInformation {
private final int id;
private final String firstName;
private final String lastName;
public PersonalInformation(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
private int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
#Override
public String toString() {
return "PersonalInformation{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
class PersonalInformationCollection
public static class PersonalInformationCollection {
public static void main(String[] args) {
// implement here your program that uses the PersonalInformation class
List<PersonalInformation> infoCollection = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Identification number: ");
int id = scanner.nextInt();
if (id < 0){
break;
}
System.out.print("First name: ");
String firstName = scanner.nextLine();
System.out.print("Last name: ");
String lastName = scanner.next();
infoCollection.add(new PersonalInformation(id, firstName, lastName));
}
for (PersonalInformation personalInfo : infoCollection){
System.out.println(personalInfo);
}
scanner.close();
}
}

Related

How can i access the variable from different class method

This is the main file, im trying to print the result of the Age, Name, Birthdate, etc.
LabExercise1
package labexercise1;
/**
*
* #author user
*/
public class LabExercise1{
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
NewClass newClass = new NewClass();
NewClass.getFirstName();
NewClass.getLastName();
NewClass.getAge();
NewClass.getBirthDate();
NewClass.getGWA();
// TODO code application logic here
System.out.println("My name is " + FirstName + "." + " I am " + Age + " years old and the day that i was born is on " + BirthDate + ". My general weighted average this semester is " + GWA + ".");
}
NewClass
package labexercise1;
import java.util.Scanner;
/**
*
* #author user
*/
public class NewClass {
public static void getFirstName(){
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter First Name: ");
String FirstName = myObj.nextLine(); // Read user input
}
public static void getLastName(){
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter Last Name: ");
String LastName = myObj.nextLine(); // Read user input
}
public static void getAge(){
Scanner myObj = new Scanner(System.in);
System.out.println("Enter your age: ");
int Age = myObj.nextInt();
}
public static void getBirthDate(){
Scanner myObj = new Scanner(System.in);
System.out.println("Enter your BirthDate: ");
String BirthDate = myObj.nextLine();
}
public static void getGWA(){
Scanner myObj = new Scanner(System.in);
System.out.println("Enter your GWA: ");
float GWA = myObj.nextFloat();
}
}
A lot of this is basic Java 101, concepts and ideas which you should be building around "what is an object".
I would, highly, recommend taking the time to go through things like...
Declaring Member Variables
Defining Methods
Providing Constructors for Your Classes
Passing Information to a Method or a Constructor
Understanding Class Members
For example...
import java.text.ParseException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws ParseException {
new Main();
}
public Main() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter First Name: ");
String firstName = scanner.nextLine();
System.out.print("Enter Last Name: ");
String lastName = scanner.nextLine();
System.out.print("Enter Age: ");
int age = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter Birthdate: ");
String dateOfBirth = scanner.nextLine();
System.out.print("Enter GWA: ");
int gwa = scanner.nextInt();
scanner.nextLine();
Person person = new Person(firstName, lastName, age, dateOfBirth, gwa);
System.out.println("First name = " + person.getFirstName());
System.out.println("Last name = " + person.getLastName());
System.out.println("Age = " + person.getAge());
System.out.println("Date of birth = " + person.getDateOfBirth());
System.out.println("GWA = " + person.getGwa());
}
public class Person {
private String firstName;
private String lastName;
private int age;
private String dateOfBirth;
private int gwa;
public Person(String firstName, String lastName, int age, String dateOfBirth, int gwa) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.dateOfBirth = dateOfBirth;
this.gwa = gwa;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public int getGwa() {
return gwa;
}
}
}
Please keep in mind, Stack overflow is NOT a tutorial site/forum and you will, ultimately, be expected to make the effort to learn these basic concepts.

Why do I keep getting null instead of the output I want?

This assignment requires me to take in input and print it out. The first half of the output is printing currently, but the other half is giving me null. What's wrong here?
Heres my code:
This is the main class.
import java.util.*;
public class Assignment4 {
public static void main(String[] args) {
// local variables, can be accessed anywhere from the main method
char input1 = 'Z';
// String inputInfo= "";
String courseName, firstName, lastName, office, university;
String line = new String();
// instantiate a Course object
Course cse110 = null;
printMenu();
// Create a Scanner object to read user input
Scanner scan = new Scanner(System.in);
do // will ask for user input
{
System.out.println("What action would you like to perform?");
line = scan.nextLine();
if (line.length() == 1) {
input1 = line.charAt(0);
input1 = Character.toUpperCase(input1);
// matches one of the case statement
switch (input1) {
case 'A': // Add a course
System.out.print("Please enter the Instructor information:\n");
System.out.print("Enter instructor's first name:\t");
firstName = scan.nextLine();
System.out.print("Enter instructor's last name:\t");
lastName = scan.nextLine();
System.out.print("Enter instructor's office number:\t");
office = scan.nextLine();
Instructor myInstructor = new Instructor(firstName, lastName, office);
System.out.print("\nPlease enter the Course information:");
System.out.print("\nEnter course name:\t");
courseName = scan.nextLine();
System.out.print("Enter university name:\t");
university = scan.nextLine();
cse110 = new Course(courseName, myInstructor, university);
break;
case 'D': // Display course
System.out.print(cse110.toString());
break;
case 'Q': // Quit
break;
case '?': // Display Menu
printMenu();
break;
default:
System.out.print("Unknown action\n");
break;
}
} else {
System.out.print("Unknown action\n");
}
} while (input1 != 'Q' || line.length() != 1);
scan.close();
}
/** The method printMenu displays the menu to a user **/
public static void printMenu() {
System.out.print("Choice\t\tAction\n" + "------\t\t------\n" + "A\t\tAdd Course\n" + "D\t\tDisplay Course\n"
+ "Q\t\tQuit\n" + "?\t\tDisplay Help\n\n");
}
}
Heres the Course class:
import java.util.*;
public class Course
{
//----------------------------------------------------------------------
// ATTRIBUTES
private String courseName;
private Instructor instructor;
private String university;
//----------------------------------------------------------------------
// CONSTRUCTOR
public Course()
{
courseName = "?";
university = "?";
instructor = null;
}
public Course(String name, Instructor inst, String univer)
{
this.setName(name);
this.setInstructor(name, Instructor.lastName, Instructor.officeNum);
this.setUniversity(univer);
}
//----------------------------------------------------------------------
// ACCESSORS
public String getName()
{
return courseName;
}
public String getUniversity()
{
return university;
}
public Instructor getInstructor()
{
return instructor;
}
//----------------------------------------------------------------------
//METHODS
public void setName(String someName)
{
this.courseName = someName;
}
public void setUniversity(String someUniversity)
{
this.university = someUniversity;
}
public void setInstructor(String firstName, String lastName, String office)
{
Instructor.firstName = firstName;
Instructor.lastName = lastName;
Instructor.officeNum = office;
}
public String toString()
{
return "Course name:\t" + courseName + " at " + university + "\nInstructor Information:" + instructor + "\n";
}
}
Heres the Instructor class:
import java.util.*;
public class Instructor
{
//----------------------------------------------------------------------
// ATTRIBUTES
public static String firstName;
public static String lastName;
public static String officeNum;
//----------------------------------------------------------------------
// CONSTRUCTOR
public Instructor()
{
firstName = "?";
lastName = "?";
officeNum = "?";
}
public Instructor(String first, String last, String office)
{
this.setFirstName(first);
this.setLastName(last);
this.setOfficeNum(office);
}
public Instructor(Instructor inst)
{
firstName = inst.firstName;
lastName = inst.lastName;
officeNum = inst.officeNum;
}
//----------------------------------------------------------------------
// ACCESSORS
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getOfficeNum()
{
return officeNum;
}
//----------------------------------------------------------------------
//METHODS
public void setFirstName(String someFirstName)
{
this.firstName = someFirstName;
}
public void setLastName(String someLastName)
{
this.lastName = someLastName;
}
public void setOfficeNum(String someOffice)
{
this.officeNum = someOffice;
}
public String toString()
{
return ("\nLast Name:\t" + lastName +
"\nFirst Name:\t " + firstName +
"\nOffice Number:\t" + officeNum);
}
}
And finally heres the output:
> Choice Action
------ ------
A Add Course
D Display Course
Q Quit
? Display Help
What action would you like to perform?
A
Please enter the Instructor information:
Enter instructor's first name: John
Enter instructor's last name: Appleseed
Enter instructor's office number: 501
Please enter the Course information:
Enter course name: Intro to Java
Enter university name: ASU
What action would you like to perform?
D
Course name: Intro to Java at ASU
Instructor Information:null
What action would you like to perform?
Instead of Information:null, it should be printing out:
Last name: Appleseed
First name: John
Office Number: 501
How can I fix this?
Thanks!
You've never set the instructor property inside Course, after it is initialized as null. You should not use static fields in Instructor. You should create a new Instructor() and assign the instructor instance to the instructor property of Course
First fix your Instructor class:
public class Instructor
{
/******These should not be public static********/
private String firstName;
private String lastName;
private String officeNum;
...
}
Next fix your Course class
public class Course
{
private String courseName;
private Instructor instructor;
private String university;
public Course(String name, Instructor inst, String univer)
{
this.setName(name);
this.setInstructor(inst);
this.setUniversity(univer);
}
public void setInstructor(Instructor inst)
{
this.instructor = inst;
}
...
}

Passing console input from scanner into a java object, cannot find symbol error

I have a student class which consist of first and last name methods and constructor. I need to create a method that passes console input and assign it to a student object and can print the full name and the first name separately in the main method.
Student Class
public class Student {
private String firstName;
private String lastName;
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
#Override
public String toString(){
return firstName + " " + lastName;
}
}
StudentName Class
import java.util.Scanner;
public class StudentName {
public static void main(String[] args) {
System.out.println("Your full name is " + getStudentFullName(newStudent));
System.out.println("Your first name is " + getStudentFullName(firstName));
}
public static void getStudentFullName(Student student){
Scanner sc = new Scanner(System.in);
System.out.print("What is your full name?");
String name = sc.nextLine();
name = name.trim();
int index1 = name.indexOf(" ");
String firstName = name.substring(0,index1);
String lastName = name.substring(index1 + 1);
Student newStudent = new Student(firstName,lastName);
}
}
Update: Error messages
error: cannot find symbol
System.out.println("Your full name is " + getStudentFullName(newStudent));
symbol: variable newStudent
location: class StudentName
error: cannot find symbol
System.out.println("Your first name is " + getStudentFullName(firstName));
symbol: variable firstName
location: class StudentName
You are calling the getStudentFullName method in a wrong way.
in line System.out.println("Your full name is " + getStudentFullName(newStudent)); where's the newStudent variable? you can have two approches : first you can define it in main method and pass it to getStudentFullName method and in this method change the passed argument instead of creating a new one as below :
public class StudentName {
public static void main(String[] args) {
Student newStudent = new Student();
System.out.println("Your full name is " + getStudentFullName(newStudent));
}
public static void getStudentFullName(Student student){
Scanner sc = new Scanner(System.in);
System.out.print("What is your full name?");
String name = sc.nextLine();
name = name.trim();
int index1 = name.indexOf(" ");
String firstName = name.substring(0,index1);
String lastName = name.substring(index1 + 1);
student.setFirstName(firstName);
student.setLastName(lastName);
}
}
or you can return the newStudent from the getStudentFullName method as below:
public class StudentName {
public static void main(String[] args) {
System.out.println("Your full name is " + getStudentFullName(newStudent));
}
public static Student getStudentFullName(Student student){
Scanner sc = new Scanner(System.in);
System.out.print("What is your full name?");
String name = sc.nextLine();
name = name.trim();
int index1 = name.indexOf(" ");
String firstName = name.substring(0,index1);
String lastName = name.substring(index1 + 1);
Student newStudent = new Student(firstName,lastName);
return newStudent;
}
}
but in line System.out.println("Your first name is " + getStudentFullName(firstName)); what is the firstName? if it is a String variable you can't pass it to getStudentFullName because it accepts a variable of type Student as an argument not a String.
after all, it's better you put the code of getting the input form console in main method!

Making output match whats needed

I have a practice problem that I need to complete and have done everything however I cannot get the output to match whats needed. I have tried some of the google answers but nothing seems to be working. Below is the code and the output I get vs what I want. We are not allowed to modify the main method but only the classes.
I am just confused on how to make the output from each class start on a new line.
There is this statement in the instructions but I don't understand how to go about it:
the Student class should have a public display function that calls the parent class’ display
function,
Code:
public class H255{public static void main (String[] args){while (JPL.test()){
Person pObj = new Person("Albert","Einstein");
Student sObj = new Student("John","Smith",123456,"First Year","Pullan");
Teacher tObj = new Teacher("Wayne","Pullan","Computer Science",100000,"Lecturer");
System.out.println("Person :");
pObj.Display();
System.out.println("");
System.out.println("Student :");
sObj.Display();
System.out.println("");
System.out.println("Teacher :");
tObj.Display();
}}}
class Person{
private String FirstName;
private String LastName;
public Person(String fName, String lName){
this.FirstName = fName;
this.LastName = lName;
}
public void Display(){
System.out.println("First Name: " + FirstName + " Last Name: " + LastName);
}
}
class Student extends Person{
private int id;
private String standard;
private String instructor;
public Student(String fName, String lName, int nId, String stnd, String instr){
super(fName, lName);
this.id = nId;
this.standard = stnd;
this.instructor = instr;
}
public void Display(){
System.out.println("ID: " + id + "Standard: " + standard + "Instructor: " + instructor);
}
}
class Teacher extends Person{
private String mainSubject;
private int salary;
private String type;
public Teacher(String fName, String lName, String sub, int slry, String sType){
super(fName, lName);
this.mainSubject = sub;
this.salary = slry;
this.type = sType;
}
public void Display(){
System.out.println("Main Subject: " + mainSubject + "Salary: "
+ salary + "Type: " + type );
}
}
Output:
the writing of main method like these code:
System.out.print("Person :");
pObj.Display();
System.out.print("Student :");
sObj.Display();
System.out.print("Teacher :");
tObj.Display();
because:the println method has a build in wrap feature, so just replace println with print.

arraylist with method

As my last question obviously was a little bit unclear (I applogise for that), I'm making a new try, and this time I will really try to be clear.
Here is the code I have written so far
Main class:
import java.util.*;
public class Head {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String fname, lname;
int choice;
ArrayList<People>list = new ArrayList<>();
People p1 = new People("Mia", "Wallace", "1111");
People p2 = new People("Marcellus", "Wallace", "2222");
list.add(p1);
list.add(p2);
System.out.println("Welcome");
System.out.println("1) Add person \n2) Last name \n3) Print list");
choice = scan.nextInt();
switch(choice){
case 1:
People.walk(); //calling the method
break;
case 2:
People.run();
break;
case 3:
People.crawl();
break;
}
}
}
People class:
import java.util.*;
public class People {
static Scanner scan = new Scanner(System.in);
private static String fname;
private static String lname;
private static String dob;
public People(String fname, String lname, String dob){
this.fname = fname;
this.lname = lname;
this.dob = dob;
}
public String getFname(){
return fname;
}
public String getLname(){
return lname;
}
public String getDob(){
return dob;
}
public static void walk(){
System.out.println("Enter first name: ");
fname = scan.next();
System.out.println("Enter last name: ");
lname = scan.next();
System.out.println("Enter dob: ");
dob = scan.next();
list.add(new People(fname, lname, dob)); **//list cannot be resolved**
}
public static void run(){
System.out.println("Remove people");
}
public static void crawl(){
int peoplenumber = 0;
System.out.println("\nNumber of peoples: " + list.size()); **//list cannot be resolved**
for(People p : list){ **//list cannot be resolved**
peoplenumber += 1;
System.out.println("#" + peoplenumber + "\n" + p.toString());
}
}
public String toString(){
return "First name: " + this.fname + "\nLast name: " + this.lname + "\nDateOfBirth: " + this.dob;
}
}
I do understand why I get the error, but I don't know how to get around it. Any help?
Am I right when I try to move code from the main-class to the costructors?
If you guys have any comments or ideas how I should solve this, or move on with java, I will gladly here them.
Thank you very much for your time and your help :)
The arraylist should be in the main class. If it were in the person class, it would be created once for every person object you create. To access a method for that person, you want to call the name of the OBJECT (not the type), the .method(parameters).
If you wanted to call run on p1 (not really sure what you want to call it on), you would use:
p1.run();
That would perform the code in the run method where it is defined.

Categories