why java method return same result? - java

i have problem with my program << this program take information for 3 student name and id and marks in 5 course then return information with marks avrage my program is work good but it return same avrage for all student its same number please can u help me
this is the class
StudentsMarks.java
package programmersx;
import java.io.BufferedWriter;
import java.io.*;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
public class StudentsMarks {
private String studentName;
private int studentId;
private double marks[];
public static int NoInstntitd;
public StudentsMarks() {
NoInstntitd += 1;
}
double avgCalculator(double[] marks) { //avg method
double sum =0;
double avg=0;
for (int i = 0; i < marks.length; i++) {
sum = sum + marks[i];
avg=sum/5;
}
return avg;
}
#Override
public String toString() {
return studentName +" " + studentId +" " + Arrays.toString(marks) +" " ;
}
void toFile(String fileName) throws IOException {
FileOutputStream file= new FileOutputStream(fileName);
PrintWriter writer= new PrintWriter(file);
writer.print("reem ");
String information = "student information :" + getStudentName() + "" + getStudentId() + " average " + avgCalculator(marks);
LocalDate localDate = LocalDate.now();
BufferedWriter writer1 = new BufferedWriter(new FileWriter("average.txt"));
BufferedWriter writer2 = new BufferedWriter(new FileWriter("localDate.txt"));
try {
writer.write(information);
writer1.write(" average " + avgCalculator(marks));
writer2.write(DateTimeFormatter.ofPattern("yyy/MM/dd").format(localDate));
writer2.close();
} catch (IOException ex) {
Logger.getLogger(Programmersx.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("student information :" + getStudentName() + "" + getStudentId() + " average " + avgCalculator(marks));
System.out.println(" student average. : " + avgCalculator(marks));
System.out.println(DateTimeFormatter.ofPattern("yyy/MM/dd").format(localDate));
}
{
NoInstntitd += 1;
}
void display( ) {
System.out.println("display the count of the instantiated objects from StudentMarks" + getNoInstntitd());
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public double[] getMarks() {
return marks;
}
public void setMarks(double[] marks) {
this.marks = marks;
}
public int getNoInstntitd() {
return NoInstntitd;
}
public void setNoInstntitd(int NoInstntitd) {
this.NoInstntitd = this.NoInstntitd + 1;
}
}
this is main
Programmersx.java
package programmersx;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Programmersx {
public static void main(String[] args) throws IOException {
StudentsMarks myObject = new StudentsMarks();
StudentsMarks myObject1 = new StudentsMarks();
StudentsMarks myObject2 = new StudentsMarks();
System.out.print("Please enter your student Name : ");
Scanner myObj = new Scanner(System.in); // Create a Scanner object
myObject.setStudentName(myObj.next()) ;
System.out.print("Please enter your student Id : ");
myObject.setStudentId(myObj.nextInt()) ;
System.out.println("Please enter your marks of 5 courses : ");
double marks[] = new double [5];
for (int i = 0; i < 5; i++) {
marks[i]= myObj.nextInt();
}
myObject.setMarks(marks) ;
System.out.print("Please enter your student Name : ");
Scanner myObj1 = new Scanner(System.in); // Create a Scanner object
myObject1.setStudentName(myObj1.next()) ;
System.out.print("Please enter your student Id : ");
myObject1.setStudentId(myObj1.nextInt()) ;
System.out.println("Please enter your marks of 5 courses : ");
double marks1[] = new double [5];
for (int i = 0; i < 5; i++) {
marks1[i]= myObj1.nextInt();
}
myObject1.setMarks(marks) ;
myObject1.toString();
System.out.print("Please enter your student Name : ");
Scanner myObj2 = new Scanner(System.in); // Create a Scanner object
myObject2.setStudentName(myObj2.next()) ;
System.out.print("Please enter your student Id : ");
myObject2.setStudentId(myObj2.nextInt()) ;
System.out.println("Please enter your marks of 5 courses : ");
double marks2[] = new double [5];
for (int i = 0; i < 5; i++) {
marks2[i]= myObj2.nextInt();
}
myObject2.setMarks(marks) ;
myObject2.toString();
myObject.toString();
myObject.toFile("Reem.txt");
myObject1.toFile("MAria.txt");
myObject2.toFile("Abrar.txt");
System.out.println("display the count of the instantiated objects from StudentMarks: " + StudentsMarks.NoInstntitd );
}
}
the output is
run:
Please enter your student Name : jack
Please enter your student Id : 1123
Please enter your marks of 5 courses :
6
4
5
7
6
Please enter your student Name : mick
Please enter your student Id : 87534
Please enter your marks of 5 courses :
6
4
3
22
5
Please enter your student Name : meno
Please enter your student Id : 43433
Please enter your marks of 5 courses :
6
55
33
22
7
student information :jack1123 average 5.6
student average. : 5.6
2019/12/06
student information :mick87534 average 5.6
student average. : 5.6
2019/12/06
student information :meno43433 average 5.6
student average. : 5.6
2019/12/06
display the count of the instantiated objects from StudentMarks: 6

All of the StudentMarks objects have their marks set by a similar call:
myObject2.setMarks(marks)
They all use the same marks array, so they all have the same marks.
Even if you change the content of the marks array between
myObject.setMarks(marks)
and
myObject1.setMarks(marks)
there's still only one marks array, shared by all StudentMarks objects: the StudentMarks setter does not copy the array.

All student are setted the same marks
myObject.setMarks(marks)
myObject1.setMarks(marks)
myObject2.setMarks(marks)
You should change your code like this
myObject.setMarks(marks)
myObject1.setMarks(marks1)
myObject2.setMarks(marks2)

Related

how to change the string into char in bookCategory?

I have this code in Java,
package bookpurchased;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Book {
public static void getInputFromScanner() {
Scanner input = new Scanner(System.in);
System.out.print("Enter the Number you want: ");
Short bookId = input.nextShort();
System.out.println("\nBook Price : ");
double bookPrice = input.nextDouble();
System.out.println("The Book Category is: " + bookId);
System.out.println("The Book Price is: " + bookPrice);
input.close();
}
public static void getInputFromReader() {
BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) );
String bookTitle = "";
System.out.print("Enter book title");
here below it:
I want to change the bookCategory from String to char, but if I change, I have received a lots of error. It's like a string when in run but I have to change only a bookCategory from String to char.
String bookCategory = "";
System.out.print("Enter book title");
try {
bookTitle = dataIn.readLine();
bookCategory = dataIn.readLine();
}catch(IOException e) {
System.out.println("Error!");
}
System.out.println("The book title is: " + bookTitle);
System.out.println("The book category is: " + bookCategory);
}
public static void main(String[]args) {
getInputFromReader();
getInputFromScanner();
}
}
You can make of String.toCharArray() i.e., bookCategory.toCharArray() or dataIn.readLine().toCharArray() will give you char[] array.
But you have to intialize the bookCategory to char array or you can print directly the converted char[] array using Arrays.toString()

ERROR: unreported exception java.io.IOException; must be caught or declared to be thrown [duplicate]

This question already has an answer here:
What does "error: unreported exception <XXX>; must be caught or declared to be thrown" mean and how do I fix it?
(1 answer)
Closed 8 months ago.
i am almost through with this assignment but i keep getting the error
"unreported exception java.io.IOException; must be caught or declared to be thrown" Am i writing my code out of order or am i missing a chunk of code? Thanks for your time!
import java.io.*;
import java.util.*;
import java.text.*;
public class database1 {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
String empnumber;
String firstname;
String lastname;
String city;
String state;
String zipcode;
String jobtitle;
int salary;
int max = 200000;
int counter = 0;
FileWriter ryyt = new FileWriter("c:\\EmployeeData.txt");
BufferedWriter out = new BufferedWriter(ryyt);
while (counter < 9) {
System.out.print("Enter the employee number ...... ");
empnumber = console.next();
System.out.print("Enter employee's first name .... ");
firstname = console.next();
//firstname = Character.toUpperCase(firstname.charAt(0)) +
firstname.substring(1);
System.out.print("Enter employee's last name ..... ");
lastname = console.next();
lastname = Character.toUpperCase(lastname.charAt(0))
+ lastname.substring(1);
System.out.print("Enter employee's city .......... ");
city = console.next();
city = Character.toUpperCase(city.charAt(0)) + city.substring(1);
System.out.print("Enter employee's state ......... ");
state = console.next();
String upperstate = state.toUpperCase();
System.out.print("Enter employee's zip code ...... ");
zipcode = console.next();
System.out.print("Enter employee's job title ..... ");
jobtitle = console.next();
jobtitle = Character.toUpperCase(jobtitle.charAt(0))
+ jobtitle.substring(1);
System.out.print("Enter employee's salary ........ ");
salary = console.nextInt();
while (salary > max) {
if (salary > max) {
System.out.println(
"Salary is over the maxium allowed, re-enter please ...");
System.out.print("Enter employee's salary ........ ");
salary = console.nextInt();
} else {
System.out.println("Thank you please enter the next employee!");
}
}
System.out.println();
out.write(empnumber + ",");
out.write(firstname + ",");
out.write(lastname + ",");
out.write(city + ",");
out.write(upperstate + ",");
out.write(zipcode + ",");
out.write(jobtitle + ",");
out.write(salary + ",");
out.newLine();
counter = counter + 1;
}
out.close();
}
}
You have to use throws IOException like this :
public static void main(String[] args) throws FileNotFoundException, IOException
Or you can surround your statement with try{}catch(...){} :
try {
//Your code ...
} catch (IOException ex) {
//exception
}

Error in reading Input from DataInputStream in java

Firstly I have made a folder named juet and then I have made two packages inside that folder. First one is Student package which takes care of all the students in university
package juet.stud;
import java.io.IOException;
import java.io.DataInputStream;
public class Student {
String name;
public int roll_no;
int std;
char grade;
public Student() {
try (DataInputStream in = new DataInputStream(System.in)) {
System.out.println("Enter name of student:");
name = in.readUTF();
System.out.println("Enter roll no.:");
roll_no = in.readInt();
System.out.println("Enter std:");
std = in.readInt();
System.out.println("Enter grade");
grade = in.readChar();
} catch (IOException e) {
System.err.println(e);
}
}
public void showInfo() {
System.out.println("Name of student: " + name);
System.out.println("Roll no.: " + roll_no);
System.out.println("Std: " + std);
System.out.println("Grade: " + grade);
}
}
Another package which I have made is Staff which takes care of all staff in the university
package juet.staff;
import java.io.IOException;
import java.io.DataInputStream;
public class Staff {
public int id;
String name, specialization;
char group;
public Staff() {
try (DataInputStream in = new DataInputStream(System.in)) {
System.out.println("Enter id:");
id = in.readInt();
System.out.println("Enter name:");
name = in.readUTF();
System.out.println("Enter area of specialization:");
specialization = in.readUTF();
System.out.println("Enter group");
group = in.readChar();
} catch (IOException e) {
System.err.println(e);
}
}
public void showInfo() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Area of specialization: " + specialization);
System.out.println("Group: " + group);
}
}
And then at the last I have made MyUniversity Class in which I was using both the packages
package juet;
import juet.stud.Student;
import juet.staff.Staff;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.Console;
class University {
Student[] stu;
Staff stf[];
int studCount, staffCount;
University() {
try (DataInputStream in = new DataInputStream(System.in)) {
System.out.println("Enter capacity for students:");
int x = Integer.parseInt(in.readLine());
//stu = new Student[x];
System.out.println("Enter capacity for staff:");
x = Integer.parseInt(in.readLine());
stf = new Staff[x];
studCount = staffCount = 0;
} catch (IOException e) {
System.err.println(e);
}
}
void newStudent() {
stu[studCount] = new Student();
studCount++;
}
void studInfo(int roll
) {
int i;
for (i = 0; i < studCount; i++) {
if (stu[i].roll_no == roll) {
stu[i].showInfo();
return;
}
}
System.out.println("No match found.");
}
void newStaff() {
stf[staffCount] = new Staff();
staffCount++;
}
void staffInfo(int id
) {
int i;
for (i = 0; i < staffCount; i++) {
if (stf[i].id == id) {
stf[i].showInfo();
return;
}
}
System.out.println("No match found.");
}
}
class MyUniversity {
public static void main(String args[]) throws IOException {
University juet = new University();
int ch;
DataInputStream in = new DataInputStream(System.in);
while (true) {
System.out.println("\tMAIN MENU\n");
System.out.println("1. Add student\n2. Add staff member\n3. Display info about specific student\n4. Display info about specific staff member\n0. Exit\n\tEnter your choice");
try {
ch = Integer.parseInt(in.readLine());
switch (ch) {
case 1:
juet.newStudent();
break;
case 2:
juet.newStaff();
break;
case 3:
System.out.println("Enter roll no. of student to display info:");
int roll = in.readInt();
juet.studInfo(roll);
break;
case 4:
System.out.println("Enter ID of staff member to display info:");
int id = in.readInt();
juet.staffInfo(id);
break;
case 0:
return;
default:
System.out.println("Incorrect choice.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Problem is arising when I am calling University object in the main class it is asking for two inputs
1).Enter capacity for students
so I enter 3
and again it ask for
2)Enter capacity for staff
But when I enter the integer there it is running infinite times
and showing error
java.io.Exception:Stream closed
at
java.io.BufferedInputStream.getBufIfopen(BufferedInputStream.java:170)
atjuet.MyUniversity.main(MyUniversity.java:76)
at java.io.DataInputStream.readLine(DataInputStream.java:513)
Please help me Thanks in advance
You are using the wrong class. DataInputStream and the methods readUTF() and readInt() can not be used for reading text from the console. It is designed to read binary content encoded by a different Java program using DataOutputStream.
The following question and answers show you how to do it right:
How can I read input from the console using the Scanner class in Java?

End of File Error in File Handling Program

I am creating a database project in java using file handling. The program is working without compiling error. Following points are not working
File is storing only first record. (if program is running again it is overwriting file)
I want to display all records but the only first record is displaying with Exeception
Please offer suggestions..
import java.io.*;
public class Student implements Serializable
{
private int roll;
private String name; //To store name of Student
private int[] marks = new int[5]; //To store marks in 5 Subjects
private double percentage; //To store percentage
private char grade; //To store grade
public Student()
{
roll = 0;
name = "";
for(int i = 0 ; i < 5 ; i++)
marks[i] = 0;
percentage = 0;
grade = ' ';
}
public Student(int roll , String name ,int[] marks)
{
setData(roll,name,marks);
}
public void setData(int roll , String name ,int[] marks)
{
this.roll = roll;
this.name = name;
for(int i = 0 ; i < 5 ; i++)
this.marks[i] = marks[i];
cal();
}
//Function to calculate Percentage and Grade
private void cal()
{
int sum = 0;
for(int i = 0 ; i < 5 ;i++)
sum = sum + marks[i];
percentage = sum/5;
if(percentage>85)
grade = 'A';
else if(percentage > 70)
grade = 'B';
else if (percentage >55)
grade = 'C';
else if (percentage > 33)
grade = 'E';
else
grade = 'F';
}
public char getGrade() { return grade; }
public double getPercentage() { return percentage; }
#Override
public String toString()
{
string format = "Roll Number : %4d, Name : -%15s "
+ "Percentage : %4.1f Grade : %3s";
return String.format(format, roll, name, percentage, grade);
}
}
second file
import java.io.*;
public class FileOperation
{
public static void writeRecord(ObjectOutputStream outFile, Student temp)
throws IOException, ClassNotFoundException
{
outFile.writeObject(temp);
outFile.flush();
}
public static void showAllRecords(ObjectInputStream inFile)
throws IOException, ClassNotFoundException
{
Student temp = new Student();
while(inFile.readObject() != null)
{
temp = (Student)inFile.readObject();
System.out.println(temp);
}
}
}
main file
(only two options are working)
import java.util.*;
import java.io.*;
public class Project
{
static public void main(String[] args)
throws IOException,ClassNotFoundException
{
ObjectInputStream inFile;
ObjectOutputStream outFile;
outFile = new ObjectOutputStream(new FileOutputStream("info.dat"));
inFile = new ObjectInputStream(new FileInputStream("info.dat"));
Scanner var = new Scanner(System.in) ;
int roll;
String name;
int[] marks = new int[5];
int chc = 0;
Student s = new Student();
while(chc != 6)
{
System.out.print("\t\tMENU\n\n");
System.out.print("1.Add New Record\n");
System.out.print("2.View All Records\n");
System.out.print("3.Search a Record (via Roll Number) \n");
System.out.print("4.Delete a Record (via Roll Number) \n");
System.out.print("5.Search a Record (via Record Number)\n");
System.out.print("6.Exit\n");
System.out.print("Enter your choice : ");
chc = var.nextInt();
switch(chc)
{
case 1:
System.out.print("\nEnter Roll number of Student : ");
roll = var.nextInt();
System.out.print("\nEnter Name of Student : ");
name = var.next();
System.out.println("\nEnter marks in 5 subjects \n");
for(int i = 0 ; i < 5 ; i++)
{
System.out.print("Enter marks in subject " + (i+1) + " ");
marks[i] = var.nextInt();
}
s.setData(roll , name , marks );
System.out.println("\n Adding Record to file \n");
System.out.printf("Record \n " + s);
System.out.println("\n\n");
FileOperation.writeRecord(outFile,s);
System.out.println("Record Added to File\n ");
break;
case 2:
System.out.println("All records in File \n");
FileOperation.showAllRecords(inFile);
break;
default: System.out.println("Wrong choice ");
}
}
outFile.close();
inFile.close();
}
}
Your program found a ClassNotFoundException and your method only throws an IOException.
I would check your import statements to make sure you are bringing in the class for ObjectInputStream
import java.io.ObjectInputStream;
If you want to get rid of unreported exception try:
Try
public static void showAllRecords(ObjectInputStream inFile) throws IOException, ClassNotFoundException

Print students in an array

I am trying to have the user type in the last name and first name of a student in an array so that I can call the student information and use it in a grade book.
The Student class has a method called Student(String last_name, String first_name)
I cannot figure out how to make it print students in a list such as:
last name, first name
last name, first name
Here is my program so far:
public static void main (String[] args)
{
System.out.println("--------------------------------");
System.out.println("Welcome to the Gradebook Program");
System.out.println("--------------------------------");
System.out.println();
students = GetNumberOfStudents();
//Allocate space for student information
Student student[] = new Student[students];
for (int i = 0; i < students; i++)
{
System.out.println("Student #" + (i+1));
System.out.print("\tEnter last name: ");
student[i] = scan.nextLine();
System.out.print("\tEnter first name: ");
student[i] = scan.nextLine();
}
System.out.println(student[i]);
I expect we would need to see the definition of Student, you have given the constructor but not the getters/setters.
I would expect the printing code to look something like
for (Student s : student) {
System.out.println(s.getLastName() + "," + s.getFirstName());
}
You are also not initialising your Student objects correctly.
Inside the loop you have written I would expect to see
new Student(lastname, firstname);
Here is a soltuion with a student class which looks like in your description.
package test; //change to your package name
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Student{
private String m_LastName;
private String m_FirstName;
private int[] TestScores = new int[3];
//Constructor
public Student(String last, String first) {
m_LastName = last;
m_FirstName = first;
}
//returns firstname
public String firstName() {
return m_FirstName;
}
//returns lastname
public String lastName() {
return m_LastName;
}
//set a test score at a given index
public void setTestScore(int index, int score) {
TestScores[index] = score;
}
//returns test score at a given index
public int testScore(int index) {
return TestScores[index];
}
//returns testscores average
public double testAverage() {
int sum = 0;
for(int i = 0; i<TestScores.length; i++) {
sum += TestScores[i];
}
return sum/TestScores.length;
}
//returns students highest test score
public int maxTestScore() {
//sort the array
for(int i = 0; i<TestScores.length; i++) {
for(int j = 0; j<TestScores.length; j++) {
if(TestScores[i]<TestScores[j]) {
int buffer;
buffer = TestScores[i];
TestScores[i] = TestScores[j];
TestScores[j] = buffer;
}
}
}
return TestScores[TestScores.length-1];
}
public boolean isPassing() {
//TODO: when hes passing?
return true;
}
public static void main (String[] args)
{
Scanner scan = new Scanner(new InputStreamReader(System.in));
System.out.println("--------------------------------");
System.out.println("Welcome to the Gradebook Program");
System.out.println("--------------------------------");
System.out.println();
/**
* dont know where you declare the students variable
* and how the getnumberofstudents function looks like
*
* students = GetNumberOfStudents();
*/
int students = 1;
List<Student> StudentList = new ArrayList<>(); //creat a list which can store student objects
for (int i = 0; i < students; i++)
{
System.out.println("Student #" + (i+1));
System.out.print("\tEnter last name: ");
String lastname = scan.nextLine(); //store lastname in a variable
System.out.print("\tEnter first name: ");
String firstname = scan.nextLine(); //store firstname in a variable
Student student = new Student(lastname, firstname); //creat new student object with the last and firstname
StudentList.add(student); //add it to the student list
}
//print out all students first and lastnames. here you can add the other data you want to print.
for (int i = 0; i < students; i++)
{
System.out.println("List of all Students:");
System.out.println("Firstname:"+StudentList.get(i).firstName()+" Lastname:"+StudentList.get(i).lastName());
}
}
}

Categories

Resources