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.
Related
I'm doing an assignment that asks a user to input a student name, and then quiz scores until the user chooses to stop. It then calculates the total score and the average of all those scores and outputs them to the screen.
We are moving on to the subject of inheritance and now we are requested to make a class called MonitoredStudent which extends Student. The point of the MonitoredStudent class is to check if the average is above a user inputted average and display whether the student is off academic probation.
I have got most of the program written and when I input just one score (such as 71, when the average I set is 70) it is still displaying that I am on academic probation, even though the one quiz score is above the average I set of 70.
The main issue is that no matter what integer is set for the minimum passing average, I always get a return of false.
I added the "return false" statement in the isOffProbation method as when I add an if-else statement to check if the averageScore (from the Student class) is less than or equal to minPassingAvg eclipse tells me that the method needs a return type of boolean.
public class MonitoredStudent extends Student {
int minPassingAvg;
public MonitoredStudent(){
super();
minPassingAvg = 0;
}
public MonitoredStudent(String name, int minPassingAvg) {
super(name);
this.minPassingAvg = minPassingAvg;
}
public int getMinPassingAvg() {
return minPassingAvg;
}
public void setMinPassingAvg(int minPassingAvg) {
this.minPassingAvg = minPassingAvg;
}
boolean isOffProbation() {
if(getAverageScore() >= minPassingAvg)
return true;
return false;
}
}
This is the Student super class:
public class Student{
private String name;
private double totalScore;
private int quizCount;
public Student(){
name = "";
totalScore = 0;
quizCount = 0;
}
public Student(String n){
name = n;
totalScore = 0;
quizCount = 0;
}
public void setName(String aName){
name = aName;
}
public String getName(){
return name;
}
public void addQuiz(int score){
if(score >= 0 && score <= 100){
totalScore = totalScore + score;
quizCount = quizCount + 1;
}else{
System.out.println("Score must be between 0 and 100, inclusive");
}
}
public double getTotalScore(){
return totalScore;
}
public double getAverageScore(){
return totalScore / quizCount;
}
}
This is the main method:
import java.util.Scanner;
public class MonitoredStudentTester{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
MonitoredStudent monStu = new MonitoredStudent();
String repeat = "n";
int currentScore = 0;
int minPassAv;
System.out.println("Enter the student's name:");
String stuName = scan.next();
Student sName = new Student(stuName);
System.out.println("What is the minimum passing average score: ");
minPassAv = scan.nextInt();
Student stu = new Student();
do {
System.out.println("Enter a quiz score: ");
currentScore = scan.nextInt();
stu.addQuiz(currentScore);
monStu.setMinPassingAvg(currentScore);
System.out.println("Would you like to enter any more scores?: (Y for yes, N for no)");
scan.nextLine();
repeat = scan.nextLine();
}while(repeat.equalsIgnoreCase("y"));
String studName = stu.getName();
double totalScore = stu.getTotalScore();
double avgScore = stu.getAverageScore();
boolean offProb = monStu.isOffProbation();
System.out.println(studName + "'s Total Score is: " + totalScore);
System.out.println(studName + "'s Average Score is: " + avgScore);
System.out.println("Is " + studName + "off academic probation?: " + offProb);
}
}
You main class should be something like this.
public class MonitoredStudentTester {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
MonitoredStudent monStu = new MonitoredStudent();
String repeat = "n";
int currentScore = 0;
int minPassAv;
System.out.println("Enter the student's name:");
monStu.setName(scan.next());
System.out.println("What is the minimum passing average score: ");
minPassAv = scan.nextInt();
do {
System.out.println("Enter a quiz score: ");
currentScore = scan.nextInt();
monStu.addQuiz(currentScore);
monStu.setMinPassingAvg(minPassAv);
System.out.println("Would you like to enter any more scores?: (Y for yes, N for no)");
scan.nextLine();
repeat = scan.nextLine();
} while (repeat.equalsIgnoreCase("y"));
String studName = monStu.getName();
double totalScore = monStu.getTotalScore();
double avgScore = monStu.getAverageScore();
boolean offProb = monStu.isOffProbation();
System.out.println(studName + "'s Total Score is: " + totalScore);
System.out.println(studName + "'s Average Score is: " + avgScore);
System.out.println("Is " + studName + "off academic probation?: " + offProb);
}
}
When using inheritance you just need to create an object of child class.
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 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;
I am currently trying to program a array based program. We have to make a employee class then a tester main class that holds a array of five user input employee names, salaries, and performance rating. The performance rating is used to determine a supplied raise amount. I have it basically done, but when i run the program, nothing happens even though java virtual machine is running. I have looked up and down for the error, anyone can point out what i am doing wrong?
Employee Class
public class Employee
{
private String employeeName;
private int salary;
private int performanceRating;
public Employee()
{
employeeName = "";
salary = 0;
performanceRating = 0;
}
public String getEmployeeName()
{
return employeeName;
}
public int getSalary()
{
return salary;
}
public int getPerformanceRating()
{
return performanceRating;
}
}
And this is the tester main class where the error comes in somewhere
import java.util.Scanner;
public class Tester
{
public static void main(String[] args)
{
Employee[] work = new Employee[5];
Scanner scanString = new Scanner(System.in);
Scanner scanInt = new Scanner(System.in);
String employeeName = "";
double salary = 0;
double performanceRating = 0;
String choice = scanString.nextLine();
while(choice.equals("yes"))
{
for(int i = 0; i < 5 ;i++)
{
System.out.println("What is the employee's name?");
employeeName = scanString.nextLine();
System.out.println("Enter Employee's salary");
salary = scanInt.nextInt();
System.out.println("Performance? 1 = excellent, 2 = good, 3 = poor");
performanceRating = scanInt.nextInt();
work[i] = new Employee();
}
for(int j = 0; j < 5; j ++)
if(work[j].getPerformanceRating() == 1)
{
salary = salary * 0.06;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating == 2)
{
salary = salary * 0.04;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating == 3)
{
salary = salary * 0.015;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating < 5)
{
salary = salary;
System.out.println("Rating is off scale. No raise for emplyee " + employeeName);
}
System.out.println("Enter more employees? type 'yes' if you want to go again");
choice = scanString.nextLine();
}
System.out.println("Done");
}
}
The program reads from System.in. If you don't enter anything, nothing will happen.
Not sure why you have 2 Scanners instead of just one.
You have while(choice.equals("yes")) except you never prompt the user to make a choice. The program does do stuff (some of which may not all work properly), but you have to give the program input. What you can do is ask the user a question before the line String choice = scanString.nextLine();.
As a side note, you could use a switch in place of the if and else if's and it might be a little easier to read and understand.
Hey guys just need help on how to finish this up.
Code Snippet:
import java.util.Scanner;
public class CreateLoans implements LoanConstants {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//set the program here
float prime;
float amountOfLoan = 0;
String customerFirstName;
String customerLastName;
String LoanType;
System.out.println("Please Enter the current prime interest rate");
prime = sc.nextInt() / 100f;
//ask for Personal or Business
System.out.println("are you after a business or personal loan? Type business or personal");
LoanType = sc.next();
//enter the Loan amount
System.out.println("Enter the amount of loan");
amountOfLoan = sc.nextInt();
//enter Customer Names
System.out.println("Enter First Name");
customerFirstName = sc.next();
System.out.println("Enter Last Name");
customerLastName = sc.next();
//enter the term
System.out.println("Enter the Type of Loan you want. 1 = short tem , 2 = medium term , 3 = long term");
int t = sc.nextInt();
}
}
I need to display the records I have asked and store the object into an array.
so this where I'm stuck. I need to do this in a loop 5 times and by the end display all records in an array, if that makes sense?
Try this way :
import java.util.Scanner;
public class CreateLoans {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Loan[] loans = new Loan[5];
for(int i=0;i<5;i++) {
loans[i] = new Loan();
System.out.println("Please Enter the current prime interest rate");
float prime = sc.nextInt();
prime = (float)(prime/100f);
loans[i].setPrime(prime);
//ask for Personal or Business
System.out.println("are you after a business or personal loan? Type business or personal");
String loanType = sc.next();
loans[i].setLoanType(loanType);
//enter the Loan amount
System.out.println("Enter the amount of loan");
float amountOfLoan = sc.nextFloat();
loans[i].setAmountOfLoan(amountOfLoan);
//enter Customer Names
System.out.println("Enter First Name");
String customerFirstName = sc.next();
loans[i].setCustomerFirstName(customerFirstName);
System.out.println("Enter Last Name");
String customerLastName = sc.next();
loans[i].setCustomerLastName(customerLastName);
}
//Display details
for(int i=0;i<5;i++) {
System.out.println(loans[i]);
}
}
}
class Loan {
private float prime;
private float amountOfLoan = 0;
private String customerFirstName;
private String customerLastName;
private String LoanType;
public float getPrime() {
return prime;
}
public void setPrime(float prime) {
this.prime = prime;
}
public float getAmountOfLoan() {
return amountOfLoan;
}
public void setAmountOfLoan(float amountOfLoan) {
this.amountOfLoan = amountOfLoan;
}
public String getCustomerFirstName() {
return customerFirstName;
}
public void setCustomerFirstName(String customerFirstName) {
this.customerFirstName = customerFirstName;
}
public String getCustomerLastName() {
return customerLastName;
}
public void setCustomerLastName(String customerLastName) {
this.customerLastName = customerLastName;
}
public String getLoanType() {
return LoanType;
}
public void setLoanType(String loanType) {
LoanType = loanType;
}
#Override
public String toString() {
return "First Name : " + customerFirstName + "\n" +
"Last Name : " + customerLastName + "\n" +
"Amount of Loan : " + amountOfLoan + "\n" +
"Loan type : " + LoanType + "\n" +
"Prime : " + prime + "\n\n";
}
}
Create a Loan class and put all necessary details as private members into it and override toString() method.
Make a ArrayList and add all the variables inside that list
ArrayList arrlist = new ArrayList();
arrlist.add(prime);
arrlist.add(LoanType);
arrlist.add(amountOfLoan);
arrlist.add(customerFirstName );
arrlist.add(customerLastName);
arrlist.add(t);
and display the ArrayList
System.out.println(arrlist);
Example of a loop
int[] nums = new int[5];
String[] names = new String[5];
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++){
System.out.println("Enter a number: ");
int number = input.nextInt();
// insert into array
nums[i] = number;
System.out.println("Enter a name: ");
String name = input.nextLne();
// insert into array
names[i] = name;
}
Everything you want to be looped 5 times, you can put inside the loop. Whatever values you want to store, you can do that in the loop also.