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.
Related
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();
}
}
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;
}
...
}
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!
This is the output of the program:
Enter your last name: Dela Cruz
Enter your first name: Juan
Enter your course: BSCS
Enter your year: 4th Year
Display Array List
[0] - Dela Cruz | Juan | BSCS | 4th Year
Add More (y/n): if yes it will add more entry...
Use following code.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class IO {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String continueAdd = "y";
List<Student> studentList = new ArrayList<>();
Student student;
while ("y".equalsIgnoreCase(continueAdd)) {
student = new Student();
System.out.println("Enter your last name:");
student.lastName = scn.nextLine();
System.out.println("Enter your first name:");
student.firstName = scn.nextLine();
System.out.println("Enter your course:");
student.course = scn.nextLine();
System.out.println("Enter your year:");
student.year = scn.nextLine();
studentList.add(student);
System.out.println("Add More (y/n): ");
continueAdd = scn.nextLine();
}
int i = 0;
for(Student studentTemp : studentList){
System.out.println("["+i+"] - " + studentTemp);
i++;
}
}
}
class Student {
String firstName;
String lastName;
String course;
String year;
#Override
public String toString(){
return lastName+" | "+ firstName +" | "+course+" | "+year;
}
}
You need :
public class Entries {
private String lname;
private String fname;
private String course;
private String year;
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}
and then your mainApp :
public class MainApp {
public static void main(String[] args) {
List<Entries> students = new ArrayList<Entries>();
Scanner scan = new Scanner(System.in);
System.out.println("Enter a student:(y/n)");
String option = scan.nextLine();
while(option.equalsIgnoreCase("y")||option.equalsIgnoreCase("yes")){
Entries stud = new Entries();
System.out.println("Enter student's first name");
stud.setFname(scan.nextLine());
System.out.println("Enter student's last name");
stud.setLname(scan.nextLine());
System.out.println("Enter student's course");
stud.setCourse(scan.nextLine());
System.out.println("Enter student's year");
stud.setYear(scan.nextLine());
students.add(stud);
System.out.println("Enter another student:(y/n)");
option = scan.nextLine();
}
if(option.equalsIgnoreCase("n")||option.equalsIgnoreCase("no")){
System.out.println("Do you want to dispay all students? (y/n");
String display = scan.nextLine();
if(display.equalsIgnoreCase("y")||display.equalsIgnoreCase("yes"))
for (Entries entrie : students) {
System.out.println(entrie.getLname()+" |"+
entrie.getFname()+" |"+
entrie.getCourse()+" |"+
entrie.getYear());
} else {
System.exit(0);;
}
} else {
System.out.println("option not availabe");
System.exit(0);
}
}
use this code
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class hi {
static String n,c,y;
static String option="";
static ArrayList al= new ArrayList();
static Scanner s=new Scanner(System.in);
public static void input(){
System.out.println("Enter the name");
n=s.next();
System.out.println("Enter the course");
c=s.next();
System.out.println("Enter the year");
y=s.next();
al.add(n+"|"+c+"|"+y);
System.out.println("Add More (y/n)");
option=s.next();
System.out.println(option);
if(option.equals("y")|| option.equals("Y")){
input();
}
else{
System.out.println(al);
//System.exit(0);
}
}
public static void main(String args[]) throws InstantiationException, IllegalAccessException{
input();
}
}
It would probably be better to have a class and work with objects but here is with List.
boolean flag = true;
List<String> list = new ArrayList<>();
int i = 0;
while (flag) {
String lastname, firstname, code, year;
Scanner sc = new Scanner(System.in);
System.out.println("Enter lastname");
lastname = sc.nextLine();
System.out.println("Enter firstname");
firstname = sc.nextLine();
System.out.println("Enter code");
code = sc.nextLine();
System.out.println("Enter year");
year = sc.nextLine();
list.add(i, lastname + " | " + firstname + " | " + code + " | " + year);
System.out.println(list.get(i));
i++;
System.out.println("add more? y/n");
if (!"y".equals(sc.next())) {
flag = false;
}
}
the question, I look at the code millions of times, may be I just can't see the simple answer but why at the point of Author name and Author Surname, system print out like this:
Enter author Name: Enter author Surname:
and it should be like this...
Enter author Name:
Enter author Surname:
and if I input information in system remember only Author first name and I can't put information for surname.
import java.util.Scanner;
public class BookTest {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
Book bookIn = new Book();
System.out.print("Enter book title: ");
bookIn.setTitleBook(scan.nextLine());
System.out.print("Enter author Name: ");
bookIn.setFirstName(scan.nextLine());
System.out.print("Enter author Surname: ");
bookIn.setSecondName(scan.nextLine());
System.out.print("Enter author Nationality: ");
bookIn.setNationality(scan.nextLine());
System.out.print("Enter book price: ");
bookIn.setPriceBook(scan.nextDouble());
System.out.print("Enter book ISBN: ");
bookIn.setIsbn(scan.nextInt());
System.out.println("Title: " +bookIn.getTitleBook());
System.out.println("Author: "+ bookIn.getFirstName()+ " " + bookIn.getSecondName());
System.out.println("Price: "+bookIn.getPriceBook());
System.out.println("ISNB Number: "+bookIn.getIsbn());
System.out.println("Aurhor Nationality: " + bookIn.getNationality());
}
}
Book Class
public class Book {
private double priceBook;
private int isbn;
private String titleBook;
private String firstName;
private String secondName;
private String nationality;
public void setTitleBook(String titleBook){
this.titleBook = titleBook;
}
public String getTitleBook(){
return titleBook;
}
public void setPriceBook(double priceBook) {
this.priceBook = priceBook;
}
public double getPriceBook() {
return priceBook;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
public int getIsbn() {
return isbn;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public String getSecondName() {
return secondName;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public String getNationality() {
return nationality;
}
}
Move the scanner to the next line after reading the ISBN. When using Scanner.nextInt the input only reads the number and not the new line character created when you press enter. Calling Scanner.nextLine after Scanner.nextInt reads the new line character and clears the buffer.
import java.util.Scanner;
public class BookTest {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
Book title = new Book();
Book price = new Book();
Book isbn = new Book();
Book fName = new Book();
Book sName = new Book();
Book nation = new Book();
System.out.print("Enter book title: ");
title.setTitleBook(scan.nextLine());
System.out.print("Enter book price: ");
price.setPriceBook(scan.nextDouble());
System.out.print("Enter book ISBN: ");
isbn.setIsbn(scan.nextInt());
scan.nextLine(); //NOTICE CHANGE HERE
//System.out.println(); THIS WAS REMOVED
System.out.print("Enter author Name: ");
fName.setFirstName(scan.nextLine());
System.out.print("Enter author Surname: ");
sName.setSecondName(scan.nextLine());
System.out.print("Enter author Nationality: ");
nation.setNationality(scan.nextLine());
System.out.println("Title: " +title.getTitleBook());
System.out.println("Price: "+price.getPriceBook());
System.out.println("ISNB Number: "+isbn.getIsbn());
System.out.println("Author: "+ fName.getFirstName() + sName.getSecondName());
System.out.println("Aurhor Nationality: " + nation.getNationality());
}
}