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)
Related
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.
I have an ArrayList of FlowerClass objects. Each of these FlowerClass objects has a name. I want to go through the ArrayList and count them. I want to display the amount of each. So if I have three FlowerClass objects named Rose, two named Daffodil, and one named Tulip...I want to display the following:
Found 3 Rose
Found 3 Daffodil
Found 3 Tulip
So far, I've gotten it to count correctly using two functions I made. The problem is that I iterate through the entire ArrayList...so it'll show me the results more than once. For example, if the user adds 3 Roses and 2 Daffodils...The output is like this:
Found 3 Roses
Found 3 Roses
Found 3 Roses
Found 2 Daffodils
Found 2 Daffodils
I know why the code does this but I don't know how to erase repeats of output. I also don't know how to implement Collections correctly. I've used Collections on an ArrayList of strings before...and it works. But this time I'd be using Collections on an ArrayList of Objects, and I want to check for the frequency of each specific name. Here is the main class:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class MainClass {
static ArrayList<FlowerClass> flowerPack = new ArrayList<FlowerClass>();
public static void main(String[] args){
Scanner input = new Scanner(System.in);
while(true){
System.out.println("1. Add flower to flowerpack.");
System.out.println("2. Remove flower from the flowerpack.");
System.out.println("3. Search for a flower in the flowerpack.");
System.out.println("4. Display the flowers in the flowerpack.");
System.out.println("5. Exit the program.");
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addFlower();
break;
case 2:
searchFlower();
break;
case 3:
displayFlowers();
break;
case 4:
System.out.println("Goodbye!");
System.exit(0);
}
}
}
public static void addFlower(){
if (FlowerClass.numberFlowers() == 25){
System.out.println("There are 25 flowers in the flowerpack. Remove at least one in order to add more.");
return;
}
Scanner input = new Scanner(System.in);
System.out.println("What is the flower's name?");
String desiredName = input.nextLine();
System.out.println("What is the flower's color?");
String desiredColor = input.nextLine();
System.out.println("How many thorns does it have?");
Scanner input2 = new Scanner(System.in);
int desiredThorns = input2.nextInt();
System.out.println("What does it smell like?");
String desiredSmell = input.nextLine();
flowerPack.add(new FlowerClass(desiredName, desiredColor, desiredThorns, desiredSmell));
}
public static void searchFlower(){
System.out.println("Enter the flower you want to search for.");
Scanner input = new Scanner(System.in);
String userChoice = input.nextLine();
int occurrences = 0;
for (FlowerClass flower: flowerPack){
String name = flower.getName();
if (userChoice.equals(name)){
occurrences++;
}
else if(occurrences == 0){
System.out.println("Match not found.");
return;
}
}
System.out.println("Found " + occurrences + " " + userChoice);
}
public static void searchFlower(String desiredFlower){
int occurrences = 0;
String userChoice = desiredFlower;
for (FlowerClass flower: flowerPack){
String name = flower.getName();
if (userChoice.equals(name)){
occurrences++;
}
}
System.out.println("Found " + occurrences + " " + userChoice);
}
public static void displayFlowers(){
int repeats = 0;
/*for (FlowerClass flower: flowerPack){
System.out.println(flower.getName());
}
System.out.println("Number of flowers in pack: " + FlowerClass.numberFlowers());*/
//int occurrences = Collections.frequency(flowerPack, name);
//System.out.println(name + ": " + occurrences);
for (FlowerClass flower: flowerPack){
String name = flower.getName();
searchFlower(name);
}
}
}
Here is the FlowerClass:
public class FlowerClass {
public static int numberOfFlowers = 0;
public String flowerName = null;
public String flowerColor = null;
public int numberThorns = 0;
public String flowerSmell = null;
FlowerClass(){
}
FlowerClass(String desiredName, String desiredColor, int desiredThorns, String desiredSmell){
flowerName = desiredName;
flowerColor = desiredColor;
numberThorns = desiredThorns;
flowerSmell = desiredSmell;
numberOfFlowers++;
}
public void setName(String desiredName){
flowerName = desiredName;
}
public String getName(){
return flowerName;
}
public static int numberFlowers(){
return numberOfFlowers;
}
}
If you look at my last function in the main class, you'll see that I commented out the way I was attempting to implement Collections.frequency. I also tried making a multidimensional array of Strings and storing the names of the flowers and also the number of flowers in the arrays. This was counting everything correctly but I wasn't sure how to display the names alongside the counts. It was getting very messy so I abandoned that attempt for now in favor of trying these other two options. If I can find a way to erase repeated lines of output (or if I can find a way to get Collections to work) then I won't need to tinker with the multidimensional array.
Any tips would be very much appreciated. Thank you for your time.
Interesting code, but it doesn't work the way I would do it.
In this current case as you've done it, you would need to keep track of the flower names you have already encountered:
public static void displayFlowers(){
//int repeats = 0;
List<String> displayedFlowerTypes = new ArrayList<String>();
for (FlowerClass flower: flowerPack){
String name = flower.getName();
if(!displayedFlowerTypes.contains(name))
{
displayedFlowerTypes.add(name);
searchFlower(name);
}
}
}
What I would rather do is maintain a Map that keeps track of the counts of the flower types, and just obtain the numbers for the types from that:
public class MainClass {
static List<FlowerClass> flowerPack = new ArrayList<FlowerClass>();
static Map<String, Integer> flowerCount = new HashMap<String, Integer>();
public static void addFlower() {
if (FlowerClass.numberFlowers() == 25) {
System.out.println("There are 25 flowers in the flowerpack. Remove at least one in order to add more.");
return;
}
Scanner input = new Scanner(System.in);
System.out.println("What is the flower's name?");
String desiredName = input.nextLine();
System.out.println("What is the flower's color?");
String desiredColor = input.nextLine();
System.out.println("How many thorns does it have?");
Scanner input2 = new Scanner(System.in);
int desiredThorns = input2.nextInt();
System.out.println("What does it smell like?");
String desiredSmell = input.nextLine();
flowerPack.add(new FlowerClass(desiredName, desiredColor, desiredThorns, desiredSmell));
if(!flowerCount.containsKey(desiredName))
{
flowerCount.put(desiredName, 1);
}
else
{
int currentCount = flowerCount.get(desiredName);
flowerCount.put(desiredName, currentCount+1));
}
}
That way, you could just display the flowers as the following:
public static void displayFlowers() {
for (String name : flowerCount.keySet()) {
//searchFlower(name);
System.out.println("Found " + flowerCount.get(name) + " " + name);
}
}
You could put your Flower(s) in a Set. But the easiest solution I can think of is to sort your flowers. So first, implement a Comparator<FlowerClass>
public static class FlowerComparator implements Comparator<FlowerClass> {
#Override
public int compare(FlowerClass o1, FlowerClass o2) {
return o1.getName().compareTo(o2.getName());
}
}
Then you can sort with Collections.sort(List, Comparator)
FlowerComparator flowerComparator = new FlowerComparator();
Collections.sort(flowerPack, flowerComparator);
And then your for loop needs to be something like this (to stop searching for the same flower),
String lastName = null;
for (int i = 0; i < flowerPack.size(); i++){
FlowerClass flower = flowerPack.get(i);
String name = flower.getName();
if (lastName == null || !lastName.equals(name)) {
lastName = name;
searchFlower(name); // or return the number found, and then add that count to i.
}
}
I'm having a problem with my project in Java.
Here's the situation: the user will enter a character and integer of course code subj and units with a loop and restriction that indicates that when the total unit reaches "25" it will stop adding subj and course.
For example:
course code | subject | units
------------+-----------+-------
GE 111 | education | 3
GE 112 | history | 1
and so on..
After the user has entered the codes above, it will count all units and it will print to something thanks for the help. The code is too long, here is the most important part:
int[] a = new int[6];
Scanner sc = new Scanner(System.in);
System.out.println("\nenter units");
for (int j = 0; j < 9; j++) {
a[j] = sc.nextInt();
}
System.out.println("your subjects are:\n : ");
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
System.out.print("\nEnter course code:" + a);
code = br.readLine().charAt(0);
System.out.print("\nenter course description");
subj = br.readLine().charAt(0);
System.out.print("\nenter units");
units = br.readLine().charAt(0);
case 2: break;
case 3: break;
case 4: break;
}
}
Are you trying to achieve this:
Main.java
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//Make one Course container list to store a set of courses
List<Course> courses = new ArrayList<Course>();
//to store sum of units, intially 0
int unitSum = 0;
Course course = null;
while(true){
//make new course
course = new Course();
System.out.println("Enter course code:");
course.setSubjectCode(sc.nextInt());//store course code
System.out.println("Enter subject name:");
course.setSubjectName(sc.next());//store subject name
System.out.println("Enter units:");
course.setUnits(sc.nextInt());//store units
courses.add(course);//add Course to container
//take sum of units
unitSum += course.getUnits();
if(unitSum>=25)//end loop if sum reached 25
break;
}
System.out.println(courses);
sc.close();
}
}
Course.java
public class Course {
private int subjectCode;
private String subjectName;
private int units;
public Course() {
}
public int getSubjectCode() {
return subjectCode;
}
public void setSubjectCode(int subjectCode) {
this.subjectCode = subjectCode;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public int getUnits() {
return units;
}
public void setUnits(int units) {
this.units = units;
}
#Override
public String toString() {
return "Course [subjectCode=" + subjectCode + ", subjectName="
+ subjectName + ", units=" + units + "]";
}
}
this may help you..
Why don't you make object of what you need to work with? Then you can have it so much easier. Make a class and constructor of whathewer you want to use as entry new Entry(data1,data2,data3) work with all of those. It will help you when you make your program more complex.
To sum up the array to get total units
int sum=0;
for(int i:yourArray){
sum+=i;
}
The problem is that you work with all of your data as individual pars try to make some connection between them. Make object and put some functions in. (sum units), (get desc) etc. - it will be easy for you then to precede.
Im having some trouble printing out details ive put into my array. when i run my addBook i out in details of two books, but when i select option 2 from menu, i get a runtime error (outofbounds),
Above is resolved by adding [i] to the printline and changing my loop length.
The problem i am having now if my BookID from my loanbook, its not incrementing.
import java.util.Scanner;
public class library {
static Scanner keyboard = new Scanner(System.in);
static boolean run = true;
public static fiction [] fictionArray = new fiction[2];
public static nonfiction [] nonfictionArray = new nonfiction[2];
public static void main (String[] args){ // main class method
while (run){ // this while statement allows the menu to come up again
int answer = 0; // answer initialized to Zero
boolean isNumber;
do{ // start of validation
System.out.println("1. Add book"); // Menu selections
System.out.println("2. Display the books available for loan");
System.out.println("3. Display the books currently on loan");
System.out.println("4. Make a book loan");
System.out.println("5. Return book ");
System.out.println("6 Write book details to file");
if (keyboard.hasNextInt()){ // I would like to set values to =>1 <=6
answer = keyboard.nextInt(); // this is more validation for the input for menu selection
isNumber = true;
} else { // else if number not entered, it will prompt for the correct input
System.out.print(" You must enter a number from the menu to continue. \n");
isNumber = false;
keyboard.next(); // clears keyboard
}
}
while (!(isNumber)); // while to continue program after the do has completed
switch (answer){ // switch statement - uses answer from the keyboard to select a case
case 1:
addBook(); // adds book
break;
case 2:
for (int i=0; i<5; i++){
if (fictionArray[i] != null){
System.out.println(fictionArray);}
if (nonfictionArray[i] != null){
System.out.println(nonfictionArray);}}
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
}
}
}
static void addBook(){
loanbook [] loanArray = new loanbook[2];
String title,author;
int choice;
for(int x = 0; x < loanArray.length; x++){
System.out.print("Press 1 for Fiction or 2 for Non Fiction: "); // sub menu for fiction and non fiction
choice = keyboard.nextInt();
if (choice == 1){
for(int count = 0; count < fictionArray.length; count++){
System.out.print("Enter title: ");
title= keyboard.nextLine();
title= keyboard.nextLine();
System.out.print("Enter author: ");
author= keyboard.nextLine();
fictionArray[count] = new fiction(title, author);
System.out.println("The book information you entered was : " + fictionArray[count].toString()); // this will show the entry which was inout to the array
count++; }}
else if (choice == 2) {
for(int count = 0; count < nonfictionArray.length; count++){
System.out.print("Enter title: ");
title= keyboard.nextLine();
title= keyboard.nextLine();
System.out.print("Enter author: ");
author= keyboard.nextLine();
nonfictionArray[count] = new nonfiction(title, author);
System.out.println("The book information you entered was : " + nonfictionArray[count].toString()); // this will show the entry which was inout to the array
count++;}}
else{ int noBooks = loanArray.length;
for (int i=0; i<noBooks; i++){
System.out.print(loanArray[x]);
}}}} // addbook
} // Library end
Below is my Superclass , then my subclass
public class loanbook {
private String title,author;
private int bookID;
public loanbook(String pTitle,String pAuthor){
bookID = 0;
title = pTitle;
author = pAuthor;
bookID++;
} // Constructor
public void setTitle(String pTitle){
title = pTitle;
} // setTitle
protected String getTitle(){
return title;
} // getTitle
protected String getAuthor(){
return author;
} // getAuthor
public String toString(){
return "\n BookID: "+ bookID+"\n" + " Title: "+ getTitle()+"\n" +" Author : "+ getAuthor()+ "\n";
}
} // loanbook
My subclasses are the same except for the class name and constructor
public class fiction extends loanbook {
String bookType;
private String getBookType; // Would be fiction
public fiction(String pTitle,String pAuthor){
super(pTitle,pAuthor);
} // constructor
protected void setBookType (String pBookType){
bookType = pBookType;
} // setter for bookType
protected String getBookType(){
return "Fiction";
}
public String toString(){
return super.toString() +" This book is : "+ getBookType();
}
} // class
You've declared your fictionarray and nonfictionarray to be of length 2. However, in your case 2, you are looping 5 times:
for (int i=0; i<5; i++){
if (fictionArray[i] != null){
Change it to 2. It's possible you changed the array length in the declaration, but forgot to change the loop iteration. In that case, you can just use the array's length:
for (int i = 0; i < fictionArray.length; i++) {
Additionally, it looks like you want to print out the specific array element, not the array itself:
System.out.println(fictionArray[i]);
and likewise for nonfictionarray and the nonfiction class.
Two things I see
if (fictionArray[i] != null){
System.out.println(fictionArray);}
if (nonfictionArray[i] != null){
System.out.println(nonfictionArray);}}
You're trying to print the entire array System.out.println(fictionArray). You probably want System.out.println(fictionArray[i])
Also you should set your array sizes to 5 if you want to loop 5 times
the question is :
A fruit shop sells several types of fruits each day. Write a program that reads from user several lines of input.Each line includes a fruit's name,price per kilogram (as an integer), number of kilograms sold (as an integer).
the program should calculate and print the earned money of all fruits sold and fruit that achieved largest profit.
hint: -you could assume that user will insert valid data -user could stop the program via entering the word "stop" as a fruit's name.
Sample input and out put:
in each line, insert a fruit's name, price per kilogram, number of kilograms sold. To halt the program,insert "stop" as a fruit's name
banana 2 11
mango 3 8
peach 4 5
stop
the earned money of all fruits sold: 66
fruit that achieved the largest profit: mango
what i wrote now:
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String fruitname= " ";
String maxfruit = " ";
int price = 0,number=0;
int sum=0;
int max=0;
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
while (!fruitname.equals("stop"))
{
fruitname = input.next();
price = input.nextInt();
number = input.nextInt();
}
if (fruitname.equals("stop"))
{
sum = sum+(price*number);
}
if (max<(price*number))
{
max = price*number;
maxfruit = fruitname;
}
System.out.println("the earned money of all fruits is " + sum);
System.out.println("fruit that achieved the largest profit is "+ maxfruit);
}
}
the program is not reading what i submit to it, don't know why and not giving me the sum and the max fruit.. what is the problem of what i wrote?
As you can see your reads happen in the while loop:
while (!fruitname.equals("stop"))
{
fruitname = input.next();
price = input.nextInt();
number = input.nextInt();
}
Every time it loops - it overrides the values. Finally when you read stop and exit the loop - your fruitname is stop. So you need to fix your logic on how you would want to read in the input
Working variant:
public class FruitTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
String text = input.nextLine();
String[] words = text.split(" ");
List<Fruit> fruits = parseInput(words);
int sum = getSum(fruits);
String popular = getPopularFruitName(fruits);
System.out.println("Got fruits: " + fruits.toString());
System.out.println("the earned money of all fruits is " + sum);
System.out.println("fruit that achieved the largest profit is " + popular);
}
private static String getPopularFruitName(List<Fruit> fruits) {
int max = 0;
String name = null;
for (Fruit fruit : fruits) {
int checkVal = fruit.getPrice() * fruit.getAmount();
if(checkVal > max) {
max = checkVal;
name = fruit.getName();
}
}
return name;
}
private static int getSum(List<Fruit> fruits) {
int result = 0;
for (Fruit fruit : fruits) {
result += fruit.getPrice() * fruit.getAmount();
}
return result;
}
private static List<Fruit> parseInput(String[] words) {
List<Fruit> result = new ArrayList<Fruit>();
int element = 1;
final int name = 1;
final int price = 2;
final int amount = 3;
Fruit fruit = null;
for (String word : words) {
if (word.equals("stop") || word.isEmpty()) {
break;
}
if(element > amount)
element = name;
switch (element) {
case name:
fruit = new Fruit(word);
result.add(fruit);
break;
case price:
if (fruit != null) {
fruit.setPrice(Integer.valueOf(word));
}
break;
case amount:
if(fruit != null) {
fruit.setAmount(Integer.valueOf(word));
}
break;
}
element++;
}
return result;
}
static class Fruit {
String name;
int price = 0;
int amount = 0;
Fruit(String name) {
this.name = name;
}
String getName() {
return name;
}
int getPrice() {
return price;
}
void setPrice(int price) {
this.price = price;
}
int getAmount() {
return amount;
}
void setAmount(int amount) {
this.amount = amount;
}
#Override
public String toString() {
return name + ". $" + price +
", amount=" + amount;
}
}
}
Comments to code - it's proper way to parse all the inputted string and parse it to an object that stores all the data - name, price and amount. Store all parsed objects into array or a list and then calculate max and popular fruit while looping your parsed fruit array
I found some mistake. The most important was in the while condition. Check this out.
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String fruitname = null;
String maxfruit = null;
int fruitSum = 0;
int totalSum = 0;
int max = 0;
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
while(!(fruitname = input.next()).equals("stop")){
fruitSum = input.nextInt() * input.nextInt();
totalSum += fruitSum;
if(fruitSum > max){
maxfruit = fruitname;
max = fruitSum;
}
}
System.out.println("the earned money of all fruits is " + totalSum);
System.out.println("fruit that achieved the largest profit is "+ maxfruit);
}
}
Oh it is reading it.
the problem is that it doesn't do what you want it to do.
the problems with the code I can see are this:
you are not storing the fruits quantities or prices anywhere, you need to store the values
in an array or something (maxFruit,MaxValue) to compare them later.
when you are reading the fruit values and a "stop" string is input the next step in your code is to wait for the price so it won't get out of the loop even if you input "stop", you need to restructure your scanner loop.
And if it is a beginner class it may be ok, but the code you are writing is not object oriented don't write the logic in the main.
You may want to learn to debug it is a very useful tool when you are learning to code, if you run this program in debug mode , you could see that the values are getting input and everything that is happening, Netbeans and Eclipse have very good debuggers and it would be worth to expend half an hour learning the basics of debugging It certainly helped me a lot when I was starting.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class FruitSells {
public static void main(String... args) {
BufferedReader bufer = new BufferedReader(new InputStreamReader(System.in));
try {
String str;
String[] inarr;
int sumMoney = 0;
do {
str = (String) bufer.readLine();
inarr = str.split(" ");
for(int i = 1; i < inarr.length; i += 3) {
sumMoney += Integer.parseInt(inarr[i]) * Integer.parseInt(inarr[i + 1]);
}
System.out.println(sumMoney);
sumMoney = 0;
} while (!str.equals("stop"));
} catch(IOException ex) {
System.out.println("Problems with bufer.readLine()");
}
}
}
something like this you can modernize it.sorry for eng i can not speak))and write correctly of course))