Displaying a function calculation - java

I'm encountering an issue on a program I'm compiling. i got to display the actual calculation on function 2.The main program is called display11 and I'm calling the functions on the other class. can't figure it out whats wrong that is not displaying the loop. thanks a lot
import java.util.Scanner;
/**
*
* #author ec1302696
*/
public class Functions
{
private int n;
public void string_function(String name)
{
int optionChosen;
String fname;
String sname;
Scanner keyboard = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
Functions fun = new Functions();
System.out.println("Please enter full name");
fname = sc.nextLine(); //accept first name entered by user
//****enter as a comment for now fun.first(fname);
fun.createname(fname);// this create name
//display this is option 1,administrator name admin
//ask for full name for generating username
//call createname passing the username
}
public void number_function(String admin)
{
{
int n, c, fact = 1;
System.out.println("Enter a number to calculate it's factorial");
Scanner in = new Scanner(System.in);
n = in.nextInt();
if ( n < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
System.out.println("Factorial of "+n+" is = "+fact);
}
// return fact;
//this is option 2 ,administrator name admin
//read the factorial
//calcualte the fatorial
// print it
}
}
public void createname(String username)
{
String fname = fname.substring(0,1);
System.out.println("The usernameis " + fname);
//string calcualte the string function to find the first letter ,and second name.
//concatenate and print it.
}
}
import java.util.Scanner;
/**
*
* #author ec1302696
*/
public class Display11 {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Functions fun = new Functions();// this create teh functions
int optionChosen;
String admin;
Scanner keyboard = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name");
admin = keyboard.nextLine();
{
System.out.println("Welcome please select option from menu below");
}
System.out.println("OPTION 1 – USERNAME");
System.out.println("OPTION 2 - CALCULATE THE FACTORIAL");
System.out.println("OPTION 3 - EXIT");
optionChosen = keyboard.nextInt();
if (optionChosen == 1)
{
fun.string_function(admin);
}
else if (optionChosen == 2) {
{
fun.number_function(admin);
}
}
else if (optionChosen == 3)
{
}
}
}

If you need to show the calculation of the factorial, change the calculation loop to something like this:
StringBuilder result = new StringBuilder("Factorial of ").append(n).append(" is ");
for ( c = n ; c >0 ; c-- )
{
result.append(c);
if(c>1)
{
result.append(" * ");
}
fact = fact*c;
}
result.append(" = ").append(fact);
System.out.println(result);

Related

While loop not repeating in java

A program that takes ticket orders and provides the total. It's not letting me answer the question whether, i would like to buy more tickets. I'm a beginner, If you guys could guide me or suggest any upgrades that would be helpful.
package ridecalc;
import java.util.Scanner;
/** *
1. #author */
public class Ridecalc {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
double tickets = 0;
double totprice;
String moretickets = "";
System.out.println("Hi! welcome to JP's amusment park");
do {
if (response()) {
System.out.println("How many tickets would you like to purchase ?");
tickets = in.nextInt();
} else {
totprice = 0;
}
totprice = calc(tickets);
System.out.println("The total amount for the tickets are :" + totprice);
System.out.println("Would you like to buy more tickets ?(y/n)");
moretickets = in.nextLine();
} while (moretickets.equalsIgnoreCase("y"));
}
public static boolean response() {
Scanner in = new Scanner(System.in);
String response = "";
System.out.println("Would you like to buy any tickets (y/n)");
response = in.nextLine();
if (response.equalsIgnoreCase("y")) {
return true;
} else {
return false;
}
}
public static double calc(double tickets) {
double totprice;
totprice = (tickets * 20);
return totprice;
}
}
List item
Firstly, your response.equalsIgnoreCase("y") never evaluates to true because it is always an empty string, there has been no affectation to the variable response. So I added a boolean rps that will store the response of the user from your function response() and loop until it is true.
EDIT: Fixed usage of Scanner, only one Scanner instance
EDIT 2: Fixed double condition
package ridecalc;
import java.util.Scanner;
/** *
1. #author */
public class some {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
double tickets = 0;
double totprice;
String moretickets = "";
System.out.println("Hi! welcome to JP's amusment park");
boolean rps = true;
while( rps ){
if ( (rps = response(in)) == true) {
System.out.println("How many tickets would you like to purchase ?");
tickets = in .nextInt();
} else {
totprice = 0;
}
totprice = calc(tickets);
System.out.println("The total amount for the tickets are :" + totprice);
System.out.println("Would you like to buy more tickets ?(y/n)"); // this doesn't seem necessary since there is no test following
in.next();
moretickets = in.nextLine();
}
}
public static boolean response(Scanner in) {
String response = "";
System.out.println("Would you like to buy any tickets (y/n)");
response = in.nextLine();
if (response.equalsIgnoreCase("y")) {
System.err.println("here");
return true;
} else {
return false;
}
}
public static double calc(double tickets) {
double totprice;
totprice = (tickets * 20);
return totprice;
}
}

How does one pass parameters between methods and correctly call the method using Java?

The program should do the following:
Write a method called getheartRate that takes no parameters and returns an int (heartRate).
This method prompts the user for the patient's heart rate, reads
their input from the command line, and returns this value.
Write a method called checkHeartRate that takes an int parameter (the heart rate) and returns
a String (result). If the heart rate is above 100, return the value "High". If the heart rate is below
60, return the value "Low". Otherwise return "Normal".
Write a method called printHRResult that takes a String parameter, which is the result
from the method checkHeartRate. Print this value to the command line.
Call all three methods from the main method using appropriate parameter passing.
So far I have:
public class UnitSixInClassFall2018 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
UnitSixInClassFall2018 u = new UnitSixInClassFall2018();
u.getHeartRate();
System.out.println();
Scanner scan = new Scanner(System.in);
u.checkHeartRate(0);
// END MAIN
}
public int getHeartRate(){
System.out.print("Please enter your heart rate: ");
Scanner scan = new Scanner(System.in);
int heartRate = scan.nextInt();
return 0;
}
public void checkHeartRate(int heartRate){
if (heartRate > 100) {
String result = "High";
}
else if (heartRate < 60) {
String result = "Low";
}
else {
String result = "Normal";
}
}
public String printHRResults(String result) {
System.out.print("Your hear rate is " + result + ".");
return result;
}
}
When this is run, all that is output is "Please enter your heart rate: ". Once I enter an integer, the program ends. What is being done incorrectly?
You should change this method to return the heart rate like this:
public int getHeartRate(){
System.out.print("Please enter your heart rate: ");
Scanner scan = new Scanner(System.in);
int heartRate = scan.nextInt();
// Also add this
scan.close();
return heartRate;
}
And change this method to return the result:
public String checkHeartRate(int heartRate){
if (heartRate > 100) {
return "High";
}
else if (heartRate < 60) {
return "Low";
}
else {
return "Normal";
}
}
Then in your main method:
// get the heart rate
int heartRate = u.getHeartRate();
// Call the checkHeartRate method
String result = checkHeartRate(heartRate);
// call the printHRResults
printHRResults(result);
That should solve your problem.
First of all, you are creating two Scanner objects with the same input type (System.in), which isn't recommended. Instead, just make one Scanner object and use it everywhere in your program. This post has some good info.
An improved version of your code with an improved use of the Scanner object is as follows:
public UnitSixInClassFall2018 {
private static final Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
NewMain u = new NewMain();
int heartRate = u.getHeartRate();
System.out.println();
String result = u.checkHeartRate(heartRate);
u.printHRResults(result);
scan.close(); // Close the scanner once you are completely done using it
}
public int getHeartRate() {
System.out.print("Please enter your heart rate: ");
return scan.nextInt(); // Return the input of the user
}
public String checkHeartRate(int heartRate) {
String result = ""; // Initialize some default value
if (heartRate > 100) {
result = "High";
}
else if (heartRate < 60) {
result = "Low";
}
else {
result = "Normal";
}
return result; // Return the result calculated from the if-statements
}
public void printHRResults(String result) {
System.out.print("Your heart rate is " + result + ".");
// Originally this method returned a string but that seems unnecessary
}
}

Method to Find ArrayList Index to Where the Object Will be Added

I have an ArrayList that is being filled with customer information using a Customer class. In my addCustomerRecord method, I am calling findAddIndex within the addCustomerRecord method so the data entered will be sorted prior to displaying the data. Here is my code and do not mind the fileWhatever method, I don't use it.
public class CustomerDemo
{
//arrayList of customer objects
public static ArrayList<Customer> customerAL = new ArrayList<>();
public static void main (String[] args)
{
//to hold menu choice
String menuChoice = "";
Scanner kb = new Scanner(System.in);
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
//loop priming read
menuChoice = kb.nextLine();
//make input case insensitive
menuChoice = menuChoice.toLowerCase();
do
{
if(menuChoice.equals("a"))
addCustomerRecord(kb);
else if(menuChoice.equals("d"))
{
displayCustomerRecords();
}
else if(menuChoice.equals("q"))
{
System.out.println("Program exiting..");
System.exit(0);
}
else
{
System.out.println("incorrect entry. Please re-enter a valid entry: \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}while(menuChoice.equals("a") || menuChoice.equals("d") || menuChoice.equals("q"));
kb.close();
}
/* public static void displayCustomerRecords()
{
System.out.println();
for (int i = 0; i < customerAL.size(); ++i)
{
System.out.printf("%-15s", customerAL.get(i).getLastName());
System.out.printf("%-15s", customerAL.get(i).getFirstName());
System.out.printf("%-6s", customerAL.get(i).getCustID());
System.out.printf("%15s\n", customerAL.get(i).getPhoneNumber());
}
System.out.println();
}
/**
* prompts to enter customer data and mutator methods called
* with a Scanner object passed as an argument to set data
* #param location index position of where the element will be added.
* #param kb a Scanner object to accept input
*/
public static void addCustomerRecord(Scanner kb)
{
Customer currentCustomerMemoryAddress = new Customer();
System.out.println("Enter first name: \n");
String fName = kb.nextLine();
currentCustomerMemoryAddress.setFirstName(fName);
System.out.println("Enter last name: \n");
String lName = kb.nextLine();
currentCustomerMemoryAddress.setLastName(lName);
System.out.println("Enter customer phone number: \n");
String pNum = kb.nextLine();
currentCustomerMemoryAddress.setPhoneNumber(pNum);
System.out.println("Enter customer ID number: \n");
String ID = kb.nextLine();
currentCustomerMemoryAddress.setCustID(ID);
int addLocation = findAddLocation(currentCustomerMemoryAddress);
customerAL.add(addLocation, currentCustomerMemoryAddress);
currentCustomerMemoryAddress = null;
}
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(int i = 0; i < customerAL.size(); i++)
{
//Stumped here
}
}
else
return location;
return location;
}
}
It looks like you are reinventing the wheel here William
Replace your code for displayCustomerRecords with this:
public static void displayCustomerRecords()
{
System.out.println();
customerAL.stream().map(c -> String.format("%-15s%-15s%-6s%15s\n",
c.getLastName(), c.getFirstName(), c.getCustID(), c.getPhoneNumber()))
.sorted()
.forEach(System.out::print);
System.out.println();
}
Update
Taking into account your comment you can replace your findAddLocationmethod by the following:
private static Comparator<Customer> comparator = Comparator.comparing(Customer::getLastName)
.thenComparing(Customer::getFirstName)
.thenComparing(Customer::getCustID)
.thenComparing(Customer::getPhoneNumber);
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(Customer customerInList : customerAL)
{
if(comparator.compare(customerInList, cust) > 0) {
break;
}
location++;
}
}
return location;
}
We are traversing the array using Java's enhanced for-loop and comparing the objects using a Java 8 declared comparator (which I believe is the key to this assignment).
It would be a good idea if you could look into the Comparable interface and implement it in your Customer class. That way you could simply do a simple call to customerInList.compareTo(cust) to compare both objects.
As already stated, this is not a good practice and shouldn't be used in production code.

Getting Exception java.util.NoSuchElementException: No line found while reading from file?

The code was working fine before but getting runtime exception even when no changes were made. The programs purpose is, to be a database for baseball players, which houses a couple of their stats - can be seen in code below. When I run the program now, I get this error
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Assig3.getBatters(Assig3.java:47)
at Assig3.<init>(Assig3.java:62)
at Assig3.main(Assig3.java:248)
This error is not really helping me to solve anything, I am completely lost about, what is the problem which occured overnight . Anyways here is the code, it is split up between three files which receive the data from a fourth plain text file
import java.util.*;
import java.io.*;
// CS 0401 Assignment 3 main program class. Note how this class is set up
// with instance variables and methods. The idea is that the main program is itself an
// object and the methods being called are parts of the object that implement the various
// requirements. I have implemented the initial reading of the data from the file to
// get you started. You must add the menu and all of its required functionality.
// Note that this program WILL NOT COMPILE until you have completed the Batter and BatterDB
// classes to some extent. They do not have to be totally working but all of the methods
// used here must be implemented in order for this code to compile.
public class Assig3
{
private BatterDB theDB;
private Batter currBatter;
private Scanner inScan;
private String fName;
// Note how this method is working. It first reads the number of Batters from the
// file, then for each Batter it gets the names, creates the object, and mutates it
// with the instance methods shown. Finally, it adds the new object to the BatterDB
// object.
public void getBatters(String fName) throws IOException
{
Batter currB;
File inFile = new File(fName);
Scanner inScan = new Scanner(inFile);
int numBatters = inScan.nextInt();
inScan.nextLine();
for (int i = 0; i < numBatters; i++)
{
String first = inScan.nextLine();
String last = inScan.nextLine();
currB = new Batter(first, last);
int ab, h, d, t, hr;
ab = inScan.nextInt(); inScan.nextLine();
currB.setBats(ab);
h = inScan.nextInt(); inScan.nextLine();
currB.setHits(h);
d = inScan.nextInt(); inScan.nextLine();
currB.setDoubles(d);
t = inScan.nextInt(); inScan.nextLine();
currB.setTriples(t);
hr = inScan.nextInt(); inScan.nextLine();
currB.setHR(hr);
theDB.addBatter(currB);
}
}
// Constructor is really where the execution begins. Initialize the
// database (done for you) and then go into the main interactive loop (you
// must add this code).
public Assig3(String fstring) throws IOException
{
Scanner reader = new Scanner(System.in);
fName = fstring;
Batter currB;
theDB = new BatterDB(); // <-- there used to be a 2 in there
getBatters(fName);
System.out.println("The database has been loaded");
System.out.println(theDB.toString());
commandPrompter();
String command = reader.next();
while(!command.equals("8")){
if(command.equals("1")){
System.out.println(theDB.toString());
} else if(command.equals("2")){
System.out.println("First name: ");
String first = reader.next();
System.out.println("Last name: ");
String last = reader.next();
currB = new Batter(first, last);
int ab, h, d, t, hr;
System.out.print("How many times did he bat: ");
ab = reader.nextInt();
currB.setBats(ab);
System.out.println("How many hits: ");
h = reader.nextInt();
if(h>ab || h<0){
while(h>ab || h<0){
System.out.println("Invalid try again: ");
h = reader.nextInt();
}
}
currB.setHits(h);
System.out.println("How many doubles: ");
d = reader.nextInt();
if(d>ab || d<0 || d>h){
while(d>ab || d<0){
System.out.println("Invalid try again: ");
d = reader.nextInt();
}
}
currB.setDoubles(d);
System.out.println("How many triples: ");
t = reader.nextInt();
if(t>ab || t<0 || t>h || (t+d)>h){
while(t>ab || t<0 || t>h || (t+d)>h){
System.out.println("Invalid try again: ");
t = reader.nextInt();
}
}
currB.setTriples(t);
System.out.println("How many Homeruns: ");
hr = reader.nextInt();
if(hr>ab || hr<0 || hr>h || (hr+d+t)>h){
while(hr>ab || hr<0 || hr>h || (hr+d+t)>h){
System.out.println("Invalid try again: ");
hr = reader.nextInt();
}
}
currB.setHR(hr);
theDB.addBatter(currB);
} else if(command.equals("3")){
System.out.println("Player first name: ");
String firstNameSearch = reader.next();
System.out.println("Player last name: ");
String lastNameSearch = reader.next();
currB = theDB.findBatter(firstNameSearch, lastNameSearch);
if(currB == null){
System.out.println("The player you wish to see in not in this database");
} else {
System.out.println(currB.toString());
}
} else if(command.equals("4")){
System.out.println("Player first name: ");
String firstNameSearch = reader.next();
System.out.println("Player last name: ");
String lastNameSearch = reader.next();
currB = theDB.findBatter(firstNameSearch, lastNameSearch);
if(currB == null){
System.out.println("The player you wish to remove in not in this database");
} else {
System.out.println("The player has been removed from the database");
theDB.removeBatter(currB);
}
} else if(command.equals("5")){
System.out.println("Player first name: ");
String firstNameSearch = reader.next();
System.out.println("Player last name: ");
String lastNameSearch = reader.next();
currB = theDB.findBatter(firstNameSearch, lastNameSearch);
if(currB == null){
System.out.println("The player you wish to edit in not in this database");
} else {
int ab, h, d, t, hr;
System.out.print("How many times did he bat: ");
ab = reader.nextInt();
currB.setBats(ab);
System.out.println("How many hits: ");
h = reader.nextInt();
if(h>ab || h<0){
while(h>ab || h<0){
System.out.println("Invalid try again: ");
h = reader.nextInt();
}
}
currB.setHits(h);
System.out.println("How many doubles: ");
d = reader.nextInt();
if(d>ab || d<0 || d>h){
while(d>ab || d<0){
System.out.println("Invalid try again: ");
d = reader.nextInt();
}
}
currB.setDoubles(d);
System.out.println("How many triples: ");
t = reader.nextInt();
if(t>ab || t<0 || t>h || (t+d)>h){
while(t>ab || t<0 || t>h || (t+d)>h){
System.out.println("Invalid try again: ");
t = reader.nextInt();
}
}
currB.setTriples(t);
System.out.println("How many Homeruns: ");
hr = reader.nextInt();
if(hr>ab || hr<0 || hr>h || (hr+d+t)>h){
while(hr>ab || hr<0 || hr>h || (hr+d+t)>h){
System.out.println("Invalid try again: ");
hr = reader.nextInt();
}
}
currB.setHR(hr);
}
} else if(command.equals("6")){
theDB.sortName();
} else if(command.equals("7")){
theDB.sortAve();
} else {
System.out.println("What the heck that was not an option, bye.");
}
commandPrompter();
command = reader.next();
}
theDB.toStringFile();
System.out.println("Thanks for using the DB! Bye.");
}
private void commandPrompter(){
System.out.println("Please choose one of the options below: ");
System.out.println("1) Show the list of players");
System.out.println("2) Add a new player");
System.out.println("3) Search for a player");
System.out.println("4) Remove a player");
System.out.println("5) Update a player");
System.out.println("6) Sort the list alphabetically");
System.out.println("7) Sort the list by batting average");
System.out.println("8) Quit the program [list will be saved]");
}
// Note that the main method here is simply creating an Assig3 object. The
// rest of the execution is done via the constructor and other instance methods
// in the Assig3 class. Note also that this is using a command line argument for
// the name of the file. All of our programs so far have had the "String [] args"
// list in the header -- we are finally using it here to read the file name from the
// command line. That name is then passed into the Assig3 constructor.
public static void main(String [] args) throws IOException
{
Assig3 A3 = new Assig3(args[0]);
}
}
BatterDB:
import java.util.ArrayList;
import java.util.Collections;
import java.util.stream.Collectors;
import java.io.PrintWriter;
// CS 0401 BatterDB class
// This class is a simple database of Batter objects. Note the
// instance variables and methods and read the comments carefully. You minimally
// must implement the methods shown. You may also need to add some private methods.
// To get you started I have implemented the constructor and the addBatter method for you.
public class BatterDB
{
private ArrayList<Batter> theBatters = new ArrayList<Batter>(); // ArrayList of Batters
private int num; // int to store logical size of DB
// Initialize this BatterDB
public BatterDB()
{
num = 0;
}
// Take already created Batter and add it to the DB. This is simply putting
// the new Batter at the end of the array, and incrementing the int to
// indicate that a new movie has been added. If no room is left in the
// array, resize to double the previous size, then add at the end. Note that
// the user never knows that resizing has even occurred, and the resize()
// method is private so it cannot be called by the user.
public void addBatter(Batter b)
{
theBatters.add(b);
num++;
}
// Remove and return the Batter that equals() the argument Batter, or
// return null if the Batter is not found. You should not leave a gap in
// the array, so elements after the removed Batter should be shifted over.
public Batter removeBatter(Batter b)
{
theBatters.remove(b);
return b;
}
// Return logical size of the DB
public int numBatters()
{
return theBatters.size();
}
// Resize the Batter array to that specified by the argument
private void resize(int newsize)
{
//Don't need this now that it's an array list!
}
// Find and return the Batter in the DB matching the first and last
// names provided. Return null if not found.
public Batter findBatter(String fName, String lName)
{
Batter currentB = null;
String fullNameSearch = lName+","+fName;
for(int i=0; i<theBatters.size(); i++){
if(fullNameSearch.toUpperCase().equals(theBatters.get(i).getName().toUpperCase())){
currentB = theBatters.get(i);
}
}
return currentB;
//change
}
// Sort the DB alphabetically using the getName() method of Batters for
// comparison
public void sortName()
{
int j;
for ( j = 0; j < theBatters.size()-1; j++)
{
if ( theBatters.get(j).getName().compareToIgnoreCase(theBatters.get(j+1).getName()) > 0 )
{ // ascending sort
Collections.swap(theBatters, j, j+1);
j=0;
}
if ( theBatters.get(j).getName().compareToIgnoreCase(theBatters.get(j+1).getName()) > 0 )
{ // ascending sort
Collections.swap(theBatters, j, j+1);
j=0;
}
}
}
// Sort the DB from high to low using the getAve() method of Batters for
// comparison
public void sortAve()
{
int j;
for ( j = 0; j < theBatters.size()-1; j++)
{
if ((theBatters.get(j+1).getAve() - theBatters.get(j).getAve()) > 0 )
{ // ascending sort
Collections.swap(theBatters, j, j+1);
j=0;
}
if ((theBatters.get(j+1).getAve() - theBatters.get(j).getAve()) > 0 )
{ // ascending sort
Collections.swap(theBatters, j, j+1);
j=0;
}
}
}
// Return a formatted string containing all of the Batters' info. Note
// that to do this you should call the toString() method for each Batter in
// the DB.
public String toString()
{
return theBatters.stream().map(b -> b.toString()).collect(Collectors.joining("\n"));
}
// Similar to the method above, but now we are not formatting the
// string, so we can write the data to the file.
public void toStringFile()
{
try{
PrintWriter writer = new PrintWriter("batters.txt", "UTF-8");
writer.println(theBatters.size());
for(int i=0; i<theBatters.size(); i++){
String[] parts = theBatters.get(i).getName().split(",");
String fName= parts[1];
String lName = parts[0];
writer.println(fName);
writer.println(lName);
writer.println(theBatters.get(i).getAtBats());
writer.println(theBatters.get(i).getHits());
writer.println(theBatters.get(i).getDoubles());
writer.println(theBatters.get(i).getTriples());
writer.println(theBatters.get(i).getHomeRuns());
}
writer.close();
} catch (Exception e) {
System.out.println("Did not work, sorry :(");
}
}
}
Batter:
public class Batter {
private String firstName;
private String lastName;
private int atBats;
private int hits;
private int doubles;
private int triples;
private int homeRuns;
public Batter(String fName, String lName){
firstName = fName;
lastName = lName;
}
public void setBats(int batCount){
atBats = batCount;
}
public void setHits(int hitCount){
hits = hitCount;
}
public void setDoubles(int doubleCount){
doubles = doubleCount;
}
public void setTriples(int tripleCount){
triples = tripleCount;
}
public void setHR(int homeRunCount){
homeRuns = homeRunCount;
}
public double getAve(){
double one = this.hits;
double two = this.atBats;
double average = (one / two);
return average;
}
public int getAtBats(){
return this.atBats;
}
public int getHits(){
return this.hits;
}
public int getDoubles(){
return this.doubles;
}
public int getTriples(){
return this.triples;
}
public int getHomeRuns(){
return this.homeRuns;
}
public String getName(){
String fullName = this.lastName + "," + this.firstName;
return fullName;
}
public boolean equals(){
return true;
}
public String toString(){
return "Player: "+getName()+"\nAt Bats: "+this.atBats+"\nHits: "+this.hits+"\nDoubles: "+this.doubles+"\nTriples: "+this.triples+"\nHome Runs: "+this.homeRuns;
}
}
batters.txt (text file):
5
Cannot
Hit
635
155
12
7
6
Major
Hitter
610
290
50
25
65
The
Hulk
650
300
0
0
300
Iron
Man
700
600
300
0
300
Herb
Weaselman
600
200
20
15
30
Error :
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Assig3.getBatters(Assig3.java:47)
at Assig3.<init>(Assig3.java:62)
at Assig3.main(Assig3.java:248)
Description :
NoSuchElementException mean whatever your code is trying to read is not there
mean there is no element which you are trying to read.
At line 47 i.e hr = inScan.nextInt(); inScan.nextLine();
your code is trying to read an int and nextline
but there is no next line in your source file
which basically will happen in the last iteration of your loop
Reason is when your code reach your last file entry i.e 30 then
hr = inScan.nextInt(); inScan.nextLine();
//^^^ this will read 30
// but ^^^ there is no next line and hence the exception
Solution : either use hasNextLine or add nextline by using an enter at the end of the file
hr = inScan.nextInt();
if(inScan.hasNextLine())
inScan.nextLine();
or you can manipulate file then simply add an empty line in your file at the end using enter (which i don't recommend)

Method to display records.

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.

Categories

Resources