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
Related
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;
Make a program that gets user input and stores it in arrays. You will store information about, at least 3, people. There will be three pieces of information you will need to store about each person: name, age and gender (age must be an integer). After the user inputs information about every person you will print all of the information like shown below
List of people
Melissa, 28, F
Adam, 11, M
Landon, 6, M
Sadie, 1, F
How do I order the people by their age when I have String and int at the same time? Here is my code:
public static void main(String[] args) {
Scanner inputString = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.println("Enter your age:");
int age1 = input.nextInt();
System.out.println("Enter your name:");
String name1 = inputString.nextLine();
System.out.println("Enter your gender:");
String gender1 = inputString.nextLine();
System.out.println("Enter your age:");
int age2 = input.nextInt();
System.out.println("Enter your name:");
String name2 = inputString.nextLine();
System.out.println("Enter your gender:");
String gender2 = inputString.nextLine();
System.out.println("Enter your age:");
int age3 = input.nextInt();
System.out.println("Enter your name:");
String name3 = inputString.nextLine();
System.out.println("Enter your gender:");
String gender3 = inputString.nextLine();
int[] age = new int[3];
age[0] = age1;
age[1] = age2;
age[2] = age3;
String[] name = new String[3];
name[0] = name1;
name[1] = name2;
name[2] = name3;
String[] gender = new String[3];
gender[0] = gender1;
gender[1] = gender2;
gender[2] = gender3;
System.out.print("List of People");
System.out.print("\n" + (age[0]) + ", " + (name[0]) + ", " + (gender[0]));
System.out.print("\n" + (age[1]) +", " + (name[1]) +", "+ (gender[1]));
System.out.print("\n" + (age[2]) + ", " + (name[2]) +" , "+ (gender[2]));
}
If you want to learn Java, please try to first learn object oriented concepts.
In your specific case, you should be using a Person class, a single List<Person> and a Comparator of Person instances to sort your list, instead of trying to sort three different arrays. Have a look at the following example.
First, your runner class that contains the main() method:
package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import test.Person.Gender;
public class Runner {
public static void main(final String[] args) {
Scanner input = new Scanner(System.in);
Boolean createNewPerson = true;
// a single list of person instances
List<Person> people = new ArrayList<Person>();
while (createNewPerson) {
Person person = new Person();
System.out.println("Enter age:");
person.setAge(Integer.valueOf(input.nextLine()));
System.out.println("Enter name:");
person.setName(input.nextLine());
System.out.println("Enter gender:");
person.setGender(Gender.valueOf(input.nextLine().toUpperCase()));
// add the person to the list
people.add(person);
System.out.println("Add another person ? (true/false)");
createNewPerson = Boolean.valueOf(input.nextLine());
}
input.close();
// here is the sorting trick
Collections.sort(people, new AgeComparator());
// print it out
System.out.println(Arrays.toString(people.toArray()));
}
}
Your Person class:
package test;
public class Person {
private String name;
private Gender gender;
private Integer age;
public Integer getAge() {
return this.age;
}
public void setAge(final Integer age) {
this.age = age;
}
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
public Gender getGender() {
return this.gender;
}
public void setGender(final Gender gender) {
this.gender = gender;
}
#Override
public String toString() {
return this.name + " is a " + this.gender + " and is " + this.age + " year(s) old." + System.lineSeparator();
}
enum Gender {
MALE,
FEMALE;
}
}
And your Comparator (here I wrote one that compares by age, but it is only an example):
package test;
import java.util.Comparator;
public class AgeComparator implements Comparator<Person> {
#Override
public int compare(final Person person1, final Person person2) {
return person1.getAge().compareTo(person2.getAge());
}
}
In other words, programming is not about writing lines, it's about conception, design, using concepts and only then writing lines of code.
The Cullerton Part District holds a mini-Olympics each summer. Create a class named Participant with fields for a name, age, and street address. Include a constructor that assigns parameter values to each field and a toString() method that returns a String containing all the values. Also include an equals() method that determines two Participants are equal if they have the same values in all three fields. Create an application with two arrays of at least 5 Participants each--one holds the Participants in the mini-marathon and the other holds Participants in the diving competition. Prompt the user for Participants who are in both events save the files as BC.java and ABC.java.
import javax.swing.JOptionPane;
import java.util.*;
public class ABC {
private static Participant mini[] = new Participant[2];
public static void main(String[] args) {
setParticipant();
displayDetail();
}
// BC p=new BC(name,age,add);
//displayDetails();
// System.out.println( p.toString());
public static void displayDetail() {
String name=null;
String add = null;
int age=0;
System.out.println("Name\tAdress\tAge");
BC p=new BC(name,age,add);
for (int x = 0; x < mini.length; x++) {
//Participant p1=mini[x];
System.out.println(p.toString());
}
}
public static String getName() {
Scanner sc = new Scanner(System.in);
String name;
System.out.print(" Participant name: ");
return name = sc.next();
}
// System.out.print(" Participant name: ");
// name = sc.next();
public static int getAge() {
int age;
System.out.print(" Enter age ");
Scanner sc=new Scanner(System.in);;
return age= sc.nextInt();
}
public static String getAdd() {
String add;
Scanner sc=new Scanner(System.in);;
System.out.print("Enter Address: ");
return add=sc.next();
}
public static void setParticipant(){
for (int x = 0; x < mini.length; x++) {
System.out.println("Enter loan details for customer " + (x + 1) + "...");
//Character loanType=getLoanType();
//String loanType=getLoanType();
String name=getName();
String add=getAdd();
int age=getAge();
System.out.println();
}
}
}
//another class
public class BC {
private String name;
private int age;
private String address;
public BC(String strName, int intAge, String strAddress) {
name = strName;
age = intAge;
address = strAddress;
}
#Override
public String toString() {
return "Participant [name=" + name + ", age=" + age + ", address=" + address + "]";
}
public boolean equals(Participant value){
boolean result;
if (name.equals(name) && age==value.age && address.equals(address))
result=true;
else
result=false;
return result;
}
}
outPut:
Enter loan details for customer 1...
Participant name: hddgg
Enter Address: 122
Enter age 12
Enter loan details for customer 2...
Participant name: ddjkjde
Enter Address: hdhhd23
Enter age 12
//Why I'm not getting right output
Name Adress Age
Participant [name=null, age=0, address=null]
Participant [name=null, age=0, address=null]
You are getting that output because of this method:
public static void displayDetail() {
String name=null;
String add = null;
int age=0;
System.out.println("Name\tAdress\tAge");
BC p=new BC(name,age,add);
for (int x = 0; x < mini.length; x++) {
//Participant p1=mini[x];
System.out.println(p.toString());
}
}
You are creating a BC with null for name and add and 0 for age. You are then printing it twice.
The program should take two inputs and display them. However when i run it, it ask only my Age and then it prints it out. I want that the program would ask also my name.
You are 16 years old
Your name is:
import java.util.Scanner;
public class NIMEVALIK{
int Vanus;
String NIMI;
public void setAge(int vanus){
Vanus = vanus;
}
public void setName(String name){
NIMI = name;
}
public int getAge() {
System.out.println("Your are %s years old: ",Vanus);
return Vanus;
}
public String getName(){
System.out.println("Your name is: " + NIMI);
return NIMI;
}
public static void main(String[]args){
int age;
String name;
NIMEVALIK nimiObject = new NIMEVALIK();
Scanner input = new Scanner(System.in);
System.out.println("Siseta vanus");
age = input.nextInt();
nimiObject.setAge(age);
System.out.println("sisega nimi");
name = input.nextLine();
nimiObject.setName(name);
nimiObject.getAge();
nimiObject.getName();
}
}
Your code:
name = input.nextLine();
Try This :
name = input.next()+input.nextLine();
before this line:
name = input.nextLine();
add:
input.nextLine(); //junk
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.)