I need help trying to rewrite this program using a linked list. Any help you can give me would help. I have never used linked lists before, and so far looking online has just confused me. Here is my code that is using an arraylist.
public class Main {
public static void main(String[] args) throws Exception {
String stdID, sName, fName, lName, mName;
int testScore1, testScore2, testScore3,totalNoHours;
float cGPA;
Students workobj;
//****************************************External Output*****************************************************
PrintWriter output;
output = new PrintWriter(new File("StudentRecords.txt"));
//****************************************External Input******************************************************
try {
//opening the file for input
FileInputStream istream = new FileInputStream("input.txt");
Scanner input = new Scanner(istream);
//creating an arraylist to store student objects
ArrayList<Students> AllStudents = new ArrayList<Students>();
while (input.hasNextLine()) {
//first I will read the student id
stdID = input.next();
//next I will read the student name
fName = input.next();
lName = input.next();
if (input.hasNextInt()) {
mName = "";
} else {
mName = input.next();
}
sName = fName + " " + lName + " " + mName;
//next read in the test scores
testScore1 = input.nextInt();
testScore2 = input.nextInt();
testScore3 = input.nextInt();
//next read in totalNoHours
totalNoHours = input.nextInt();
//next read in cGPA
cGPA = input.nextFloat();
//creating a student object
Students StudentRecord = new Students(stdID, sName, testScore1, testScore2, testScore3,totalNoHours,cGPA);
//now store this in allstudents
AllStudents.add(StudentRecord);
}//end of while
}//end of main
}//end of program
LinkedList<Student> list = new LinkedList<Student>();
for(Student s: AllStudents)
list.add(s);
public static void main(String[] args)
{
List<Integer> t=new ArrayList<Integer>();
t.add(1);
t.add(2);
t.add(5);
t.add(3);
System.out.println("ArrayList upcating to list");
for(Integer x:t)
{
System.out.println(x);
}
System.out.println(t instanceof ArrayList);
System.out.println(t instanceof LinkedList);
t=new LinkedList<Integer>(t);
System.out.println("After upcasted to linkedList");
for(Integer x:t)
{
System.out.println(x);
}
System.out.println(t instanceof LinkedList);
System.out.println(t instanceof ArrayList);
}
Related
I am having a problem displaying the user input of subjects (subj) and their units (unit). It says null, which part do you think I have to fix/add? And if possible, can I add column on this so that subjects and units will align together? What do I have to do/import? This is my whole code (I am a beginner):
package com.mycompany.studentinfo;
import java.util.Scanner;
public class StudentInfo {
static String lname, fname, mname, program, subj;
static int studentno, unit;
public static void main(String[] args){
student();
academicinfo();
academicunit();
finaloutput();
}
static void student() {
try {
System.out.println("***PROVIDE THE FOLLOWING***");
Scanner sc = new Scanner(System.in);
System.out.print("Student No: ");
studentno = sc.nextInt();
String xd = sc.nextLine(); // extra
System.out.print("Last Name: ");
lname = sc.nextLine();
System.out.print("First Name: ");
fname = sc.nextLine();
System.out.print("Middle Name: ");
mname = sc.nextLine();
}
catch (Exception x){
System.out.println("***ERROR***");
student();
}
}
static void academicinfo() {
Scanner sc = new Scanner(System.in);
String[] subj = new String[8];
System.out.print("Program: ");
program = sc.nextLine();
System.out.println("Courses: ");
int i = 0;
while (i < subj.length) {
subj[i] = sc.nextLine();
i++;
}
}
static void academicunit() {
Scanner sc = new Scanner(System.in);
int[] unit = new int[8];
System.out.println("Units in corresponding order");
int i = 0;
while (i < unit.length) {
unit[i] = sc.nextInt();
i++;
}
}
static void finaloutput() {
System.out.println("PERSONAL INFORMATION");
System.out.println("\tStudent No. " + studentno);
System.out.println("\tLast Name: " + lname);
System.out.println("\tFirst Name: " + fname);
System.out.println("\tMiddle Name: " + mname);
System.out.println("\nACADEMIC INFORMATION");
System.out.println("Program: " + program);
System.out.println("Courses: ");
System.out.println(subj);
System.out.println(unit);
}
}
With this code, the final output will be:
PERSONAL INFORMATION
Student No. 123
Last Name: asd
First Name: asd
Middle Name: asd
ACADEMIC INFORMATION
Program: asd
Courses:
null
0
and the outcome I am trying to do is:
PERSONAL INFORMATION
Student No. 123
Last Name: asd
First Name: asd
Middle Name: asd
ACADEMIC INFORMATION
Program: asd
Courses: Units:
this is course 0
It is because in method academicInfo you are declaring and initialising a local variable String[] subj, while the class variable subj remains unchanged.
You ought to remove the declaration of subj in the foregoing method and declare and initialise subj as an array of Strings at class level.
public class StudentInfo {
static String lname, fname, mname, program;
static int studentno, unit;
static String[] subj = new String[8];
...
...
static void academicinfo() {
Scanner sc = new Scanner(System.in);
System.out.print("Program: ");
program = sc.nextLine();
System.out.println("Courses: ");
int i = 0;
while (i < subj.length) {
subj[i] = sc.nextLine();
i++;
}
}
...
Inside the method academicInfo you are creating the variable subj again, but as String[]. I believe you want to use the variable declared in line 4, in that case it would be like this:
static void academicinfo() {
Scanner sc = new Scanner(System.in);
System.out.print("Program: ");
program = sc.nextLine();
System.out.println("Courses: ");
subj = sc.nextLine();
}
Now, to align the texts, you must use the System.out.format, passing as a parameter the text and the division number, it would look like this:
String courses_text = "Courses:";
String units_text = "Units:";
System.out.format("%-5d"+courses_text,1);
System.out.format("%-5d"+units_text,2);
System.out.println();
System.out.format("%-5d"+subj, 1);
System.out.format("%-5d"+unit, 2);
See more about alignment here
I have looked at similar examples or other programs that call array from another class and it seems like I have done it the correct way but I am still getting errors.
This is where the arrarys are stored:
import java.util.Scanner;
public class DriverProgram {
public static int[] IDs = new int[10];
public static String[] names = new String[10];
public static double[] grades = new double[10];
public static int i = 0;
static Student call = new Student();
public static void main(String[] args){
call = new Student();
Scanner command = new Scanner(System.in);
System.out.println("Please Enter a command(i, r, s, or d): ");
while(command.hasNext()){
char command1 = command.next().charAt(0);
if(command1 == 'i'){
call.AddToArray(IDs[], names[] , grades[], i);
}else if(command1 == 'r'){
call.RemoveFromArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 's'){
call.SortArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 'd'){
call.DisplayArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 'z') {
break;
}
else System.out.println("Invalid command enter a valid command next time.");
System.out.println("Please Enter a command(i, r, s, or d) or z to finish: ");
}
}
And this is what I am tryign to call the arrays to:
import java.util.Scanner;
public class Student {
public static void AddToArray(int[] IDs, String[] names, double[] grades, int i) {
if (i >= 10) {
System.out.println("You have already inputted 10 students please delete one first.");
} else {
Scanner readin = new Scanner(System.in);
Scanner readinname = new Scanner(System.in);
Scanner readingrade = new Scanner(System.in);
System.out.println("Please enter student ID: ");
IDs[i] = readin.nextInt();
System.out.println("Please enter student name: ");
names[i] = readinname.nextLine();
System.out.println("Please enter student grade: ");
grades[i] = readingrade.nextDouble();
System.out.println(IDs[i] + " " + names[i] + " " + grades[i]);
i++;
for (int j = 0; j < i; j++) {
if (IDs[j] == IDs[i]) {
System.out.println("This student has already been entered.");
}else{
System.out.println("The student has been added");
break;
}
}
}
}
I am not sure what else I need or what I am missing in order to call those arrays.
call.AddToArray(IDs[], names[] , grades[], i);
should be replaced with
call.AddToArray(IDs, names , grades, i);
P.S. Design notes
Student has only static method, so this is utilitly class and should not allowed an instance creation
call.AddToArray() and others static methods should be called as Student.AddToArray()
array is not correct data strucutre where you can add or remove elements. There're more suitable data structures like List or Map.
It's better to use only one instance of Scanner.
This is how you DriverProgram could look like.
public class DriverProgram {
public static void main(String[] args) {
Map<Integer, Student> students = new HashMap<>();
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
System.out.println("Please Enter a command [1-5]:");
System.out.println("1. add new student");
System.out.println("2. remove existed student");
System.out.println("3. sort existed students by grades desc");
System.out.println("4. show existed students");
System.out.println("5. exit");
System.out.print("> ");
int menu = scan.nextInt();
if (menu == 1)
addStudent(scan, students);
else if (menu == 2)
removeStudent(scan, students);
else if (menu == 3)
sortStudents(students);
else if (menu == 4)
showStudents(students);
else if (menu == 5)
break;
System.err.println("Unknown command. Try again");
}
}
private static void addStudent(Scanner scan, Map<Integer, Student> students) {
if (students.size() == 10) {
System.err.println("You have already inputted 10 students please delete one first.");
return;
}
System.out.print("Please enter student ID: ");
int id = scan.nextInt();
if (students.containsKey(id)) {
System.err.println("This student with this id has already been entered.");
return;
}
System.out.print("Please enter student name: ");
String name = scan.nextLine();
System.out.print("Please enter student grade: ");
double grade = scan.nextDouble();
students.put(id, new Student(id, name, grade));
}
private static void removeStudent(Scanner scan, Map<Integer, Student> students) {
}
private static void sortStudents(Map<Integer, Student> students) {
}
private static void showStudents(Map<Integer, Student> students) {
}
public static final class Student {
private final int id;
private final String name;
private final double grade;
public Student(int id, String name, double grade) {
this.id = id;
this.name = name;
this.grade = grade;
}
}
}
I have to make a program using inheritance and I want to print out what I have inputted. But when I run the program, no error founded, it just gives me an empty blank space. What is wrong with my code? Did I make a mistake in calling the variable?
This is my main code:
package labweek7;
import java.awt.Menu;
import java.util.Scanner;
import java.util.Vector;
public class Main {
Vector<String> menu =new Vector<>();
Scanner scan = new Scanner(System.in);
//Employee emp;
Employee emp = new EmployeeFullTime(null, 0, null, null);
Employee emps = new EmployeePartTime(null, 0, null, null);
EmployeeFullTime ft = new EmployeeFullTime(null, 0, null, null);
EmployeePartTime pt = new EmployeePartTime(null, 0, null, null);
public Main() {
int choice = 0;
int pay;
int time;
int salary;
do{
System.out.println("ABC EMPLOYEE DATA");
System.out.println("=================");
System.out.println("1. Add Employee");
System.out.println("2. View Employee");
System.out.println("3. Resign");
System.out.println("4. Exit");
System.out.print("Choice: ");
choice = scan.nextInt();
scan.nextLine();
switch(choice){
case 1:
String name = "";
do{
System.out.print("Input employee name[must be more than 3 characters]: ");
name = scan.next();
}while(! (name.length()>=3));
emp.empName.add(name);
int age;
do{
System.out.print("Input employee age[>=17]: ");
age = scan.nextInt();
}while(!(age>=17));
emp.empAge.add(age);
String role = "";
do{
System.out.print("Input employee role[Assistant | Programmer](Case Sensitive): ");
role = scan.next();
}while(!(role.equals("Assistant") || (role.equals("Programmer"))));
emp.empRole.add(role);
String type = "";
do{
System.out.print("Input employee type[PartTime | FullTime](Case Sensitive): ");
type = scan.next();
}while(!(type.equals("PartTime")|| type.equals("FullTime")));
emp.empType.add(type);
if(type.equals("PartTime")){
emp = new EmployeePartTime(name, age, role, type);
do{
System.out.print("Input pay per hour[>=10000]: ");
pay = scan.nextInt();
}while(!(pay>=10000));
pt.pays.add(pay);
do{
System.out.print("Input working hour per week[>0]: ");
time = scan.nextInt();
}while(!(time>0));
pt.hours.add(time);
}
else{
emps = new EmployeeFullTime(name, age, role, type);
do{
System.out.print("Input base salary[>=10000]: ");
salary = scan.nextInt();
}while(!(salary>=10000));
ft.salary.add(salary);
}
String status = "active";
System.out.println("Success insert employee data");
System.out.println("");
System.out.println("Please any key to continue...");
scan.nextLine();
break;
case 2:
boolean ans = emp.empName.isEmpty();
if(ans == true){
System.out.println("There is no employee data in the list");
}
else
{
view();
}
}
}while(choice!=4);
}
void view(){
//for(int i=0; i<menu.size(); i++){
System.out.println("Employee no.");
if(emp.empType.equals("FullTime")){
System.out.println("Full Time Employee");
System.out.println("===================");
System.out.println("Status: ");
for(int j=0; j<emps.empName.size(); j++){
// if(emps == null){
// }
// else{
System.out.println("Name: " + emps.empName.get(j));
// }
//System.out.println("Name: " + emps.empName.get(j));
}
for(int m=0; m<emp.empAge.size(); m++){
System.out.println("Age: " + emps.empAge.get(m));
}
for(int n=0; n<emps.empRole.size(); n++){
System.out.println("Role: " + emps.empRole.get(n));
}
for(int o=0; o<ft.salary.size(); o++){
System.out.println("Base salary per month: " + ft.salary.get(o));
}
System.out.println("");
}
else
{
System.out.println("Part Time Employee");
System.out.println("===================");
// System.out.println("Status: " );
// System.out.println("Name: " + emp.empName.get(i));
// System.out.println("Age: " + emp.empAge.get(i));
// System.out.println("Role: " + emp.empRole.get(i));
// System.out.println("Pay per hour: "+pt.pays.get(i));
// System.out.println("Working hour per week: "+pt.hours.get(i));
// System.out.println("Salary per month: "+ pt.pays.get(i) * pt.hours.get(i));
//
}
System.out.println("\n\n");
System.out.println("Press any key to continue...");
}
void resign(){
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Main();
}
}
This is my parent class:
package labweek7;
import java.util.Vector;
public abstract class Employee {
public String name;
public int age;
public String role;
public String type;
Vector<String> empName = new Vector<>();
Vector<Integer> empAge = new Vector<>();
Vector<String> empRole = new Vector<>();
Vector<String> empType = new Vector<>();
public Employee(String name, int age, String role, String type) {
// TODO Auto-generated constructor stub
this.name = name;
this.age = age;
this.role = role;
this.type = type;
}
}
This is my child class 1 :
package labweek7;
import java.util.Vector;
public class EmployeePartTime extends Employee{
int pay;
int hour;
Vector<Integer> pays = new Vector<>();
Vector<Integer> hours = new Vector<>();
public EmployeePartTime(String name, int age, String role, String type) {
super(name, age, role, type);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
This is my child class 2 :
p
ackage labweek7;
import java.util.Vector;
public class EmployeeFullTime extends Employee{
int gaji;
Vector<Integer> salary = new Vector<>();
public EmployeeFullTime(String name, int age, String role, String type) {
super(name, age, role, type);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
Did I make mistake in the for loop? Why does my code not printing the inputted items? Any help is appreciated. Thank You.
I have debugged your code in my eclipse work-space.
I'm able to insert the employee data successfully as shown below:
ABC EMPLOYEE DATA
=================
1. Add Employee
2. View Employee
3. Resign
4. Exit
Choice: 1
Input employee name[must be more than 3 characters]: asfds
Input employee age[>=17]: 14
Input employee age[>=17]: 18
Input employee role[Assistant | Programmer](Case Sensitive): Assistant
Input employee type[PartTime | FullTime](Case Sensitive): PartTime
Input pay per hour[>=10000]: 20000
Input working hour per week[>0]: 12
Success insert employee data
But after selecting second option for View Employee I was getting empty output.
ABC EMPLOYEE DATA
=================
1. Add Employee
2. View Employee
3. Resign
4. Exit
Choice: 2
There is no employee data in the list
After debugging it a bit more I came across a condition in Main()
boolean ans = emp.empName.isEmpty();
if(ans == true){
System.out.println("There is no employee data in the list");
} else {
view();
}
The emp.empName is empty here. All Vectors are empty which belong to Employee class.
Vector<String> empName = new Vector<>();
Vector<Integer> empAge = new Vector<>();
Vector<String> empRole = new Vector<>();
Vector<String> empType = new Vector<>();
As a workaround I just changed emp.empName.isEmpty() to emp.name.isEmpty() to resolve the problem. I hope this helps you in identifying the problem.
I'm trying to convert the user input from the question of students name and score into a array.
I also need help to printout the array.
The while loop is using boolean loopNaming as its condition, and i is updated everytime the loop occurs.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
String[] name = new String[i];
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
name[i] = keyboard.next();
if(name[i].equals("done"))
{
loopNaming = false;
}
else
{
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
i=i+1;
}
System.out.println(name[i]);
}
}
You can simplify the logic of your program and write something like this,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
List<String> nameList = new ArrayList<String>();
List<Double> scoreList = new ArrayList<Double>();
while (true) {
System.out.printf("Enter first name of student or done to finish: ");
String fname = keyboard.next();
if (fname.equals("done")) {
break;
}
System.out.printf("Enter last name of student: ");
String lname = keyboard.next();
nameList.add(fname + " " + lname);
System.out.println("Enter score: ");
scoreList.add(keyboard.nextDouble());
}
keyboard.close();
System.out.println("Names: " + nameList);
System.out.println("scores: " + scoreList);
}
I have changed the array to an arraylist and moved i=i+1; to inside else segment. Also changed the final print statement to print the list.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
ArrayList<String> name = new ArrayList<String>();
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
name.add(keyboard.next());
if(name.get(i).equals("done"))
{
loopNaming = false;
}
else
{
System.out.println("Enter score: ");
score = keyboard.nextDouble();
i=i+1;
}
}
System.out.println(name);
}
I would firstly recommend using a List data structure:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming = true;
List<String> name = new ArrayList<>();
while (loopNaming) {
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if (input.equals("done")) {
loopNaming = false;
} else {
name.add(input);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
}
System.out.println(name.toString());
}
However, if you very much would like to use an array, you could make your own method to increase the size of your array each time a new name is added:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double score;
int i = 0;
boolean loopNaming = true;
String[] name = {};
while (loopNaming) {
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if (input.equals("done")) {
loopNaming = false;
} else {
name = increaseArray(name);
name[i] = input;
System.out.println("Enter score: ");
score = keyboard.nextDouble();
i++;
}
}
System.out.println(Arrays.toString(name));
}
public static String[] increaseArray(String[] arr) {
String[] temp = new String[arr.length + 1];
for (int i = 0; i < arr.length; i++) {
temp[i] = arr[i];
}
return temp;
}
I was unsure what your plan was with your score variable, but this would be two ways to achieve your desired result.
I hope this helps.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
ArrayList<String> name = new ArrayList<>();
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if(input.equals("done"))
{
loopNaming = false;
}
else
{ name.add(input);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
i=i+1; //no need to use
}
System.out.println(name);
}
You should use a dynamic list because You can't resize an array in Java. The second point when the user gives "done", you should not put it in the list so check it before the insertion.
You declared your String array with size 0. that's why you cant add elements in to it.
import java.util.Scanner;
public class NameArray {
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
double score[] = new double[10];
boolean loopNaming=true;
int i=0;
String namae;
String[] name = new String[10];
int count = 0;
while(loopNaming==true){
System.out.printf("Enter name of student or done to finish: ");
name[i] = keyboard.next();
if(name[i].equals("done")){
loopNaming = false;
}
else{
System.out.println("Enter score: ");
score[i] = keyboard.nextDouble();
count++;
}
i=i+1;
}
for(int j = 0; j < count; j++) {
System.out.println(name[j]+" "+score[j]);
}
}
}
Try this code or you can go for any other data structures.
I have been working on this for a while, but can't quite seem to figure out how to add an item to an ArrayList. I would like to add grocItem (should be 7 grocItems from user input from for loop) into an ArrayList of grocList:
public class ItemData{
public ItemData(String name, double cost, int priority){
Main.(ArrayList grocList).add(grocItem);
// Main.groclist.add(grocItem);
}
}
Main Class:
import java.util.*;
public class Main {
public static List<ItemData> itemData = new ArrayList<ItemData>();
public static void main(String[] args) {
int i=0;
//String name1;
//int priority1;
//double cost1;
String[] item = new String[7];
for (i=0; i<item.length; i++) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter item name " + i);
String name = keyboard.next();
Scanner keyboard2 = new Scanner(System.in);
System.out.println("Enter the price of item " + i);
double cost = keyboard2.nextDouble();
Scanner keyboard3 = new Scanner(System.in);
System.out.println("Enter Priority Number " + i);
int priority = keyboard3.nextInt();
ItemData grocItem = new ItemData(name, cost, priority);
}
//How do I add grocItem to an Array list of other grocItems (6 grocItems from user input array item)
Main.itemData.add(groclist);
}
}
Change your code, add the method inside the loop.
for (i=0; i<item.length; i++) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter item name " + i);
String name = keyboard.next();
Scanner keyboard2 = new Scanner(System.in);
System.out.println("Enter the price of item " + i);
double cost = keyboard2.nextDouble();
Scanner keyboard3 = new Scanner(System.in);
System.out.println("Enter Priority Number " + i);
int priority = keyboard3.nextInt();
ItemData grocItem = new ItemData(name, cost, priority);
itemData.add(grocItem ); // add here
}
You should add the ItemData object to your arraylist inside your loop:
for (i=0; i<item.length; i++) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter item name " + i);
String name = keyboard.next();
Scanner keyboard2 = new Scanner(System.in);
System.out.println("Enter the price of item " + i);
double cost = keyboard2.nextDouble();
Scanner keyboard3 = new Scanner(System.in);
System.out.println("Enter Priority Number " + i);
int priority = keyboard3.nextInt();
ItemData grocItem = new ItemData(name, cost, priority);
itemData.add(groclist); // <-- add to arraylist inside the loop
}