Iam developing a program to analyze the source code of programs. Now, I'm having a trouble counting results, here comes my source code:
public void walk(String path) throws FileNotFoundException {
File root = new File(path);
File[] list = root.listFiles();
int countFiles = 0;
if (list == null) {
return;
}
for (File f : list) {
if (f.isDirectory()) {
walk(f.getAbsolutePath());
}
if (f.getName().endsWith(".java")) {
System.out.println("File:" + f.getName());
countFiles++;
Scanner sc = new Scanner(f);
int count = 0;
while (sc.hasNextLine()) {
count++;
sc.nextLine();
}
Scanner sc2 = new Scanner(f);
int lower = 0;
int upper = 0;
int digit = 0;
int whiteSpace = 0;
while (sc2.hasNextLine()) {
String str = sc2.nextLine();
for (int i = 0; i < str.length(); i++) {
if (Character.isLowerCase(str.charAt(i))) {
lower++;
} else if (Character.isUpperCase(str.charAt(i))) {
upper++;
} else if (Character.isDigit(str.charAt(i))) {
digit++;
} else if (Character.isWhitespace(str.charAt(i))) {
whiteSpace++;
}
}
}
System.out.println("Your code contains: " + count + " Lines!, Out of them:");
System.out.println("lower case: " + lower);
System.out.println("upper case: " + upper);
System.out.println("Digits: " + digit);
System.out.println("White Spaces: " + whiteSpace);
}
System.out.println("You have in total: " + countFiles);
}
}
First question: when it comes to countFiles ( which is supposed to tell how many .java files or classes you have in your code) its counting and printing results like the following:
you have in total= 1 file
you have in total= 2 file
so how can i make it to print me the final result directly which is 2 in this case ?
Second question: how can I print the sum of the lines in the code in totally, instead of showing them for each class by it self?
Thanks
it has been solved by adding an if statment outside the for loop as the following:
if(!(countFiles<=0) ){
System.out.println("You have in total: " + countFiles);
}
You're printing the result of countFiles for every java file (it is inside your loop). To print the final results, you need only print out countFiles after you've passed them all.
So simply move the statement outside the loop.
public void walk(String path) throws FileNotFoundException {
// ...
int countFiles = 0;
// ...
for (File f : list) {
// ...
if (f.getName().endsWith(".java")) {
// ...
}
// System.out.println("You have in total: " + countFiles);
}
System.out.println("You have in total: " + countFiles);
}
The answer to your second question is really the same. Move the statements outside the loop.
public void walk(String path) throws FileNotFoundException {
// ...
int countFiles = 0;
// ...
int count = 0;
int lower = 0;
int upper = 0;
int digit = 0;
int whiteSpace = 0;
for (File f : list) {
// ...
// int count = 0;
// int lower = 0;
// int upper = 0;
// int digit = 0;
// int whiteSpace = 0;
if (f.getName().endsWith(".java")) {
// ...
}
// System.out.println("You have in total: " + countFiles);
}
System.out.println("You have in total: " + countFiles);
System.out.println("Your code contains: " + count + " Lines!, Out of them:");
System.out.println("lower case: " + lower);
System.out.println("upper case: " + upper);
System.out.println("Digits: " + digit);
System.out.println("White Spaces: " + whiteSpace);
}
Note that I moved the counters out of the loop because keeping track of results between loop passes requires that I have variables in the scope outside the code block.
Related
Have a task to get N numbers from console, find the longest and the shortest ones and their length. The task is not difficult and works correctly, but I decided to make a check, if the console input corresponds the conditions of the task:
Are there only Integer numbers.
Are the exactly N numbers, not more/less.
I decided to write a boolean method isInputCorrect(), which would take the Scanner and check if the input is correct, but it doesn't work correctly.
public static void main(String[] args) {
int n = 5;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Hello, please enter " + n + " integer numbers:");
while (!isInputCorrect(sc,n)){
System.out.println("Wrong! Try again:");
sc.next();
}
} while (!isInputCorrect(sc, 5));
String scLine = sc.nextLine();
String[] arr = scLine.split("\\s+");
String maxLengthNum = arr[0];
String minLengthNum = arr[0];
for (int i = 1; i < arr.length; i++){
if (maxLengthNum.length() < arr[i].length()){
maxLengthNum = arr[i];
}
if (minLengthNum.length() > arr[i].length()){
minLengthNum = arr[i];
}
}
String equalMaxNum = "";
String equalMinNum = "";
int countMax = 0;
int countMin = 0;
for (String s : arr){
if (maxLengthNum.length() == s.length()){
countMax += 1;
equalMaxNum += s + " ";
}
if (minLengthNum.length() == s.length()){
countMin += 1;
equalMinNum += s + " ";
}
}
if (countMax > 1){
System.out.println("The longest numbers are: " + equalMaxNum + " Their length is: " + maxLengthNum.length());
}
else {
System.out.println("The longest number is: " + maxLengthNum + " Its length is: " + maxLengthNum.length());
}
if (countMin > 1){
System.out.println("The shortest numbers are: " + equalMinNum + " Their length is: " + minLengthNum.length());
}
else {
System.out.println("The shortest number is: " + minLengthNum + " Its length is: " + minLengthNum.length());
}
}
public static boolean isInputCorrect(Scanner sc, int n){
boolean flag = true;
for (int i = 0; i < n; i++){
if (sc.hasNextInt()){
sc.next();
}else {
flag = false;
break;
}
}
return flag;
}
EDIT
This code still doesn't work. I realize, that the problem is in isDigit(). And exactly in regular conditions in last if statement. It is something like this:
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else {
for (String s : arr) {
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")) {
flag = true;
}
} else if (s.matches("[0-9]*")) {
flag = true;
} else {
flag = false;
}
}
}
return flag;
}
This method takes the console input as a string, then it checks, how many numbers(strings) does it contain, are there any negative numbers and so on. But it can be applied only for substrings(words without whitespace). In my case it can be applied to arr[i].
So I modified it to split String into array[] and tried to check every single element. I've got:
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else {
for (String s : arr) {
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")) {
flag = true;
}
} else if (s.matches("[0-9]*")) {
flag = true;
} else {
flag = false;
}
}
}
return flag;
}
but it returnes true even when input is:
1 3213 w 15 3
I can't understand, what is the problem? The full code is:
public static void main(String[] args) {
int n = 5;
boolean validInput = false;
String input;
do {
System.out.println("Please enter " + n + " integer numbers:");
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
if (isDigit(input, n)) {
validInput = true;
} else {
System.out.println("Wrong input! Try again: ");
}
}
while (!validInput);
String[] arr = input.split("\\s+");
String maxLengthNum = arr[0];
String minLengthNum = arr[0];
for (int i = 1; i < arr.length; i++){
if (maxLengthNum.length() < arr[i].length()){
maxLengthNum = arr[i];
}
if (minLengthNum.length() > arr[i].length()){
minLengthNum = arr[i];
}
}
String equalMaxNum = "";
String equalMinNum = "";
int countMax = 0;
int countMin = 0;
for (String s : arr){
if (maxLengthNum.length() == s.length()){
countMax += 1;
equalMaxNum += s + " ";
}
if (minLengthNum.length() == s.length()){
countMin += 1;
equalMinNum += s + " ";
}
}
if (countMax > 1){
System.out.println("The longest numbers are: " + equalMaxNum + " Their length is: " + maxLengthNum.length());
}
else {
System.out.println("The longest number is: " + maxLengthNum + " Its length is: " + maxLengthNum.length());
}
if (countMin > 1){
System.out.println("The shortest numbers are: " + equalMinNum + " Their length is: " + minLengthNum.length());
}
else {
System.out.println("The shortest number is: " + minLengthNum + " Its length is: " + minLengthNum.length());
}
}
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else {
for (String s : arr) {
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")) {
flag = true;
}
} else if (s.matches("[0-9]*")) {
flag = true;
} else {
flag = false;
}
}
}
return flag;
}
SOLVED
Thanks to everybody, your help was really usefull. I finally found the problem
It was in isDigit() method. It was checking out every element of array, and switched a flag according to the last result. I wrote "break" to stop the further checking if there was at least one false flag in loop.
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else{
for (String s: arr){
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")){
flag = true;
}
else {
flag = false;
break;
}
}
else {
if (s.matches("[0-9]*")){
flag = true;
}
else {
flag = false;
break;
}
}
}
}
return flag;
}
You may use regular expressions to verify that the input contains only integer numbers:
int n = 5;
// ... your current code
String scLine = sc.nextLine();
if (!scLine.matches("\\d+(?:\\s+\\d+)*")) {
throw new IllegalArgumentException("input contained non-integers");
}
String[] arr = scLine.split("\\s+");
if (arr.length != n) {
throw new IllegalArgumentException("found " + arr.length + " number inputs but expected " + n + ".");
}
you can check if input string has only numbers as below
public boolean isDigit(String input) {
if (input == null || input.length() < 0)
return false;
input = input.trim();
if ("".equals(input))
return false;
if (input.startsWith("-")) {
return input.substring(1).matches("[0-9]*");
} else {
return input.matches("[0-9]*");
}
}
EDIT:
allowing user to re-enter untill valid number is entered
boolean validInput = false;
do
{
System.out.println("Enter the number ");
// get user input
String input sc.nextLine();
if(isDigit(input))
validInput = true;
else
System.out.println("Enter valid Number");
}
while (!validInput );
I am stuck at a part where I am supposed to declare a string variable called "phrase", where it shouldn't loop, all the way through.
to give you an idea my task is: Similar to Option 1 except the user enters 'N' (instead of 'Q') when they are done entering results for the first team. Then, the program inputs a second team name and its results until 'Q' is entered. Outputs two statements, like the statements in option 1 followed by a third statement that says which team is in first place (based on the number of points)
Sample input:
2
Toronto
W
W
L
O
W
O
W
N
Montreal // how would I make this appear in the same while loop?
L
L
O
L
L
W
L
L
Q
Sample output:
Toronto has played 7 games and has earned 10 points
Montreal has played 8 games and has earned 3 points
Toronto is in first place by 7 points
UPDATE:
My code:
else if (option == 2){
int counter = 0;
int totalpoints = 0;
String phrase = keyboard.next();
while(go){
String letter = keyboard.next();
if (letter.equals("W")){
pointsW++;
}
else if (letter.equals("L")){
pointsL++;
}
else if (letter.equals("O")){
pointsO++;
}
counter++;
if (letter.equals("N")){
totalpoints = pointsW + pointsL + pointsO;
counter--;
go = false;
}
}
int counter2 = 0;
int totalpoints2 = 0;
pointsW = 2;
pointsL = 0;
pointsO = 1;
String phrase2 = keyboard.next();
while (go2){
String letter2 = keyboard.next();
if (letter2.equals("W")){
pointsW++;
}
else if (letter2.equals("L")){
pointsL++;
}
else if (letter2.equals("O")){
pointsO++;
}
counter2++;
if (letter2.equals("Q")){
counter2--;
totalpoints2 = pointsW + pointsL + pointsO;
go2 = false;
}
}
System.out.println(phrase + " has played "+counter+" games and has earned "+totalpoints+" points");
System.out.println(phrase2 + " has played "+counter2+" games and has earned "+totalpoints2+" points");
if (totalpoints > totalpoints2){
System.out.println(phrase + " is in first place by "+(totalpoints - totalpoints2) + " points");
}else{
System.out.println(phrase2 + " is in first place by "+(totalpoints2 - totalpoints) + " points");
}
}
Sample input:
2
Toronto
W
W
L
O
W
O
W
N
Montreal
L
L
O
L
L
W
L
L
Q
The issue: This is the output I am getting "Montreal played 8 games and has earned 11 points" where instead it should be "Montreal has played 8 games and has earned 3 points"
The output I am getting
You can reuse the same variables for individual points i.e. pointsW and pointsO because you do not want to retain their values till the end where you are publishing the results. The same is the case with the variable for the loop condition i.e. go and the variable used for inputting win/loss i.e. letter.
You will need arrays or different variables for storing total points, countings, and team name.
import java.util.Scanner;
public class Standings {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int option = keyboard.nextInt();
int pointsW = 0;
int pointsO = 0;
String letter;
boolean go = true;
if (option == 2) {
// Variables for total points, counting, and name for the first team
int playedGamesTeamOne = 0;
int teamOnePoints = 0;
String teamOneName = keyboard.next();
while (go) {
letter = keyboard.next();
if (letter.equals("W")) {
pointsW += 2;
} else if (letter.equals("O")) {
pointsO++;
}
playedGamesTeamOne++;
if (letter.equals("N")) {
teamOnePoints = pointsW + pointsO;
playedGamesTeamOne--;
go = false;
}
}
// Reset common variables
go = true;
pointsW = 0;
pointsO = 0;
// Variables for total points, counting, and name for the second team
int playedGamesTeamTwo = 0;
int teamTwoPoints = 0;
String teamTwoName = keyboard.next();
while (go) {
letter = keyboard.next();
if (letter.equals("W")) {
pointsW += 2;
} else if (letter.equals("O")) {
pointsO++;
}
playedGamesTeamTwo++;
if (letter.equals("Q")) {
teamTwoPoints = pointsW + pointsO;
playedGamesTeamTwo--;
go = false;
}
}
System.out.println(teamOneName + " has played " + playedGamesTeamOne + " games and has earned "
+ teamOnePoints + " points");
System.out.println(teamTwoName + " has played " + playedGamesTeamTwo + " games and has earned "
+ teamTwoPoints + " points");
if (teamOnePoints > teamTwoPoints) {
System.out
.println(teamOneName + " is in first place by " + (teamOnePoints - teamTwoPoints) + " points");
} else {
System.out
.println(teamTwoName + " is in first place by " + (teamTwoPoints - teamOnePoints) + " points");
}
}
}
}
A sample run:
2
Toronto
W
W
L
O
W
O
W
N
Montreal
L
L
O
L
L
W
L
L
Q
Toronto has played 7 games and has earned 10 points
Montreal has played 8 games and has earned 3 points
Toronto is in first place by 7 points
you can use this code for option two
Scanner keyboard = new Scanner(System.in);
int teamCounter = 1;
//String[] teamsNames = new String[2];
String teamOneName="";
String teamTwoName="";
//int[] playedGames = new int[2];
int playedGamesTeamOne = 0;
int playedGamesTeamTwo = 0;
//int[] points = new int[2];
int teamOnePoints = 0;
int teamTwoPoints = 0;
boolean firstTimeTeam1 = true;
boolean firstTimeTeam2 = true;
while (teamCounter <= 2) {
if (teamCounter == 1) {
if (firstTimeTeam1) {
teamOneName = keyboard.nextLine();
firstTimeTeam1 = false;
}
String letter = keyboard.next();
if (letter.equals("W")) {
teamOnePoints += 2;
playedGamesTeamOne++;
} else if (letter.equals("L")) {
playedGamesTeamOne++;
} else if (letter.equals("O")) {
teamOnePoints += 1;
playedGamesTeamOne++;
} else if (letter.equals("N")) {
teamCounter++;
}
} else {
if (firstTimeTeam2) {
teamTwoName = keyboard.next();
firstTimeTeam2 = false;
}
String letter = keyboard.next();
if (letter.equals("W")) {
teamTwoPoints += 2;
playedGamesTeamTwo++;
} else if (letter.equals("L")) {
playedGamesTeamTwo++;
} else if (letter.equals("O")) {
teamTwoPoints += 1;
playedGamesTeamTwo++;
} else if (letter.equals("Q")) {
teamCounter++;
}
}
}
System.out.println(teamOneName + " has played " + playedGamesTeamOne + " games and has earned " + teamOnePoints + " points");
System.out.println(teamTwoName + " has played " + playedGamesTeamTwo + " games and has earned " + teamTwoPoints + " points");
if (teamOnePoints > teamTwoPoints) {
System.out.println(teamOneName + " is in first place by " + (teamOnePoints-teamTwoPoints) + " points");
} else {
System.out.println(teamTwoName + " is in first place by " + (teamTwoPoints-teamOnePoints) + " points");
}
New to programming here. I need to write application that does the following...
Squaring application instructions
The code I have so far follows. I am running into a problem where my code will not read from negative integers to strings and properly prompt the user to enter valid data. I believe I need to nest my loops but am having trouble doing so. Any help would be greatly appreciated. Thanks.
import java.util.Scanner;
public class Squaring {
public static int getValidInt(int greaterThan, Scanner scan) {
System.out.println("Enter an integer greater than " + greaterThan + ":" );
int input;
while ( !scan.hasNextInt() ) {
String garbage = scan.next();
scan.nextLine();
System.out.println(garbage + " is not valid input.");
System.out.println("Enter an integer greater than " + greaterThan + ":" );
}
while ( !((input = scan.nextInt()) > greaterThan )) {
int garbage = input;
System.out.println(garbage + " is not greater than 1.");
System.out.println("Enter an integer greater than " + greaterThan + ":" );
}
return input;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = 1 ;
int total = 0;
a = getValidInt(a,scan);
int b = a;
System.out.println(a);
long n = a;
while ( n < 1000000 ) {
System.out.println(n*n);
n = n * n;
total = total + 1;
}
System.out.println(b + " exceeded 1,000,000 after " + total + " squarings.") ;
}
}
Without any try-catch:
public static int getValidInt(int greaterThan, Scanner scan) {
int input = 0;
boolean valid = false;
while (!valid) {
System.out.println("Enter an integer greater than " + greaterThan + ":");
if (!scan.hasNextInt()) {
String garbage = scan.next();
System.out.println(garbage + " is not valid input.");
} else {
input = scan.nextInt();
if (input <= greaterThan) {
System.out.println(input + " is not greater than " + greaterThan);
} else {
valid = true;
}
}
}
return input;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = getValidInt(1, scan);
System.out.println(a);
int total = 0;
long n = a;
while ( n < 1000000 ) {
n = n * n;
System.out.println(n);
total++;
}
System.out.println(a + " exceeded 1,000,000 after " + total + " squarings.") ;
}
I've come up with the following:
public static int getValidInt(int greaterThan, Scanner scan) {
int number = greaterThan;
do {
while (!scan.hasNextInt()) {
String garbage = scan.next();
System.out.println(garbage + " is not valid input.");
}
number = scan.nextInt();
if (number < greaterThan) {
System.out.println("input is: " + number + " minimum is: " + greaterThan);
}
} while (number < greaterThan);
return number;
}
It has a do while loop which makes sure number cannot be smaller than greaterThan, if it is it will do the while loop again.
Inside the do while loop is another loop which tells the user that their input is garbage, and will continue doing so until a number is inserted.
I have to read in a file to my project and then read the file line by line to find the percent of upper case and lower case letters. My output should be 4 lines stating the percent of upper and lower for that specific line in the file. This is what I have to far but it doesn't quite work:
Scanner inFile = new Scanner(new File("file.txt"));
int upper = 0;
int lower = 0;
int total;
double percentU = 0.0;
double percentL = 0.0;
while (inFile.hasNext()) {
String line = inFile.nextLine();
for (int x = 0; x < line.length(); x++)
{
if (Character.isUpperCase(line.charAt(x)))
{
upper++;
}
if (Character.isLowerCase(line.charAt(x)))
{
lower++;
}
total = upper + lower;
percentU = upper/total;
percentL = lower/total;
System.out.println("lowercase: " + String.format("%.2f", percentL) + "\t" + "uppercase: " + String.format("%.2f", percentU));
}
}
When you divide an int by another int the result will be also an int. So for example if you divide 30 by 50 the result will be 0 instead of 0.6.
More information:
How to make the division of 2 ints produce a float instead of another int?
Integer division: How do you produce a double?
Division of integers in Java
I Just change these lines removed if (Character.isLowerCase(line.charAt(x))):
if (Character.isUpperCase(line.charAt(x))) {
upper++;
}
if (Character.isLowerCase(line.charAt(x))) {
lower++;
}
To:
if (Character.isUpperCase(line.charAt(x))) {
upper++;
} else {
lower++;
}
And moved these lines out of while loop:
total = upper + lower;
percentU = (float)upper/total;
percentL = (float)lower/total;
System.out.println("total: " + total);
System.out.println("lowercase: " + String.format("%.2f", percentL) + "\t" + "uppercase: " + String.format("%.2f", percentU));
Try this solution it's ok:
public static void main(String[] args) {
Scanner inFile = null;
int upper = 0;
int lower = 0;
int total = 0;
double percentU = 0.0;
double percentL = 0.0;
try {
inFile = new Scanner(new File("C:\\temp\\file.txt"));
while (inFile.hasNext()) {
String line = inFile.nextLine();
for (int x = 0; x < line.length(); x++) {
if (Character.isUpperCase(line.charAt(x))) {
upper++;
} else {
lower++;
}
}
}
total = upper + lower;
percentU = (float)upper/total;
percentL = (float)lower/total;
System.out.println("total: " + total);
System.out.println("lowercase: " + String.format("%.2f", percentL) + "\t" + "uppercase: " + String.format("%.2f", percentU));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
my code (reads a text file, uses a class I built to sort through the data, and then outputs onto console), is not printing anything! Can somebody please tell me where my little mistake is! I know the VERY end is not finished yet. Please help!!!!!!!!
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Project02 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Product> products = new ArrayList<Product>();
// Enter file name
System.out.print("Enter database file name: ");
String fileName = in.nextLine();
try {
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
System.out.println();
while (inputFile.hasNext()) {
Product p = new Product();
String title = inputFile.nextLine();
String code = inputFile.nextLine();
Integer quantity = inputFile.nextInt();
Double price = inputFile.nextDouble();
inputFile.nextLine();
String type = inputFile.nextLine();
Integer userReview = inputFile.nextInt();
// read in title
p.setName(title);
// read in iCode
p.setInventoryCode(code);
// read in quantity
p.setQuantity(quantity);
// read in price
p.setPrice(price);
// read in type
p.setType(type);
// read in user reviews
while (!userReview.equals(-1)) {
p.addUserRating(userReview);
userReview = inputFile.nextInt();
}
if (inputFile.hasNext()) {
inputFile.nextLine();
}
}
inputFile.close();
} catch (IOException e) {
System.out.println("There was an error reading from " + fileName);
}
}
private static String highRating(ArrayList<Product> p) {
int highestR = 0;
int indexOfHighestR = 0;
for (int i = 0; i < p.size(); i++) {
int rating = p.get(i).getAvgUserRating();
if (p.get(i).getAvgUserRating() > highestR) {
highestR = p.get(i).getAvgUserRating();
indexOfHighestR = i;
}
}
int zero = 0;
String Star = " ";
while (highestR > zero) {
Star = Star + "*";
zero--;
}
String highestRateTitle = p.get(indexOfHighestR).getName() + " ("
+ Star + ")";
return highestRateTitle;
}
private static String lowestRating(ArrayList<Product> p) {
int lowestR = 0;
int indexOfLowestR = 0;
for (int i = 0; i < p.size(); i++) {
int rating = p.get(i).getAvgUserRating();
if (p.get(i).getAvgUserRating() < lowestR) {
lowestR = p.get(i).getAvgUserRating();
indexOfLowestR = i;
}
}
int zero = 0;
String Star = " ";
while (lowestR > zero) {
Star = Star + "*";
zero--;
}
String highestRateTitle = p.get(indexOfLowestR).getName() + " ("
+ Star + ")";
return highestRateTitle;
}
private static double maxDollar(ArrayList<Product> p) {
double largestP = 0;
int indexOfLargestP = 0;
for (int i = 0; i < p.size(); i++) {
double price = p.get(i).getPrice();
if (p.get(i).getPrice() > largestP) {
largestP = p.get(i).getPrice();
indexOfLargestP = i;
}
}
return largestP;
}
private static int minDollar(ArrayList<Product> p) {
double smallestP = p.get(0).getPrice();
int indexOfSmallestP = 0;
for (int i = 0; i < p.size(); i++) {
if (p.get(i).getPrice() < smallestP) {
smallestP = p.get(i).getPrice();
indexOfSmallestP = i;
}
}
return indexOfSmallestP;
}
private static void inventoryList(ArrayList<Product> p) {
int count =
System.out.println("Product Summary Report: ");
System.out
.println("------------------------------------------------------------");
for (int i = 0; i < count; i++) {
System.out.println("Title: " + p.get(i).getName());
System.out.println("I Code: " + p.get(i).getInventoryCode());
System.out.println("Product Type: " + p.get(i).getType());
System.out.println("Rating: " + p.get(i).getAvgUserRating());
System.out.println("# Rat.: " + p.get(i).getUserRatingCount());
System.out.println("Quantity: " + p.get(i).getQuantity());
System.out.println("Price: " + p.get(i).getPrice());
System.out.println();
}
System.out
.println("-----------------------------------------------------------------");
// System.out.println("Total products in database: " + count);
System.out.println("Highest total dollar item: "
+ p.get(maxDollar(p)) + " ($"+ p.(maxDollar(p)) + ")");
System.out.println("Smallest quantity item: "
+ p.get(minQuantity(quantities)) + " ("
+ types.get(minQuantity(quantities)) + ")");
System.out.println("Lowest total dollar item: "
+ titles.get(minDollar(prices)) + " ($"
+ prices.get(minDollar(prices)) + ")");
System.out
.println("-----------------------------------------------------------------");
}
First...
After you've create an instance of Product, p, you will need to add it to the products list, otherwise you will lose it's reference and won't be able to use it again...
while (inputFile.hasNext()) {
Product p = new Product();
//...
products.add(p);
if (inputFile.hasNext()) {
inputFile.nextLine();
}
}
Second...
You will need to pass the products List to something that want's to use/display the information, for example inventoryList...
But wait, that's not working?
If we take a closer look at the the inventoryList method...
int count = 0;
//...
for (int i = 0; i < count; i++) {
We can see that count is always 0, so it will never print anything! You should be using p.size() instead, which is the actually length of the products List
//...
for (int i = 0; i < p.size(); i++) {