I having a problem to send a value on the variables. Why my variable cannot receive the value when I input a value? I've no idea to do...
import java.io.*;
public class StudentApp {
public static void main (String [] args) throws IOException {
student studentObject = new GradeResult();
studentObject.getName();
student studentObject2 = new GradeResult();
studentObject2.getIdNum();
student studentObject3 = new GradeResult();
studentObject3.getMark();
student studentObject4 = new GradeResult();
studentObject4.setName();
student studentObject5 = new GradeResult();
studentObject5.setIdNum();
student studentObject6 = new GradeResult();
studentObject6.setMark();
student studentObject7 = new GradeResult();
studentObject7.showGrade();
student studentObject8 = new GradeResult();
studentObject8.showResult();
}
interface StudentInterface{
void getName() throws IOException;
void getIdNum()throws IOException;
void setName();
void setIdNum();
void getMark()throws IOException;
void setMark();
}
interface student extends StudentInterface{
void showResult();
void showGrade();
}
class GradeResult implements student {
String name ,name2 ,name3;
int a ,mark;
public void getName () throws IOException {
InputStreamReader inStream = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(inStream);
System.out.print("Please Input Your Name :");
name = stdin.readLine();
}
public void getIdNum()throws IOException {
BufferedReader stdin=new BufferedReader (new InputStreamReader(System.in));
System.out.print("Please Input Your ID Number :");
name2 = stdin.readLine();
a = Integer.parseInt(name2);
}
public void setName() {
System.out.print("Your Name :"+name);
}
public void setIdNum() {
System.out.print("\nYour ID Number :"+name2);
}
public void getMark()throws IOException {
BufferedReader stdin=new BufferedReader (new InputStreamReader(System.in));
System.out.print("Please Input Your Mark :");
name3 = stdin.readLine();
mark = Integer.parseInt(name3);
}
public void setMark() {
System.out.print("\nYour Mark :"+mark);
}
public void showResult() {
if ((mark>=40)&&(mark<=100)) {
System.out.print("\nYou Are PASS");
} else {
System.out.print("\nYou Are FAIL");
}
}
public void showGrade() {
if((mark>=80)&&(mark<=100)) {
System.out.print("\nYour Grade Is A");
} else if ((mark>=65)&&(mark<=80)) {
System.out.print("\nYour Grade Is B");
} else if ((mark>=50)&&(mark<=65)) {
System.out.print("\nYour Grade Is C");
} else if ((mark>=40)&&(mark<=50)) {
System.out.print("\nYour Grade Is D");
} else {
System.out.print("\nYour Grade Is E");
}
}
}
I'm not sure which one is my mistake. Should I need to use object reference to receive the value or just call as usual on main method.
Best working solution is to do the following in your GradeResult class
private static String name, name2, name3;
private static int a, mark;
This will work..!
The output:
Please Input Your Name :Mohammad
Please Input Your ID Number :10001
Please Input Your Mark :85
Your Name :Mohammad
Your ID Number :10001
Your Mark :85
Your Grade Is A
You Are PASS
You are creating new objects everytime, therefore your results get put in different objects.
Try this:
student studentObject = new GradeResult();
studentObject.getName();
studentObject.setName();
EDIT: In case you didn't know it, instance variables values are held within an object. So all your different objects (of the same class) will have different name, name2, name3, etc. The objects from which you call the System.out.println(...) methods have uninitialized instance variables (name, name2, name3) and hence will not print any values for those.
create object set value for that object and access value from same object. In your case you are setting value to some object and accessing data from other object that is why you are getting null for some fields.
public static void main (String [] args) throws IOException{
student studentObject = new GradeResult();
studentObject.getName();
studentObject.getIdNum();
studentObject.getMark();
studentObject.setName();
studentObject.setIdNum();
studentObject.showGrade();
studentObject.showResult();
}
Related
I am new to programming and at the moment I am doing a task, the essence of which is the emulation of scanning a person by gender and age with a further pass to a zone defined for its parameters. I was told to supplement the program so that, for example, when you press the S button on the keyboard, the program ends.
Please tell me how can I implement this. I have 4 classes in my code:
main
public class Main {
public static void main(String[] args) {
PassportScan passportScan = new PassportScan();
Guard guard = new Guard();
while (true) {
Person person = passportScan.methodScan();
String result = guard.checkPerson(person);
System.out.println(result);
}
}
}
PassportScan
import java.util.Scanner;
public class PassportScan {
Scanner scanner = new Scanner(System.in);
public Person methodScan() {
System.out.println("Scanning gender");
String gender = scanner.next();
System.out.println("Scanning age");
int age = scanner.nextInt();
return new Person(gender, age);
}
}
Person
public class Person {
private String gender;
private Integer age;
public Person(String gender, Integer age) {
this.gender = gender;
this.age = age;
}
public String getGender() {
return gender;
}
public Integer getAge() {
return age;
}
}
Guard
public class Guard {
public String checkPerson(Person personToCheck) {
String gender = personToCheck.getGender();
int age = personToCheck.getAge();
if (age < 18 && gender.equals("M")) {
return "Zone 1";
}
if (age >= 18 && gender.equals("M")) {
return "Zone 2";
}
if (age < 18 && gender.equals("F")) {
return "Zone 3";
}
if (age >= 18 && gender.equals("F")) {
return "Zone 4";
}
return "";
}
}
Thanks in advance for the tip and your time!
Basically there will be two scenario for this.
1. Once Press S >>> You want to terminate the program
Simply its not available in normal console
but there is way to achieve refer this post for more info https://stackoverflow.com/a/1066647/8524713
2. Press S and then press Enter key >>
In this case its easy
check on each gender input if its S break the loop
try below code for reference
public static void main(String[] args) {
PassportScan passportScan = new PassportScan();
Guard guard = new Guard();
while (true) {
Person person = passportScan.methodScan();
//checking if person object is null if ts null means s is enter
// break from loop
if(person==null) {
break;
}
String result = guard.checkPerson(person);
System.out.println(result);
}
}
static class PassportScan {
Scanner scanner = new Scanner(System.in);
public Person methodScan() {
System.out.println("Scanning gender");
String gender = scanner.next();
//check if string input is S or s
// then its returning null person object
if(gender.equalsIgnoreCase("s")) return null;
System.out.println("Scanning age");
int age = scanner.nextInt();
return new Person(gender, age);
}
}
one more way is to directly terminate in PassportScan class once S is typed
class PassportScan {
Scanner scanner = new Scanner(System.in);
public Person methodScan() {
System.out.println("Scanning gender");
String gender = scanner.next();
//check if string input is S or s terminating prog
if(gender.equalsIgnoreCase("s")) System.exit(0)
System.out.println("Scanning age");
int age = scanner.nextInt();
return new Person(gender, age);
}
}
You probably have some Component in that you display something, for example a (class that extends) JFrame, lets call it c.
Now call:
c.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if (Character.toLowerCase(e.getKeyChar()) == 's') System.exit(0);
}
#Override
public void keyReleased(KeyEvent e) {
}
});
It is not possible to catch a KeyEvent without a GUI (When you think about it, how should Java know that the key was pressed in your application? If it would catch any KeyEvent on the device, you could easily build spyware that catches passwords or sth.)
I have two methods 1st method has a object as a return type and 2nd method has integer as a return type.
I have some values in 1st method and some values in 2nd method
All i want to do is pass all these values to a single object.
But the problem is only values of 1st method is passing and the values from second method is not passing.I am practicing Encapsulation
Below is the code of two files and OUTPUT.
//Employee.java file
import java.util.*;
class Employee
{
private int employeeId;
private String employeeName;
private double salary;
private double netSalary;
/*public Employee()
{
}*/
public void setEmployeeId(int a)
{
employeeId = a;
}
public void setEmployeeName(String b)
{
employeeName = b;
}
public void setSalary(double c)
{
salary=c;
}
public int getEmployeeId()
{
return employeeId;
}
public String getEmployeeName()
{
return employeeName;
}
public double getSalary()
{
return salary;
}
public void calculateNetSalary(int pfpercentage)
{
netSalary = salary-((salary*pfpercentage)/100);
}
public double getNetSalary()
{
return netSalary;
}
}
import java.util.*;
class Main
{
public static Employee getEmployeeDetails(Employee e)//1st Method
{
Scanner sc=new Scanner (System.in);
try
{
System.out.println("Enter Id:");
e.setEmployeeId(sc.nextInt());
sc.nextLine();
System.out.println("Enter Name:");
e.setEmployeeName(sc.nextLine());
System.out.println("Enter salary:");
e.setSalary(sc.nextDouble());
sc.nextLine();
}catch(Exception e1){System.out.println("Invalid Input");}
return e;
}
public static int getPFPercentage()//2nd Method
{
Employee e = new Employee();
int pf=0;
Scanner sc1=new Scanner(System.in);
try
{
System.out.println("Enter PF percentage:");
pf=sc1.nextInt();
e.calculateNetSalary(pf);
}catch(Exception e1){System.out.println("Invalid Input");}
return pf;
}
public static void main(String args[])
{
Employee e = new Employee();
getEmployeeDetails(e);
getPFPercentage();
System.out.println();
System.out.println("Id : "+e.getEmployeeId());
System.out.println("Name : "+e.getEmployeeName());
System.out.println("Salary : "+e.getSalary());
System.out.println("Net Salary : "+e.getNetSalary());
}
}
OUTPUT
Enter Id:
101
Enter Name:
Harry
Enter salary:
20000
-------------1st method is used to take above input
Enter PF percentage:
7
-------------2nd method is used to take only PF percentage input
Id : 101
Name : Harry
Salary : 20000.0
Net Salary : 0.0
Calculation of Net salary is in file Employee.java function name "calculateNetSalary"
You have not calculated netSalary before calling method getNetSalary();
public void calculateNetSalary(int pfpercentage) //This function should be called first.
{
netSalary = salary-((salary*pfpercentage)/100);
}
public double getNetSalary()
{
return netSalary;
}
Look below code for better understanding:
System.out.println("Salary : "+e.getSalary());
e.calculateNetSalary(5); //Add this line and you will get the required output.
System.out.println("Net Salary : "+e.getNetSalary());
The problem is inside getPFPercentage() method you are creating a new Employee object. You should use the same object created in the main method.
public static int getPFPercentage(Employee e)//2nd Method
{
int pf=0;
Scanner sc1=new Scanner(System.in);
try
{
System.out.println("Enter PF percentage:");
pf=sc1.nextInt();
e.calculateNetSalary(pf);
}catch(Exception e1){System.out.println("Invalid Input");}
return pf;
}
public static void main(String args[])
{
Employee e = new Employee();
getEmployeeDetails(e);
getPFPercentage(e);
System.out.println();
System.out.println("Id : "+e.getEmployeeId());
System.out.println("Name : "+e.getEmployeeName());
System.out.println("Salary : "+e.getSalary());
System.out.println("Net Salary : "+e.getNetSalary());
}
In the 'getPFPercentage' method you are creating a new object but in the main method you are using a different object.
Pass the object that you have created in the main method to the getPFPercentage method
Change you getPFPercentage signature to
'public static int getPFPercentage(Employee e)'
Remove the object creation line in the getPFPercentage method
and call this method from the main method
- getPFPercentage(e)
hello I have written code where it takes book details using setter method and displaying details using getter method. When user enters the input it has to enter three details.
Book NameBook PriceAuthor Name
I want to check if user has given any negative value or Zero value in Book Price.
How do I do that? Below is the code. I am practicing Encapsulation problem
//Book.java file
class Book
{
private String bookName;
private int bookPrice;
private String authorName;
public String getBookName()
{
return bookName;
}
public int getBookPrice()
{
return bookPrice;
}
public String getAuthorName()
{
return authorName;
}
public void setBookName(String a)
{
bookName=a;
}
public void setBookPrice(int b)
{
bookPrice=b;
}
public void setAuthorName(String c)
{
authorName=c;
}
}
//TestBook.java file
import java.util.*;
class TestBook
{
public static void main(String args[])
{
Book bobj = new Book();
Scanner sc = new Scanner(System.in);
try
{
System.out.println("Enter the Book name:");
bobj.setBookName(sc.nextLine());
System.out.println("Enter the price:");
bobj.setBookPrice(sc.nextInt());
sc.nextLine();
System.out.println("Enter the Author name:");
bobj.setAuthorName(sc.nextLine());
System.out.println();
System.out.println("Book Details");
System.out.println("Book Name :"+bobj.getBookName());
System.out.println("Book Price :"+bobj.getBookPrice());//should not be -ve or 0
System.out.println("Author Name :"+bobj.getAuthorName());
}
catch(Exception e)
{
System.out.println("Invalid Input");
}
}
}
You should put this check in your setter method to check if it is greater than zero. For example:
public void setBookPrice(int b)
{
if(b>0)
bookPrice=b;
else
{
throw new IllegalArgumentException("b must be positive")
}
}
Above code will prevent setting of negative and zero price. You can replace exception throwing code with your own handling.
If you are practising encapsulation I suggest creating a specific validation method for the price so this can be easily modified without changing the public interface.
public boolean isValidPrice() {
return bookPrice > 0;
}
This can now be checked with
if (!bobj.isValidPrice()) {
//error handling
}
And if the validation rules for price would change the calling code will remain unchaged
public static void main(String[] args) {
System.out.println("Hello and welcome! Please enter the following: ");
String q = null, s = "nul";
userName(q);
userGender(s);
print(userName(q));
print(userGender(s)); // how to achieve something like this?
}
public static void userName(String x) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter name: ");
String n = sc.nextLine();
}
public static void userGender(String y) {
Scanner sd = new Scanner(System.in);
System.out.print("Enter Gender: ");
String v = sd.next().toString();
}
public static void print(String a) {
System.out.println(a);
}
So I was trying to make it so that a method would be used to print another method after they were done executing but I couldn't get the desired result and it gave an error.
The method print works fine, it takes a String and return nothing
public static void print(String a)
{
System.out.println(a);
}
However, your method userGender and userName returns nothing, so when you are feeding print with a method that isn't returning a string, it will produce an compile-time error. You want to do something similar to:
public static String userGender(String y){
Scanner sd = new Scanner(System.in);
System.out.print("Enter Gender: ");
return sd.next().toString();
}
I haven't tested it, as your logic is unclear to me, but this is probably why your IDE is complaining.
Your method needs to return something. You are declaring your method like this: public static void userGender(String y) the void means that your method won't return anything. But since you want that the method returns a String you need to tell this in the method signature.
Your code could look like this:
public static void main(String[] args) {
System.out.println("Hello and welcome! Please enter the following: ");
print(userName());
print(userGender());
}
public static String userName() {
try(Scanner sc = new Scanner(System.in)){ // this is try resource see which will close your resource once you are done in the try block see https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
System.out.print("Enter name: ");
return sc.next();
}
}
public static String userGender() {
try(Scanner sc = new Scanner(System.in)) {
System.out.print("Enter Gender: ");
return sc.next();
}
}
public static void print(String a) {
System.out.println(a);
}
You don't need to use toString() since the next returns already a String. Also you can use the same variable name in different methods. And really important you need to close the Scanner again, otherwise it will consume endless resources.
Like #reebow and #Kerry Gougeon both pointed out that your method is looking to return something so you make it public static String userName() or public static String userName(String s).
If you're wanting to user Scanner then you're going to have to declare Scanner globally, otherwise it will throw a NoSuchElementExcpetion
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Hello and welcome! Please enter the following: ");
print(userName());
print(userGender());
}
public static String userName() {
System.out.print("Enter name: ");
return sc.next();
}
public static String userGender() {
System.out.print("Enter Gender: ");
return sc.next();
}
public static void print(String a) {
System.out.println(a);
}
If you're not using Scanner then you can just return the String that you passed to the method.
public static void main(String[] args) {
System.out.println("Hello and welcome! Please enter the following: ");
String a = null, b ="nul";
print(userName(a));
print(userGender(b));
}
public static String userName(String a) {
System.out.print("Enter name: ");
return a;
}
public static String userGender(String b) {
System.out.print("Enter Gender: ");
return b;
}
public static void print(String a) {
System.out.println(a);
}
I am compiling all my java program in cmd but when I run below program, it's showing an error like "reached end of file while parsing" ! And when I try to run it in eclipse it's showing red underline below bold code that is methods and main methods.
import java.io.*;
class empl{
int empno;
String name;
String position;
int ph;
public void getdata()throws IOException{
DataInputStream e = new DataInputStream(System.in);
System.out.println("Enter name: ");
empno = Integer.parseInt(e.readLine());
System.out.println("Enter your name: ");
name = e.readLine();
System.out.println("Enter the employee position: ");
position=e.readLine();
System.out.println("Enter the phone number: ");
ph = Integer.parseInt(e.readLine());
}
public void displaydata() {
System.out.println(empno+"\t"+name+"\t"+position+"\t"+ph);
}
class manager extends empl{
int salary;
String secname;
public void getdata() throws IOException{
getdata();
DataInputStream e= new DataInputStream(System.in);
System.out.println("Enter salary: ");
salary=Integer.parseInt(e.readLine());
System.out.println("Enter second name: ");
secname= e.readLine();
}
public void displaydata(){
displaydata();
System.out.println(salary+"\t"+secname);
}
class inheritt{
public static void **main(String []args)throws IOException**{
inheritt e1= new inheritt();
inheritt e2= new inheritt();
**e1.getdata();
e2.getdata();
e1.displaydata();
e2.displaydata();**
}
Only top level classes can have static methods: Declare inheritt as a top level class rather than an inner class
public class inheritt {
public static void main(String[] args) throws IOException {
...
}
}
**e1.getdata();
e2.getdata();
e1.displaydata();
e2.displaydata();**
e1 and e2 are of inheritt type and don't have the getdata() and displaydata() methods
Try this code... I think this may be what you want. I fixed some of the brackets, not really sure of what goes where. I also, made inheritt extends manager. I think that's what you want. You may be wanting to show the inheritance chain of the classes.
import java.io.*;
class empl{
int empno;
String name;
String position;
int ph;
public void getdata()throws IOException{
DataInputStream e = new DataInputStream(System.in);
System.out.println("Enter name: ");
empno = Integer.parseInt(e.readLine());
System.out.println("Enter your name: ");
name = e.readLine();
System.out.println("Enter the employee position: ");
position=e.readLine();
System.out.println("Enter the phone number: ");
ph = Integer.parseInt(e.readLine());
}
public void displaydata() {
System.out.println(empno+"\t"+name+"\t"+position+"\t"+ph);
}
}
class manager extends empl{
int salary;
String secname;
public void getdata() throws IOException{
getdata();
DataInputStream e= new DataInputStream(System.in);
System.out.println("Enter salary: ");
salary=Integer.parseInt(e.readLine());
System.out.println("Enter second name: ");
secname= e.readLine();
}
public void displaydata(){
super.displaydata();
System.out.println(salary+"\t"+secname);
}
class inheritt extends manager {
public static void **main(String []args)throws IOException**{
inheritt e1= new inheritt();
inheritt e2= new inheritt();
e1.getdata();
e2.getdata();
e1.displaydata();
e2.displaydata();
}