I am working on my final and I got to the part I an mildly confused about.
I can't figure out if it's possible to call the Admin or Student inputs with it being outside of the if statement. I need to call the results in the 3rd and 4th option in the menu and I can't do it without it throwing errors.
public class MainEntry {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int printMenu = 0;
while(printMenu != 5){
printMenu();
printMenu = console.nextInt();
if (printMenu == 1){
String firstName;
String lastName;
int year;
double[] grades;
double studentId;
String major;
int size;
System.out.println("How many students do you have? ");
size = console.nextInt();
Student newStudent = new Student();
int[] stud = new int[size];
for(int i = 0; i < stud.length; i++)
{
System.out.println("What is the students first name? ");
firstName = console.next();
newStudent.setFirstName(firstName);
System.out.println("What is the students last name? ");
lastName = console.next();
newStudent.setLastName(lastName);
System.out.println("What year are they in? ");
year = console.nextInt();
newStudent.setYear(year);
System.out.println("Enter in their grades: ");
grades = console.nextDouble();newStudent.setGrades(grades);
System.out.println("What is their Student ID number? ");
studentId = console.nextDouble();
newStudent.setStudentID(studentId);
System.out.println("What is the student's major? ");
major = console.next();
newStudent.setMajor(major);
}
}
else if (printMenu == 2){
Admin newAdmin = new Admin();
System.out.println("How many admins do you have? ");
int size = console.nextInt();
int[] admins = new int[size];
for(int i = 0; i < admins.length; i++)
{
System.out.println("What is the admin's first name? ");
String firstName = console.next();
newAdmin.setFirstName(firstName);
System.out.println("What is the admin's last name? ");
String lastName = console.next();
newAdmin.setLastName(lastName);
System.out.println("What is their Admin's ID number? ");
double adminId = console.nextDouble();
newAdmin.setAdminId(adminId);
System.out.println("What is the Admin's department? ");
String department = console.next();
newAdmin.setDepartment(department);
System.out.println("What is their salary? ");
int salary = console.nextInt();
newAdmin.setsalary(salary);
}
}
else if (printMenu == 3){
System.out.println("First name: " + newStudent.getFirstName());
System.out.println("Last name: " + newStudent.getLastName());
System.out.println("ID Number: " + newStudent.getStudentID());System.out.println("GPA: " + newStudent.getgrade());System.out.println("Major: "+newStudent.getMajor());
}
else if (printMenu == 4){
System.out.println("First name: " + newAdmin.getFirstName());
System.out.println("Last name: " + newAdmin.getLastName()); System.out.println("ID Number: " + newAdmin.getAdminId()); System.out.println("GPA: " + newAdmin.getgrade());
System.out.println("Major: " + newAdmin.getsalary());
}
else if(printMenu == 5){
System.out.println("Thanks for using my program!");
}
}
}
// This method will bring up the beginning menu for the user
public static void printMenu(){
//Asking the user which option they are selecting
System.out.println("How would you like to input your data?");
System.out.println("1. Enter in students. ");
System.out.println("2. Enter in admins. ");
System.out.println("3. Print the student information. ");
System.out.println("4. Print admin information. ");
System.out.println("5. Exit the program. ");
}
}
For the student grade I need to average there 5 grades together using an array.
public class Student {
// stores the first name
private String firstName;
// stores the last name
private String lastName;
// stores the
private int year;
// stores the grades
private double[] grades;
// stores the ID number
private double studentID;
private String major;
public static int studentInfo;
//here is where it sets the defaults
public Student(){
firstName = "Jane";
lastName = "Doe";
year = 1;
grades = new double[]{0,0,0,0,0};
studentID = 0;
major = "undeclared";
studentInfo++;
}
public static int studentInfo(){
return (studentInfo);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public double[] getGrades() {
return grades;
}
public void setGrades(double[] grades) {
this.grades = grades;
}
public double getStudentID() {
return studentID;
}
public void setStudentID(double studentID) {
this.studentID = studentID;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public static int getStudentInfo() {
return studentInfo;
}
public static void setStudentInfo(int studentInfo) {
Student.studentInfo = studentInfo;
}
public Student(String firstName, String lastName, int year, double[] grades, double studentID){
this.firstName = firstName;
this.lastName = lastName;
this.year = year;
this.grades = grades;
this.studentID = studentID;
studentInfo++;
}
}
I understand how to build it in the class side but I don't understand how to use it in MainEntry. It keeps asking me to change type and I can't figure out what else to do to fix it. I have issues with arrays so that's something that I'm not quite the best at...
Any help is appreciated.
1) For this, you need to declare newStudent outside of the if statement.
while(printMenu != 5){
Student newStudent = null; // ← newStudent is declared here
printMenu();
printMenu = console.nextInt();
This means that you don't declare it later, only assign to it the result of the new operator:
int size;
System.out.println("How many students do you have? ");
size = console.nextInt();
newStudent = new Student(); // ← this is only an assignment, not a declaration
It also means that you have to be careful when the user wants to display the information concerning the student, because newStudent can be null (i.e. no information have been entered yet).
2) The average is not a double array, just a double. This is why the compiler complains about incompatible types. The average will not be computed automatically, you have to do it yourself. Basically, you need two steps. First, iterate through the array and calculate the sum of the elements:
double sum = 0;
for (double g : grades) { // do this for all elements of the array
sum += g; // add the element to the sum
}
Then, the average is the sum divided by the number of elements.
double average = sum / grades.length;
Related
public class billing{
private int id;
//File f=new File("C:/Users/Bingus/Documents/Projects/accounts.txt");
private String bc;
private String bd;
private String customerName;
private String customerAddress;
private String customerNumber;
private String periodT;
private String periodF;
private double presentR;
private double previousR;
private double previousB;
private double dueTotal;
private static ArrayList<Account> accountList = new ArrayList<>();
public billing(int id,String bc,String bd,String customerName,String customerAddress,String customerNumber,String periodT,String periodF,double presentR,double previousR,double previousB,double dueTotal){
this.id = id;
this.bc = bc;
this.bd = bd;
this.customerName = customerName;
this.customerAddress = customerAddress;
this.customerNumber = customerNumber;
this.periodT = periodT;
this.periodF = periodF;
this.presentR = presentR;
this.previousR = previousR;
this.previousB = previousB;
this.dueTotal = dueTotal;
}
public int getId(){
return id;
}
public String getBc(){
return bc;
}
public String getBd(){
return bd;
}
public String getCustomerName(){
return customerName;
}
public String getCustomerAddress(){
return customerAddress;
}
public String getCustomerNumber(){
return customerNumber;
}
public String getPeriodT(){
return periodT;
}
public String getPeriodF(){
return periodF;
}
public double getPresentR(){
return presentR;
}
public double getPreviousR(){
return previousR;
}
public double getPreviousB(){
return previousB;
}
public double getDue(){
return dueTotal;
}
public static void main(String[] args){
Scanner scanner = new Scanner (System.in);
Scanner kb = new Scanner (System.in);
int user_choice;
int x = 0;
do{
System.out.println();
System.out.println("1) New Billing");
System.out.println("2) Add Existing Billing");
System.out.println("3) View Billing Account ID");
System.out.println("4) View By Date");
System.out.println("5) Update Existing Billing");
System.out.println("6) Delete Billing Account");
System.out.println("7) Display All Account");
System.out.println("8) Exit");
System.out.println();
System.out.print("Enter choice [1-8]: ");
user_choice = scanner.nextInt();
switch (user_choice){
case 1:
int min = 1000;
int max = 9999;
int randomStr = (int)(Math.random() * (max - min + 1) + min);
int id = randomStr;
System.out.println("Your Account Number is : " + id);
System.out.print("Enter Billing Code: ");
String bc = scanner.next();
System.out.print("Enter Billing Date(dd/mm/yyyy): ");
String bd = scanner.next();
System.out.print("Enter Customer Name: ");
String customerName = kb.nextLine();
System.out.print("Enter Customer Address: ");
String customerAddress = kb.nextLine();
System.out.print("Enter Customer Number: ");
String customerNumber = scanner.next();
System.out.print("Enter Period To: ");
String periodT = scanner.next();
System.out.print("Enter Period From: ");
String periodF = scanner.next();
System.out.print("Enter Present Reading: ");
double presentR = scanner.nextDouble();
System.out.print("Enter Previous Reading: ");
double previousR = scanner.nextDouble();
System.out.print("Enter Previous Balance: ");
double previousB = scanner.nextDouble();
double dueTotal = getTotalDue(presentR,previousR,previousB);
Account user = new Account(id,bc,bd,customerName,customerAddress,customerNumber,periodT,periodF,presentR,previousR,previousB,dueTotal);
accountList.add(user);
break;
case 2:
case 3:
System.out.print("Enter Account Number: ");
int a = scanner.nextInt();
for(int i = 0; i<accountList.size();i++){
if(a == accountList.get(i).getId()){
System.out.println("Account ID: " + accountList.get(i).getId());
System.out.println("Customer Name: " +accountList.get(i).getCustomerName());
System.out.println("Customer Address: " + accountList.get(i).getCustomerAddress());
System.out.print("Customer Number: " + accountList.get(i).getCustomerNumber());
}
}
System.out.println("\nBilling Code\t\tBilling Date\t\tAmount Due");
for(int i = 0; i<accountList.size();i++){
if(a == accountList.get(i).getId())
{
System.out.println(accountList.get(i).getBc()+"\t\t\t"+accountList.get(i).getBd()+"\t\t\t"+accountList.get(i).getDue());
}
}
break;
case 4:
case 5:
System.out.print("Enter Account Number: ");
a = scanner.nextInt();
for(int i = 0; i<accountList.size();i++){
if(a == accountList.get(i).getId())
{
System.out.println("Your Account Number is : " + accountList.get(i).getId());
System.out.print("Enter Billing Code: ");
String bCode = scanner.next();
String c = accountList.get(i).getBc(); //this is the part in which i am having a hard time to fix, ive used the set but still i cannot change the element inside.
int index = accountList.indexOf(c);
accountList.set(index, bCode);
}
}
break;
case 6:
System.out.print("Enter Account Number: ");
a = scanner.nextInt();
System.out.print("Enter Billing Code: ");
String b = scanner.next();
for(int i = 0; i<accountList.size();i++){
if(a == accountList.get(i).getId()){
if(b.equals(accountList.get(i).getBc())){
accountList.remove(i);
System.out.print("\nAccount Removed\n");
}else{
System.out.print("Invalid Billing Code\n");
}
}else if(a != accountList.get(i).getId()){
System.out.print("Invalid Account Number or Number not in the database.\n");
}else{
System.out.print("Try Again\n");
}
}
break;
case 7:
System.out.println("Account ID\t\tBilling Code\t\tAccount Name\t\tTotal Due\t\tPresent R\t\tPrevious R");
Collections.sort(accountList,Collections.reverseOrder());
for(int i=0; i<accountList.size();i++){
System.out.println(accountList.get(i).getId() + "\t\t\t"+accountList.get(i).getBc()+ "\t\t\t"+accountList.get(i).getCustomerName()+ "\t\t\t"+accountList.get(i).getDue()+"\t\t\t"+accountList.get(i).getPresentR()+ "\t\t\t"+accountList.get(i).getPreviousR());
}
break;
}
}while(user_choice!=8);
}
I'm new to programming in Java and I'm still learning towards it. I'm making my billing system which calcualtes the payment. My problem for this is how can I change or update the value which is already in the arraylist, I've tried the set() but I cannot make it work. using arraylist is a big jump for me and I haven't yet got a hang of it. I've watched youtube vids but they seem to show non user input arry lists
Any help?
[1]: https://i.stack.imgur.com/HhF33.png
There are two ways to do it.
First Option is Loop the list and reach the object you want to change, update its attributes. Since the object is accessed by reference, whatever values you will change it will effect.
Second option is remove the object at that index, create a new object and insert at that position.
public void testArrayList ()
{
class MyData
{
String Id = "";
String Name = "";
public MyData () {}
public MyData (String id, String name) {
Id= id;
Name = name;
}
public String toString ()
{
return " Id=" + Id + " Name=" + Name;
}
}
ArrayList myDList = new ArrayList ();
myDList.add(new MyData("1", "John"));
myDList.add(new MyData("2", "Mike"));
myDList.add(new MyData("3", "Tom"));
System.err.println ("Org List " + myDList);
MyData tmp = (MyData) myDList.get(1);
tmp.Id = "22";
tmp.Name = tmp.Name + " Changed";
System.err.println ("Mod List (Observe second Object ) " + myDList);
}
You need to set the value in ArrayList to be an object of type Account.
1.You need to get an object of type Account and use settter method to update bcode
2. Set that Account object back to ArrayList
Code TL:DR. Do you have a set method in your Account class?
//set method example
public void setBc(String newBc){ //can also use other data types as parameters
this.bc = newBc;
}
If so you can just
accountList.get(i).setBc("This New BCODE"); //The parameter can also be a variable of string type
Your code:
System.out.println("Your Account Number is : " + accountList.get(i).getId());
System.out.print("Enter Billing Code: ");
String bCode = scanner.next();
String c = accountList.get(i).getBc(); //this is the part in which i am having a hard time to fix, ive used the set but still i cannot change the element inside.
int index = accountList.indexOf(c);
accountList.set(index, bCode);
If you want to update billing code in an account then get the account object and update the user entered bCode on the object. Also, you don't have to put the account back in the list:
System.out.println("Your Account Number is : " + accountList.get(i).getId());
System.out.print("Enter Billing Code: ");
String bCode = scanner.next();
Account existing = accountList.get(i);
//create new account with same data except bCode
Account updated = new Account(existing.getId(),bCode, existing.getBd(),/*do same for rest of the fields */);
int index = accountList.indexOf(existing);
accountList.set(index, updated);
You have to change this part in Your program
…
Billing billing = accountList.get(i);
//String c = billing.getBc(); // this is the part in which I am having a hard time to fix, I've used
// the set but still I cannot change the element inside.
billing.setBc( yourNewBc );
//int index = accountList.indexOf(c);
//accountList.set(index, billing);
…
class names are capitalized in Java
Here in this example we have iterated over the list and modified the values of the object.
Please make a setter to the values you want to modify and follow something like this.
public class Arr {
public static void main(String args[]){
ArrayList<Person> array = new ArrayList();
Scanner sc=new Scanner(System.in);
while (true){
System.out.println("1.add 2. modify 3.view list ; anything else to to quit");
int choice = sc.nextInt();
if (choice==1){
System.out.println("Enter ID then salary");
int id = sc.nextInt();
int salary = sc.nextInt();
Person p = new Person(id,salary);
array.add(p);
System.out.println("Done");
}
else if (choice==2){
System.out.println("Enter ID");
int id = sc.nextInt();
for (int i = 0; i < array.size(); i++){
Person p = array.get(i);
if (p.getId()==id){
System.out.println("value exits. Enter salary to be modified:");
int salary = sc.nextInt();
p.setSalary(salary);
}
}
System.out.println("Done");
}
else if (choice==3){
for (int i = 0; i < array.size(); i++)
System.out.print(" " + array.get(i).getId() + " " + array.get(i).getSalary());
}
else
break;
}
}
}
public class Person {
int id;
int salary;
public Person(int id, int salary) {
this.id = id;
this.salary = salary;
}
public int getId() {
return id;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
I am a student and looking for help with an assignment. Here is the task: Create a CollegeCourse class. The class contains fields for the course ID (for example, “CIS 210”), credit hours (for example, 3), and a letter grade (for example, ‘A’).
Include get() and set()methods for each field. Create a Student class containing an ID number and an array of five CollegeCourse objects. Create a get() and set() method for the Student ID number. Also create a get() method that returns one of the Student’s CollegeCourses; the method takes an integer argument and returns the CollegeCourse in that position (0 through 4). Next, create a set() method that sets the value of one of the Student’s CollegeCourses; the method takes two arguments—a CollegeCourse and an integer representing the CollegeCourse’s position (0 through 4).
I am getting runtime errors on the second for loop where I am trying to get the data into the course array. It is asking for both the CourseID and Hours in the same line and regardless of what I respond with it I am getting an error, it almost seems like it is trying to get all the arrays variables at the same time. Here is my code which includes three classes. Any help to send me in the right direction is appreciated as I have spent a ton of time already researching to resolve.
public class CollegeCourse {
private String courseId;
private int creditHours;
private char grade;
public CollegeCourse(String id, int hours, char grade)
{
courseId=id;
creditHours = hours;
this.grade = grade;
}
public void setCourseId(String id)
{
courseId = id;//Assign course id to local variable
}
public String getCourseId()
{
return courseId;//Provide access to course id
}
public void setHours(int hours)
{
creditHours = hours;//Assign course id to local variable
}
public int getHours()
{
return creditHours;//Provide access to course id
}
public void setGrade(char grade)
{
this.grade = grade;//Assign course id to local variable
}
public char getGrade()
{
return grade;//Provide access to course id
}
}
Student Class
public class Student {
final int NUM_COURSES = 5;
private int studentId;
private CollegeCourse courseAdd;//Declares a course object
private CollegeCourse[] courses = new CollegeCourse[NUM_COURSES];
//constructor using user input
public Student(int studentId)
{
this.studentId=studentId;
}
public void setStudentId(int id)
{
studentId = id;//Assign course id to local variable
}
public int getStudentId()
{
return studentId;//Provide access to course id
}
public void setCourse(int index, CollegeCourse course)
{
courses[index] = course;
}
public CollegeCourse getCourse(int index)
{
return courses[index];
//do I need code to return the courseId hours, grade
}
}
InputGrades Class
import java.util.Scanner;
public class InputGrades {
public static void main(String[] args) {
final int NUM_STUDENTS = 2;
final int NUM_COURSES = 3;
Student[] students = new Student[NUM_STUDENTS];
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
//String gradeInput;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + (s+1) + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
csIndex=c;
System.out.print("Enter course ID #" + (c+1) + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
System.out.println();
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
After input.nextInt() you need to add one more input.nextLine(); and than you can read grade.
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
Why it is needed? See this question: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
You should add a very simple length validation when you input the grade:
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
so the full main class code:
import java.util.Scanner;
/**
* Created by dkis on 2016.10.22..
*/
public class App {
public static void main(String[] args) {
final int NUM_STUDENTS = 10;
final int NUM_COURSES = 5;
Student[] students = new Student[NUM_STUDENTS];
//String name;
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + s+1 + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
//CollegeCourse course = students[s].getCourse(c);
csIndex=c;
System.out.print("Enter course ID#" + c+1 + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
public class Exams {
private int score1 = 0;
private int score2 = 0;
private int score3 = 0;
public void setScore1(int sc){
score1 = sc;
}
public void setScore2(int sc){
score2 = sc;
}
public void setScore3(int sc){
score3 = sc;
}
public int getScore1(){
return score1;
}
public int getScore2(){
return score2;
}
public int getScore3(){
return score3;
}
public String toString(){
return String.format("%-10s %-10s %4.2f\n", score1, score2, score3);
}
}
public class Student {
private String fName;
private String lName;
private Exams scores;
Student(String fn, String ln) {
fName = fn;
lName = ln;
scores = new scores();
}
public void setScore1(int sc) {
scores.setScore1(sc);
}
public void setScore2(int sc) {
scores.setScore2(sc);
}
public void setScore3(int sc) {
scores.setScore3(sc);
}
public String toSring(){
return String.format("%-10s %-10s %4.2f\n", fName, lName, scores);
}
public double getAverage(){
}
public int compareTo(Student s){
String name1 = lName + " " + fName;
String name2 = s.lName + " " + s.fName;
return ((lName + " " + fName).compareTo(s.lName + " " + s.fName));
}
}
public class ClassRoll {
private ArrayList<Student> students = new ArrayList<Student>();
private String title;
private String filename = "data.txt";
ClassRoll(String f) {
Scanner kb = new Scanner(System.in);
String inpFileName = kb.next();
File inpFile = new File(inpFileName);
Student s = new Student(fName, lName);
}
void Remove() {
Scanner kb = new Scanner(System.in);
System.out.println("What is the Student's first name?");
String fName = kb.next();
System.out.println("What is the Student's last name?");
String lName = kb.next();
Student s = new Student(fName, lName);
for (int i = 0; i < students.size(); i++) {
if (s.compareTo(students.get(i)) == 0) {
students.remove(i);
} else {
System.out.println("Error: Student is not in Class");
}
}
}
void Display() {
}
void Add() {
Scanner kb = new Scanner(System.in);
System.out.println("What is the Student's first name?");
String fName = kb.next();
System.out.println("What is the Student's last name?");
String lName = kb.next();
System.out.println("What is the Student's first score?");
int score1 = kb.nextInt();
System.out.println("What is the Student's second score?");
int score2 = kb.nextInt();
System.out.println("What is the Student's third score?");
int score3 = kb.nextInt();
Student s = new Student(fName, lName);
for (int i = 0; i < students.size(); i++) {
if (s.compareTo(students.get(i)) == 0) {
System.out.println("Student already in class");
} else {
students.add(s);
}
}
}
void changeScore1() {
Scanner kb = new Scanner(System.in);
System.out.println("What is the Student's first name?");
String fName = kb.next();
System.out.println("What is the Student's last name?");
String lName = kb.next();
System.out.println("What is the Student's first score?");
int score1 = kb.nextInt();
Student s = new Student(fName, lName);
for (int i = 0; i < students.size(); i++) {
if (s.compareTo(students.get(i)) == 0) {
s.setScore1(i);
} else {
System.out.println("Error: Student is not in Class");
}
}
}
void changeScore2() {
Scanner kb = new Scanner(System.in);
System.out.println("What is the Student's first name?");
String fName = kb.next();
System.out.println("What is the Student's last name?");
String lName = kb.next();
System.out.println("What is the Student's first score?");
int score1 = kb.nextInt();
Student s = new Student(fName, lName);
for (int i = 0; i < students.size(); i++) {
if (s.compareTo(students.get(i)) == 0) {
s.setScore2(i);
} else {
System.out.println("Error: Student is not in Class");
}
}
}
void changeScore3() {
Scanner kb = new Scanner(System.in);
System.out.println("What is the Student's first name?");
String fName = kb.next();
System.out.println("What is the Student's last name?");
String lName = kb.next();
System.out.println("What is the Student's first score?");
int score1 = kb.nextInt();
Student s = new Student(fName, lName);
for (int i = 0; i < students.size(); i++) {
if (s.compareTo(students.get(i)) == 0) {
s.setScore3(i);
} else {
System.out.println("Error: Student is not in Class");
}
}
}
public void sortAverage() {
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.getAverage() < s2.getAverage()) {
students.set(i, s2);
students.set(j, s1);
}
}
}
}
public void sortNames() {
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.compareTo(s2) > 0) {
students.set(i, s2);
students.set(j, s1);
}
}
}
}
public void save(){
}
}
I have a program with a couple of different classes. In the classroll class after I declare the private variables I have to create a classroll constructor "ClassRoll(String f)" that is suppose to .....
Read the class roll data from the input file f, creates Student objects for each of the students and adds them to the ArrayList of students. The input file contains the course title on the first line. The data for each student appears on a separate line consisting of first name, last name, score1, score 2, and score3 separated by at least one space.
I tried my best to start it off but I'm confused and don't really know the right way of making it. Can someone please help
Thank you
Read the class roll data from the input file f, creates Student
objects for each of the students and adds them to the ArrayList of
students.
Ok, so basically, we have to get student's information from some file and add it to some ArrayList. Alright, lets create an ArrayList for storing stuff first.
ArrayList<Student> studentInfo = new ArrayList<Student>();
You already have this code to read from file:
Scanner kb = new Scanner(System.in);
String inpFileName = kb.next();
File inpFile = new File(inpFileName);
Lets move on....
The input file contains the course title on the first line.
So first element in kb.nextLine() is the course title. This means that we have to start adding student data from second line aka skip the first line. Alright....
The data for each student appears on a separate line consisting of
first name, last name, score1, score 2, and score3 separated by at
least one space.
So basically, if we manage to split lines from space characters, we get data. Now to implement this:
Lets create a boolean variable to check if its first line or not:
boolean firstLine = true; // True - because it starts from first line
Time to start reading lines....
String courseName = ""; //I'll just store in a string, use as you wish
while(kb.hasNextLine()){
if(firstLine){
courseName = kb.nextLine(); //Set courseName if its first line
firstLine = false; // We have moved past first line
}
else{ // Otherwise get student data
// Lets store the student data in a string. This is just one line.
// Something like: "FirstName LastName score1 score2 score3"
String studentData = kb.nextLine();
// Now time to split up data (so we get names/scores separately)
String[] stData = studentData.split("\\s"); //Remember they have spaces between them. \\s --> A pattern that matches one or more spaces
//So we can use those to separate data
// This is how String[] stData contains the student information:
// stData[0] = first name of student
// stData[1] = last name of student
// stData[2] = score1
// stData[3] = score2
// stData[4] = score3
// Use this data however you like
//Now that we have separated data, lets add the student object to ArrayList since we got all details.
studentInfo.add(new Student(stData[0], stData[1]);
// This last line of code is probably not going to do the trick.
// You may need to make changes to your code to do stuff
}
}
In any case, I have told you how to read the problem and how to proceed. You have all the strings, the firstname, lastname and scores. Now its upto you to figure out how to use them. Although the last line of code may not work for your, but its a hint to proceed.
Rest you should try figure out yourself first, since its no fun if I do all the homework ;)
You have replaced the SE with the scire1,2,3
When you get a var in setter method it need to be placed in a property of your class.
Just replace with this code:
public void setScore1(int sc){
score1=sc;
}
public void setScore2(int sc){
score2=sc;
}
public void setScore3(int sc){
score3=sc;
}
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.
This is the code I have now and it is completely butchered. I am having issues try to allow user input of a String and two doubles to go into 3 parallel arrays and then save to a .txt file. I can not figure out what is wrong could someone please assist me?
public static void addGames(int i, String[] array1, double[] array2,
double[] array3, int arrayLength, Scanner keyboard) throws IOException
{
String newName;
double newPrice;
double newRating;
if(i < arrayLength)
{
System.out.println("Please enter another game name: ");
newName = keyboard.next();
array1[i] = newName;
System.out.println("Please enter another game price: ");
newPrice = keyboard.nextDouble();
array2[i] = newPrice;
System.out.println("Please enter another game rating: ");
newRating = keyboard.nextDouble();
array3[i] = newRating;
i++;
}
else
{
System.out.println("There is no more room to store games: ");
}
PrintWriter gamerOut = new PrintWriter("Project1_VideoGames.txt");
while(i < array1.length)
{
gamerOut.write(array1[i]);
gamerOut.add(array2[i]);
gamerOut.add(array3[i]);
i++;
}
gamerOut.close();
}
for (int j = 0; j < i; ++j) {
gamerOut.println(array1[j] + "\t" + array2[j] + "\t" + array3[j]);
No need to say the names are too imaginative for me. Make a
public class Game {
String name;
double price;
double rating;
}
Check if this is what you want.
Instead of having 3 arrays, I encapsulated all in a Gameclass.
public class Game {
private String name;
private double price;
private double rating;
public Game(String name, double price, double rating){
this.name = name;
this.price = price;
this.rating = rating;
}
#Override
public String toString(){
String ret = "";
ret = ret + name + " / " + price + " / " + rating;
return ret;
}
}
And this is what I came with for your addGames function. It only takes 1 parameter now: the number of games you want to write in the file.
public static void addGames(int gamesNumber) throws IOException
{
int i = 0;
String newName;
double newPrice, newRating;
Scanner keyboard = new Scanner(System.in);
ArrayList<Game> array = new ArrayList<Game>();
while(i < gamesNumber)
{
System.out.println("Please enter another game name: ");
newName = keyboard.next();
System.out.println("Please enter another game price: ");
newPrice = keyboard.nextDouble();
System.out.println("Please enter another game rating: ");
newRating = keyboard.nextDouble();
System.out.println();
Game game = new Game(newName, newPrice, newRating);
array.add(game);
i++;
}
System.out.println("There is no more room to store games. ");
PrintWriter gamerOut = new PrintWriter("Project1_VideoGames.txt");
i = 0;
while(i < array.size())
{
gamerOut.println(array.get(i));
i++;
}
gamerOut.close();
System.out.println("The games have been written in the file");
}
You probably want to handle some errors while reading the users input or handle exceptions from the FileWriter but I'll leave that to you.
Also, I've changed to PrintWriter#println method instead of PrintWriter#write and override the toString method in the Game class. You may want to change the implementation of that too.
Hope this helped.