My program is a simple program that involves the use of objects. There are no errors the only problem is that my program is printing out junk. After it asked the user for it name, age , and gender.
Down below are two sets of programs. The first one is the object or the skeleton of the person. The second one is the print that asks for the user name age gender and prints it out.
public class Person
{
private String name;
private int age,personality,appearance;
private String gender;
//constructor method. only use it once
public Person(String nm, int ag,String gend) {
name=nm;
age=ag;
gend=gender;
personality=1+(int)(Math.random()*10);
appearance=1+(int)(Math.random()*10);
}
//accessor created
public String getName() {
return name;
}
public String getGend() {
return gender;
}
public int getInt() {
return age;
}
//mutator method. When using "void" NO RETURN TYPE
public void setName (String nm) {
name=nm;
}
public void setAge (int ag) {
age=ag;
}
public void setGender (String gend)
{
gender=gend;
}
//helper method (kind of like print but not really printing
public String toString () {
String orange ="";
orange ="Name "+name+"/n";
orange +="age"+age+"/n";
orange +="Gender: "+gender"/n";
orange +="Personality "+personality+"/n";
orange +="Apperance "+appearance+"/n";
return orange;
}
}
2)
import java .util.Scanner;
public class PersonTester {
public static void main (String []args){
// calling person
Person person;
String name="", gender ="";
int age =0;
Scanner input =new Scanner(System.in);
System.out.println ("What is your name");
name =input.nextLine();
System.out.println("What your age?");
age=input.nextInt();
input.nextLine();
System.out.println ("What is your gender");
gender =input.nextLine();
person=new Person (name,age,gender);
System.out.println(person);
}
We are learning bout basic objects for example we only learned about private variables,constructor, accessor, mutator, and helper methods.
In your toString() you have two errors. You need to use a + between gender"/n" and you need to use \n if you want a newline.
public String toString () {
return "Name " + name + "\n" +
"Age" + age + "\n" +
"Gender: " + gender + "\n" +
"Personality " + personality + "\n" +
"Appearance " + appearance + "\n";
}
If the problem is the gender is not printed out properly, the problem is in your constructor. You are passing in gend, but not saving it. Instead you overwrite the argument with the gender member variable:
public Person(String nm, int ag,String gend)
{
name=nm;
age=ag;
gend=gender;
You wanted:
gender = gend;
Related
I tried a for loop with an if in it but I didn't know what I should've put in if(?), so then I went for using try and a catch and imported InputMismatchException. I then tried making an array with numbers from 0 to 9(I am a noob and don't know what I am doing) and used a for loop with and if, I know I could use a while. Please help me recent them from entering a string instead of numbers.
import java.util.Scanner;
import java.util.Arrays;
import java.util.InputMismatchException;
public class Employee {
// fields
private String firstName, lastName;// creates both firstName and lastName as string and private fields
private String sal;// creates sal a private and double field
private int years;// creates years a private and int field
// constructors
public Employee() {// default constructor
this("", "", 0, 0);// this sets the default values for each one of the fields
}
public Employee(String firstName, String lastName, double sal, int years) {// overloaded constructor
this.firstName = firstName;// gets the values from the field firstname and then puts it in string firstname
this.lastName = lastName;// gets the value from the field secondname and then puts it in string
// secondname
this.sal = sal;// gets the value from the field sal and then puts it in float sal
this.years = years;// gets the value from the field years and then puts it in int years
}
// methods
public String getFirstName() {// accessor for the field firstname
return firstName;
}
public void setFirstName(String firstName) {// mutator for the field firstname
this.firstName = firstName;
}
public String getLastName() {// accessor for the field lastname
return lastName;
}
public void setLastName(String lastName) {// mutator for the field lastname
this.lastName = lastName;
}
public String getSal() {// accessor for the field lastname
return sal;
}
public void setSal(String sal) {// mutator for the field sal
this.sal = sal;
}
public int getYears() {// accessor for the field years
return years;
}
public void setYears(int years) {// mutator for the field years
this.years = years;
}
public void ScannerMethod() {
int arrInt[] = new int[10];
arrInt[0] = 0;
int j = 0;
boolean a = false;
Scanner get = new Scanner(System.in);
System.out.println("enter first name: ");
firstName = get.next();
System.out.println("enter second name: ");
lastName = get.next();
System.out.println("enter the salary: ");
while(j<10) {
arrInt[j] = j+1;
j++;
}
for(int i = 0; i<1; i++){
if(sal == arrInt[]){
System.out.println("Pleas enter it agian: ");
sal = get.next();
i = 0;
}else{
i = 2;
}
}
/*/while (!a) {
try {
sal = get.nextDouble();
a = false;
} catch (Exception e) {
System.out.println("Invalid input please enter a numeric value: ");
a = true;
}
}/*/
System.out.println("enter the years of service: ");
years = get.nextInt();
}
public String typeStats() {// this method prints out the stats for the employee
System.out.println("Report: " + firstName.substring(0, 1).toUpperCase() + firstName.substring(1) + " "
+ lastName.substring(0, 1).toUpperCase() + lastName.substring(1) + " $" + sal + " " + years);
return null ;
}
}
Here is a method which asks the user for a double until they input a valid double.
package test2134235;
import java.util.Scanner;
public class ParseDouble {
public static void main(String[] args) {
System.out.println("This is your double: " + getDoubleFromKeyboard());
}
static Double getDoubleFromKeyboard() {
Scanner scanner = new Scanner(System.in);
for (;;) {
System.out.println("input a Double value");
try {
String input = scanner.nextLine();
Double d = Double.parseDouble(input);
return d;
} catch (NumberFormatException e) {
System.out.println("Sorry, only Double values can be used.");
}
}
}
}
You have a comment and an answer that I think address your needs. I wanted to literally answer the question implied in your header: "Trying to stop the user from entering a String into my double in java"
The answer is you can't control what the user types in to the console. What is typed into the console is always going to be characters and read in as a String. It's your job (as the comment and the answer address) to make sure bad input doesn't crash your program. So you need to analyze it and ask "Does this look like it's a double?" and if it does, go ahead and store it in your variable and if not, take some other action like prompting the user to try again.
so im just starting to study java and planning to learn it in-depth and then i wanna ask this thing because im stuck and to learn more.
im trying to use the get and return method.
i wanted to do this in an input way but i cant use the
"int age = person1.GetAge()
System.out.println("Age:" + age) because it will become 2 variables (age)
i hope you understand my question and i know it sounds stupid but i wanna learn xD.
CODE:
//unfinished
//cant use the getAge, no idea how; the value in yrsleft is always 65 despite of the formula that i give
package practice;
import java.util.Scanner;
class person{
String name;
int age;
void speak() {
System.out.print("Hello my name is:" + name);
}
int retire() {
int yrsleft = 65 - age;
return yrsleft;
}
int GetAge() {
return age;
}
}
public class curiosity1{
public static void main(String[]args) {
person person1 = new person();
Scanner input = new Scanner(System.in);
System.out.print("What is your name:");
String name = input.next();
System.out.print("What is your age:");
int age = input.nextInt();
//person1.name = "John";
//person1.age = 30;
System.out.println("Name: " + name);
int age = person1.GetAge();
System.out.println("Age:" + age);
int years = person1.retire();
System.out.println("Years till retirement:" + years);
}
}```
I hope I understood your question correctly, you want to do this?
person1.age = input.nextInt();
person1.name = input.next();
System.out.println("Age:" + person1.getAge());
Or you can override toString() method in your class (since all java classes are inherited from Object, which has this method) to represent your object with a string. Also, you should create a constructor for your Person class.
class Person { // always start class name with a capital letter
int age;
String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
// Your methods and etc.
#Override
public String toString() {
return "Name:" + this.name + ". Age:" + this.age;
}
}
And then:
int age = input.nextInt();
String name = input.next();
Person person1 = new Person(age, name);
System.out.println(person1.toString());
main class :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Student std = new Student();
System.out.println("plz , inter id :");
std.setId(input.nextInt());
System.out.println("plz , inter name :");
std.setName(input.next());
System.out.println("plz , inter Age :");
std.setAge(input.nextInt());
System.out.println("plz , inter department :");
std.setDepartment(input.next());
System.out.println("plz , inter GPA :");
std.setGpa(input.nextFloat());
std.printStudentInfo();
}
}
Student class :
public class Student {
private int id;
private String name;
private int age;
private String department;
private float gpa;
public void setId(int Pid) {
this.id = Pid;
}
public int getId() {
return this.id;
}
public void setName(String Pname) {
this.name = Pname;
}
public String getName() {
return this.name;
}
public void setAge(int Page) {
this.age = Page;
}
public int getAge() {
return this.age;
}
public void setDepartment(String Pdepartment) {
this.department = Pdepartment;
}
public String getDepartment() {
return this.department;
}
public void setGpa(float Pgpa) {
this.gpa = Pgpa;
}
public float getGpa() {
return this.gpa;
}
public void printStudentInfo() {
System.out.println("-------------- " + "[" + this.id + "]" + " "
+ this.name.toUpperCase() + " -----------------");
System.out.println("age : " + this.age);
System.out.println("Department : " + this.department);
System.out.println("Gpa : " + this.gpa);
}
}
this is a simple application that reads some data from the user and print it out , I want to read more than one word from the user in my tow string fields "name , department" , but , when I inter department name of two or more words like "computer science " , I get an error , I also tried to use nextline() instead of next() , similar results , I end up making another error !
Please, just add this :
input.useDelimiter("\r\n");
after
Scanner input = new Scanner(System.in);
No need to readLine().
From javadoc :
public Scanner useDelimiter(Pattern pattern)
Sets this scanner's delimiting pattern to the specified pattern.
Parameters:
pattern - A delimiting pattern
Returns:
this scanner
It means that the pattern set will be the delimiter when you will call next[...](). It will split according to this pattern.
So the default one is obviously a space. In fact this is : \p{javaWhitespace}+
The problem is that input.nextInt() only reads an integer. So when you press enter after your number, the input.next() will scan that newline instead of the input you type. So try to add an extra input.nextLine() to filter that newline and scan for your correct input:
Scanner input = new Scanner(System.in);
Student std = new Student();
System.out.println("plz , inter id :");
std.setId(input.nextInt()); //scans the number until newline
input.nextLine(); //scans the newline from the previous input
System.out.println("plz , inter name :");
std.setName(input.nextLine());
System.out.println("plz , inter Age :");
std.setAge(input.nextInt());
input.nextLine();
System.out.println("plz , inter department :");
std.setDepartment(input.nextLine());
System.out.println("plz , inter GPA :");
std.setGpa(input.nextFloat());
std.printStudentInfo();
Note: this code is tested
Please excuse what is probably a very basic question, but I am writing a program to store employee info and it works fine until it tries to set the info inside my employee class. It gives a stackoverflow error and I cannot figure out why. Thanks for any help.
Main class:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);
System.out.println("Enter the number of employees to enter.");
int employeeCount = Input.nextInt();
Input.nextLine();
Employee employee[] = new Employee[employeeCount];
String namesTemp;
String streetTemp;
String cityTemp;
String stateTemp;
String zipCodeTemp;
String address;
String dateOfHireTemp;
for(int x = 0; x < employeeCount; x++)
{
System.out.println("Please enter the name of Employee " + (x + 1));
namesTemp = Input.nextLine();
System.out.println("Please enter the street for Employee " + (x + 1));
streetTemp = Input.nextLine();
System.out.println("Please enter the city of Employee " + (x + 1));
cityTemp = Input.nextLine();
System.out.println("Please enter the state of Employee " + (x + 1));
stateTemp = Input.nextLine();
System.out.println("Please enter the zip code of Employee " + (x + 1));
zipCodeTemp = Input.nextLine();
address = streetTemp + ", " + cityTemp + ", " + stateTemp + ", " + zipCodeTemp;
System.out.println("Please enter the date of hire for Employee " + (x + 1));
dateOfHireTemp = Input.nextLine();
System.out.println("The employee ID for employee " + (x + 1) + " is " + (x + 1));
employee[x] = new Employee(x, namesTemp, address, dateOfHireTemp);
}
}
}
Employee class:
public class Employee
{
private int employeeID;
private Name name;
private Address address;
private DateOfHire hireDate;
public Employee()
{
}
public Employee(int employeeID, String name, String address, String hireDate)
{
String temp;
Name employeeName = new Name(name);
this.employeeID = employeeID;
}
}
Name class:
public class Name
{
public Name name;
public Name(String name)
{
Name employeeName = new Name(name);
this.name = employeeName;
}
}
The most common cause of StackoverflowExceptions is to unknowingly have recursion, and is that happening here? ...
public Name(String name)
{
Name employeeName = new Name(name); // **** YIKES!! ***
this.name = employeeName;
}
Bingo: recursion!
This constructor will create a new Name object whose constructor will create a new Name object whose constructor will... and thus you will keep creating new Name objects ad infinitum or until stack memory runs out. Solution: don't do this. Assign name to a String:
class Name {
String name; // ***** String field!
public Name(String name)
{
this.name = name; // this.name is a String field
}
Typically a class is used to group data together with functionality. It appears that the Name class is simply a wrapper for a String without adding any functionality. At this point in your Java career, it is probably better to declare String name; in the Employee class and remove the Name class all together. (Note that this would remove the error from your code that Hovercraft Full of Eels described.)
public class Roster extends ArrayList<Student>
{
public boolean containsStudent(String ln)
{
Scanner user_input = new Scanner (System.in);
System.out.println("Enter last name of student: ");
String lName = user_input.next();
for (Student student : this)
{
if (student.getLastName().equals(lName))
return true;
}
return false;
}
How can I fix the error in the next method:
public Student retrieveByld(int id)
{
Scanner user_input = new Scanner (System.in);
System.out.println("Enter the ID of the student: ");
String idNum = user_input.next();
for (Student student : this)
{
if (student.getID().equals(idNum))
return student.getFullName();
}
return " ";
}
Error: int cannot be dereferenced. I'm guessing I cannot compare to ints using the .equals method but how can I without changing the syntax too much.
Given the id, I have to make the program find the student in the list and return that students full name. If student not found I have to return null. If it helps here's my Student class.
public class Student
{
private String lName, fName;
private int idNum;
public Student(int id, String fn, String ln)
{
lName = ln;
fName = fn;
idNum = id;
}
public String getFullName()
{
return fName + " " + lName;
}
public String getLastName()
{
return lName;
}
public String getFirstName()
{
return fName;
}
public int getID()
{
return idNum;
}
public String toString()
{
return fName + " " + lName + " " + idNum;
}
}
ints do not have the equals() method to see if they are equal, they use the == operator, as it's a primitive type. What you're looking for to change is the line if (student.getID().equals(idNum)), which should be: if (student.getID() == idNum).
Your getID() method returns an int, which is a primitive type, meaning it does not have any methods, including the "equals" that you're trying to call. So, either you need to change your idNum from a String to an int, or you need to change what you get back from student.getID() to a String.
Since you're using a Scanner, that has a nextInt() method, which will return the user input as an int. Then you just check for equals using the standard == operator.
Something like this:
public Student retrieveByld(int id)
{
Scanner user_input = new Scanner (System.in);
System.out.println("Enter the ID of the student: ");
int idNum = user_input.nextInt();
for (Student student : this)
{
if (student.getID() == idNum)
return getFullName();
}
return " ";
}
Use Integer class. It's a wrapper around int, giving you access to such things as equals() method: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html