trying to run multiple method - java

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

Related

How can i use input(int) in get and return method in Java?

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());

Creating an array of students based on user input

I'm trying to create an array of math students, science students, and computer students based on the user input.
So basically the user should choose what student they want to add and then enter the student details.
Below I have added the code I have so far:
Main Java class:
public class Lab4 {
public static final int DEBUG = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Student s[] = new Student[10];
s[0] = new MathStudent(4,5);
s[1] = new MathStudent(5,7);
s[2] = new MathStudent(2,8);
s[3] = new MathStudent(3,6);
s[4] = new ScienceStudent(8,9);
s[5] = new ScienceStudent(3,6);
s[6] = new ScienceStudent(4,9);
s[7] = new ComputerStudent(6,12);
s[8] = new ComputerStudent(11,14);
s[9] = new ComputerStudent(13,17);
}
}
Student class:
public class Student {
private String name;
private int age;
public String gender = "na";
public static int instances = 0;
// Getters
public int getAge(){
return this.age;
}
public String getName(){
return this.name;
}
// Setters
public void setAge(int age){
this.age = age;
}
public void setName(String name){
if (Lab4.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
this.name = name;
}
/**
* Default constructor. Populates name,age,gender,course and phone Number
* with defaults
*/
public Student(){
instances++;
this.age = 18;
this.name = "Not Set";
this.gender = "Not Set";
}
/**
* Constructor with parameters
* #param age integer
* #param name String with the name
*/
public Student(int age, String name){
this.age = age;
this.name = name;
}
/**
* Gender constructor
* #param gender
*/
public Student(String gender){
this(); // Must be the first line!
this.gender = gender;
}
/**
* Destructor
* #throws Throwable
*/
protected void finalize() throws Throwable{
//do finalization here
instances--;
super.finalize(); //not necessary if extending Object.
}
public String toString (){
return "Name: " + this.name + " Age: " + this.age + " Gender: "
+ this.gender;
}
public String getSubjects(){
return this.getSubjects();
}
}
MathStudent class:
public class MathStudent extends Student {
private float algebraGrade;
private float calculusGrade;
public MathStudent(float algebraGrade, float calculusGrade) {
this.algebraGrade = algebraGrade;
this.calculusGrade = calculusGrade;
}
public MathStudent() {
super();
algebraGrade = 6;
calculusGrade = 4;
}
// Getters
public void setAlgebraGrade(float algebraGrade){
this.algebraGrade = algebraGrade;
}
public void setCalculusGrade(float calculusGrade){
this.calculusGrade = calculusGrade;
}
// Setters
public float getAlgebraGrade() {
return this.algebraGrade;
}
public float getCalculusGrade() {
return this.calculusGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Algebra Grade: " + algebraGrade + " Calculus Grade: "
+ calculusGrade);
}
}
scienceStudent class:
public class ScienceStudent extends Student {
private float physicsGrade;
private float astronomyGrade;
/**
* Default constructor
*/
public ScienceStudent() {
super();
physicsGrade = 6;
astronomyGrade = 7;
}
public ScienceStudent(float physicsGrade, float astronomyGrade) {
this.physicsGrade = physicsGrade;
this.astronomyGrade = astronomyGrade;
}
// Getters
public void setPhysicsGrade(float physicsGrade){
this.physicsGrade = physicsGrade;
}
public void setAstronomyGrade(float astronomyGrade){
this.astronomyGrade = astronomyGrade;
}
// Setters
public float getPhysicsGrade() {
return this.physicsGrade;
}
public float getAstronomyGrade() {
return this.astronomyGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Physics Grade: " + physicsGrade + " Astronomy Grade: "
+ astronomyGrade);
}
}
computerStudent class:
public class ComputerStudent extends Student {
private float fortanGrade;
private float adaGrade;
/**
* Default constructor
*/
public ComputerStudent() {
super();
fortanGrade = 4;
adaGrade = 9;
}
public ComputerStudent(float fortanGrade, float adaGrade) {
this.fortanGrade = fortanGrade;
this.adaGrade = adaGrade;
}
// Getters
public void setFortanGrade(float fortanGrade){
this.fortanGrade = fortanGrade;
}
public void setAdaGrade(float adaGrade){
this.adaGrade = adaGrade;
}
// Setters
public float getFortanGrade() {
return this.fortanGrade;
}
public float getAdaGrade() {
return this.adaGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Fortan Grade: " + fortanGrade + " Ada Grade: " + adaGrade);
}
}
How Would I go about this?
You can ask for the number of students with type on each input and dynamically create the object.
Here is an example
System.out.println("Enter total number of students");
int n = scannerObject.nextInt();
Student students[] = new Students[n];
for(int i=0;i<n;i++){
int type = scannerObject.nextInt();
if(type == 1)
students[i] = new MathStudent();
}
Similarly, you can write for others.
For allowing user to enter his choice as input
You can do this(interpreted by your comments)
Pseudo code -
Print:
Enter 1 for math student
Enter 2 for Science student
Enter 3 for Comp student
Input choice
Now in your code use either multiple if else or better switch statement
switch(choice){
case 1: create object of math student
break;
case 2: create object of science student
break;
case 3:create object of comp student
break;
default: if not above by default do this
}
You could use an ArrayList and switch case to make your life easier. Your code should be like this:
import java.util.ArrayList;
import java.util.Scanner;
public class Students {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
int age;
boolean addMore = true;
String name, gender;
Student st;
while (addMore) {
System.out.print("Give lesson (Computers, Math, Science): ");
String lesson = input.nextLine();
switch (lesson) {
case "Math":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Algebra grade: ");
int alg = input.nextInt();
System.out.print("Give student's Calculus grade: ");
int calc = input.nextInt();
input.nextLine(); // This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new MathStudent(alg, calc);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((MathStudent) st).getSubjects());
break;
case "Science":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Physics grade: ");
int physics = input.nextInt();
System.out.print("Give student's Astronomy grade: ");
int astronomy = input.nextInt();
input.nextLine();// This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new ScienceStudent(physics, astronomy);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((ScienceStudent) st).getSubjects());
break;
case "Computers":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Fortran grade: ");
int fortran = input.nextInt();
System.out.print("Give student's Ada grade: ");
int ada = input.nextInt();
input.nextLine();// This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new ComputerStudent(fortran, ada);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((ComputerStudent) st).getSubjects());
break;
default:
System.out.println("Wrong lesson");
addMore = false;
break;
}
if (addMore) {
System.out.println("Add another student? (y/n)");
String ans = input.nextLine();
addMore = ans.equals("y");
} else {
addMore = true;
}
}
System.out.println("Students");
for (Student student : students) {
System.out.println(student);
}
}
}
The code above asks for the lesson name (Computers, Math, Science) and if it is one of them it reads all the info about the student and the grades for the corresponding lesson. It creates the objects and adds them in the list students. When all info is added, it asks the user if he/she wants to add another student and if he writes the letter y, then all these are made again, until the user answers something different than the letter y (the letter n in most cases). After these it prints all the students' info by itterating the list.
Note: I think in your code for the ComputerStudent class, you meant to name the variable fortranGrade and not fortanGrade (change it also in the getSubjects function).
Links:
Java ArrayList
Switch Case in Java
Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
I hope this helped you. If you have any questions or wanted something more you can do it.
UPDATE
The code below does the same things, but it uses for loop instead of switch case, as you asked in your comment.
package students;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Lab4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
int age;
boolean addMore = true;
String name, gender;
Student st;
ArrayList<Class<?>> studentClasses = new ArrayList<>();
studentClasses.add(MathStudent.class);
studentClasses.add(ComputerStudent.class);
studentClasses.add(ScienceStudent.class);
while (addMore) {
System.out.print("Give lesson (Computers, Math, Science): ");
String lesson = input.nextLine();
addMore = false;
for (Class studentClass : studentClasses) {
try {
st = (Student) studentClass.newInstance();
if (st.getLessonName().equals(lesson)) {
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's " + st.getSubjectsNames()[0] + " grade: ");
float firstSubj = input.nextFloat();
System.out.print("Give student's " + st.getSubjectsNames()[1] + " grade: ");
float secondSubj = input.nextFloat();
input.nextLine(); // This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = (Student) studentClass.getConstructor(float.class, float.class).newInstance(firstSubj, secondSubj);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(st.getSubjects());
addMore = true;
break;
}
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(Lab4.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (addMore) {
System.out.println("Add another student? (y/n)");
String ans = input.nextLine();
addMore = ans.equals("y");
} else {
System.out.println("Wrong lesson. Try again.");
addMore = true;
}
}
System.out.println("Students");
for (Student student : students) {
System.out.println(student);
}
}
}
You also need to add the functions in the classes as mentioned bellow:
Student class:
public String getLessonName(){
return "";
}
public String[] getSubjectsNames(){
return new String[] {"", ""};
}
MathStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Algebra", "Calculus"};
}
#Override
public String getLessonName(){
return "Math";
}
ComputerStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Fortran", "Ada"};
}
#Override
public String getLessonName(){
return "Computers";
}
ScienceStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Physics", "Astronomy"};
}
#Override
public String getLessonName(){
return "Science";
}
Changes: The code firstly creates an arraylist with the student classes (studdentClasses) and adds all the classes for the students that are currently in the project (MathStudent, ComputerStudent, ScienceStudent). Then the user adds the lesson's name. Then (instead of the switch case) there is a for loop which itterates through the studdentClasses list and checks if the lesson's name that the user has written is the same with a student's class by using the getLessonName function. After that all the info for the student are asked and the grades for the subjects, and for the question (Give student's Physics grades) it uses the function getSubjectsNames. All the other things are like before.
You have a main class, that's what you need essentially, but you need to read from command line. Great, run from command line. Once you run, pay attention to what you did, you can pass parameters there as well. once you pass parameters, they go in line. This line is logically splitable, so split it within you code. for instance by pair of numbers after some key word like science and until next keyword and put again from java and ask a new question once you there.

Printing arrays by age

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.

Display input from user, using toString() Method

I'm trying to finish this homework:
Create a simple Friendsclass with, as a minimum, the following:
name and age fields
appropriate constructors
get/set methods
toString() method
Create an ArrayList of Friends
Run the program from a menu with the following options:
Add a Friend
Remove a Friend
Display all Friends
Exit
And this is what I got so far:
Friends.class
public class Friends
{
public static String name;
public static int age;
// parameters
public Friends(String name, int age)
{
this.name = name;
this.age = age;
}
// set name
public static void setName(String friendName)
{
name = friendName;
}
// get name
public static String getName()
{
return name;
}
// set age
public static void setAge(int friendAge)
{
age = friendAge;
}
// get age
public static int getAge()
{
return age;
}
// return toString()
public String toString()
{
return this.getName() + " " + this.getAge();
}
} //end clas
And FriendsTest.class:
import java.util.Scanner;
import java.util.ArrayList;
public class FriendsTest
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
// objects
ArrayList<Friends> friendsList = new ArrayList<>();
Friends a1 = new Friends("James", 10);
Friends a2 = new Friends("Christopher", 17);
Friends a3 = new Friends("George", 25);
Friends a4 = new Friends("Linda", 31);
Friends a5 = new Friends("Karen", 62);
friendsList.add(a1);
friendsList.add(a2);
friendsList.add(a3);
friendsList.add(a4);
friendsList.add(a5);
// menu
int menu_choice;
do
{
System.out.println("\n1. Add a Friend");
System.out.println("2. Remove a Friend");
System.out.println("3. Display all Friends");
System.out.println("4. Exit");
System.out.print("\nSelect one option: ");
menu_choice = input.nextInt();
switch (menu_choice)
{
case 1:
System.out.print("Enter Friend's name: ");
Friends.setName(input.next());
System.out.print("Enter Friend's age: ");
Friends.setAge(input.nextInt());
Friends a6 = new Friends(Friends.getName(), Friends.getAge());
friendsList.add(a6);
break;
case 2:
System.out.println("Enter Friend's name to remove: ");
Friends.setName(input.next());
friendsList.remove(Friends.getName());
break;
case 3:
for(int k = 0; k < friendsList.size(); k++)
{
System.out.println(friendsList.get(k).name + " " + friendsList.get(k).age);
}
break;
case 4:
System.exit(0);
}//end switch
} while (menu_choice != 4);
}//end main
}//end class
When I run the program, neither Option 1, 2 and 3 seems to work:
With (1) I get the user input 5 times...
With (2) I get the the input 5 times too
If I select display(3) I get: "Karen 62" 5 times...
I'm not sure if I applying the loop correctly and if I'm using the setters and getters correctly.
I would like to recommend you to use an IDE (for example ECLIPSE[it's free]). An IDE is an integrated development environment, which is basically a text editor(like word or notepad) that would help you minimize errors (mostly syntax errors) in your code.
Things you should fix in your code:
In the Friends class you should erase all of the 'static' keywords. Plus, I would recommend you to use private instead of public all of the attributes of this class (that means in name and in age you should use private instead of public).
In the FriendsTest class:
case 1:
System.out.println("Enter Friend's name: ");
String name = input.next();
System.out.println("Enters Friend's age: ");
int age = input.next();
Friends a6 = new Friends(name,age);
friendsList.add(a6);
break;
case 2:
You need to learn how to use an iterator (look it up at java's API) if you are working with an ArrayList.
The remove(int index) method only lets you delete an object in a specified postion (that means you should know the postion of the friend you want to delete in the friendsList).
case 3:
You should use an iterator to iterate in the friendsList and use the toString method of the Friends class to print each friend.
You should not declare the Friends class's properties as static, neither its getters & setters :
Change
public static String name;
public static int age;
public static void setName(String friendName) ...
public static String getName() ...
public static void setAge(int friendAge) ...
public static int getAge() ...
to
public String name;
public int age;
public void setName(String friendName) ...
public String getName() ...
public void setAge(int friendAge) ...
public int getAge() ...
main() :
switch (menu_choice)
{
case 1:
String name;
int age;
System.out.print("Enter Friend's name: ");
name = input.next();
System.out.print("Enter Friend's age: ");
age = input.nextInt();
Friends a6 = new Friends(name, age);
friendsList.add(a6);
break;
. ...
Retrieve the name & age separatly, create a new Friends object with the corresponding name & age, the add it to the ArrayList. (Adjust this with the other cases accordingly)

reading more than one word from user

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

Categories

Resources