I would like to sort a list (from a text file "sales.txt")that has text, int and float values. The problem I have is, my output only produces the last set of values. I would like to produce a table with as the final output. Please help me.

public class Sales {

static String name;       // Used for reading salesperson's name
static int sales;         // Used for reading sales
static int sumSales;      // Total sales
static float expenses;    // Used for reading expenses
static float sumExpenses; // Total expenses
static float salesPer;    // Sales as a percentage of total sales
static float expensesPer; // Expenses as a percentage of total expenses
// Variables used to create output table
static String A = "\n|--------------------------------------------------------------|";
static String B = "\n|                         SALES REPORT                         |";
static String C = "\n|        NAME        |     Total Sales    |    Total Expenses  |";
static String D = "|                    |";

// Scanner based constructor
public Sales(Scanner inFile) {
while (inFile.hasNext()) {                // Loops for text values
name = inFile.nextLine();                 // Takes text string value
while (inFile.hasNextInt()) {             // Loops for int/float values
sales = inFile.nextInt();                 // Takes int value
expenses = inFile.nextFloat();            // Takes float value
sumSales += sales;                        // Sum all sales values
sumExpenses += expenses;                  // Sum all expenses values
salesPer = (sales*100)/(float)sumSales;   // Calculates percentage of total sales
expensesPer = (expenses*100)/sumExpenses; // Calculates percentage of total expenses
}
}
}

// Returns formatted output for printing
public String toString() {
return A + B + A + C + '\n' + D + "       " + "$" + sumSales + "      |      "
+ "$" + sumExpenses + "     |" + A + "\n| " + name + "        |       %" + salesPer
+  "      |       %" + expensesPer + "       |" + A;
}

// Begin execution here - the driver
public static void main(String[] args) throws IOException {
Scanner inFile = new Scanner(new FileReader("sales.txt"));   // Set scanner to read file
Sales output = new Sales(inFile); // Renews sales class to print toString results

// Associated with the sales text file
System.out.println('\n' + output.toString());
}
}

my output only produces the last set of values.

How does the posted code relate to the problem with sorting and outputting only the last set of values?

Where does the program save any values at all except for the last ones read?
You need to save the all the data if you want it available later in the program to print it out.

Ouch Norm1! I feel I am being chastised for asking the question. I need help doing just what you are suggesting. You have helped me in the past and believe me when I tell you I am learing as I am very new to the subject.

When I use the "for" loop which in essence would store the values in question it does not work for me. I thought the code lines...

for (index = 0; index < inFile; index++)

I also am trying to perhaps assign the read information of the file to an array and perhaps use the "for" loop in this way, but that strategy does not appear to be a working solution either. I can't seem to use the inFile variable with anything other than a "while" loop and thus your question back to me I suppose. InFile being the variable given to the text file being read returns all kinds of mismatch and incompatibility errors. The text file has int, float and text values I want to sort. Please I need a way how?

Ouch Norm1! I feel I am being chastised for asking the question. I need help doing just what you are suggesting. You have helped me in the past and believe me when I tell you I am learing as I am very new to the subject.

When I use the "for" loop which in essence would store the values in question it does not work for me. I thought the code lines...

for (index = 0; index < inFile; index++)

I also am trying to perhaps assign the read information of the file to an array and perhaps use the "for" loop in this way, but that strategy does not appear to be a working solution either. I can't seem to use the inFile variable with anything other than a "while" loop and thus your question back to me I suppose. InFile being the variable given to the text file being read returns all kinds of mismatch and incompatibility errors. The text file has int, float and text values I want to sort. Please I need a way how?

Hi mate - everything in the .txt file is stored as a String right therefore you need to treat the file like a string. You can use this:

myString.contains( "value to look for" );

I created a program that essentially looks for certain values in the file and prints it's line number too. In order to sort it out you would just need to add it to an array of that type - following conversion.

Maybe this will help you out too?

BufferedReader myFile = new BufferedReader( new FileReader( fileToReadFrom ) );
			String str;
			
			while( ( str =  myFile.readLine() ) != null )
			{
					lineCount++;
					if( str.contains("1") )
					{
						System.out.println( str+" at Line "+lineCount );
					}
			}
			
			
			myFile.close();

Does this help you?

Hi mate - everything in the .txt file is stored as a String right therefore you need to treat the file like a string. You can use this:

myString.contains( "value to look for" );

I created a program that essentially looks for certain values in the file and prints it's line number too. In order to sort it out you would just need to add it to an array of that type - following conversion.

Maybe this will help you out too?

BufferedReader myFile = new BufferedReader( new FileReader( fileToReadFrom ) );
			String str;
			
			while( ( str =  myFile.readLine() ) != null )
			{
					lineCount++;
					if( str.contains("1") )
					{
						System.out.println( str+" at Line "+lineCount );
					}
			}
			
			
			myFile.close();

Does this help you?

Thanks Katana24, conceptually this is what I am looking for but it stops short of printing continuous values. If you look at my code thus far, it does some work to the values and output its results. Basically, the file has a name in one line and the next line has a set of numbers, one int and the other float. My job is to take this information, total all the int and total all the float and print out the percentage of each value of the total along with the corresponding name. I know the calculations is doing its job and that a table of result is imminent because I get the last value which read... Petz Edz 13.9% 6.2%

If I take the text file and sort using excel I get a sense of what the table should look like. I just need to print all the results and instead my program is printing just one line. Thanks for additional help if you have it.

Thanks Katana24, conceptually this is what I am looking for but it stops short of printing continuous values. If you look at my code thus far, it does some work to the values and output its results. Basically, the file has a name in one line and the next line has a set of numbers, one int and the other float. My job is to take this information, total all the int and total all the float and print out the percentage of each value of the total along with the corresponding name. I know the calculations is doing its job and that a table of result is imminent because I get the last value which read... Petz Edz 13.9% 6.2%

If I take the text file and sort using excel I get a sense of what the table should look like. I just need to print all the results and instead my program is printing just one line. Thanks for additional help if you have it.

I had a deeper look at your program and I got it figured it out - i hope:
Basically what you need to do is to split the string read by the while loop which i posted before this, then you pass the results into an array of type string and then check each array value individually to determine whether or not its an integer or a float - assuming that they are the only number types in the file, and then add them to their respective total variables.

I have included some example code which only does the job for the integers in the file, as well as the file itself:

BufferedReader myFile = new BufferedReader( new FileReader( fileToReadFrom ) );
			String str;
			
			
			while( ( str =  myFile.readLine() ) != null )
			{
					lineCount++;
					
					if( lineCount == 1 )
					{
						System.out.println( "File Name - "+str );
					}
					
					String[] array = str.split(" ");
					
					for( int j = 0; j < array.length; j++ )
					{
						/**
						 * Used to print the results of the array - I used this to make
						 * sure the array was getting its values
						 */
						// System.out.println( array[j] );
						
						try {
							
							/**
							 * Convert the string to an integer, if you can
							 */
						    int x = Integer.parseInt( array[j] );
						    totalInt += x;
						    
							}
						
						catch(NumberFormatException nFE) 
						{
							/**
							 * Your respective error message here - to inform you 
							 * if the string isn't an integer
							 */
						    // System.out.println("Not an Integer");
						}			
					}
					
			}
			

		    System.out.println( "Total of integers: "+totalInt );
		    System.out.println( fileToReadFrom+" contain's "+lineCount+" lines" );
			
		    myFile.close();

The file I used contents was:

sortFile
1 1.5
2 2.5
3 3.5
4 4.5
5 5.5

Hope this helps

Forgot the output:

File Name - sortFile
Total of integers: 15
sortFile.txt contain's 6 lines

I had a deeper look at your program and I got it figured it out - i hope:
Basically what you need to do is to split the string read by the while loop which i posted before this, then you pass the results into an array of type string and then check each array value individually to determine whether or not its an integer or a float - assuming that they are the only number types in the file, and then add them to their respective total variables.

I have included some example code which only does the job for the integers in the file, as well as the file itself:

BufferedReader myFile = new BufferedReader( new FileReader( fileToReadFrom ) );
			String str;
			
			
			while( ( str =  myFile.readLine() ) != null )
			{
					lineCount++;
					
					if( lineCount == 1 )
					{
						System.out.println( "File Name - "+str );
					}
					
					String[] array = str.split(" ");
					
					for( int j = 0; j < array.length; j++ )
					{
						/**
						 * Used to print the results of the array - I used this to make
						 * sure the array was getting its values
						 */
						// System.out.println( array[j] );
						
						try {
							
							/**
							 * Convert the string to an integer, if you can
							 */
						    int x = Integer.parseInt( array[j] );
						    totalInt += x;
						    
							}
						
						catch(NumberFormatException nFE) 
						{
							/**
							 * Your respective error message here - to inform you 
							 * if the string isn't an integer
							 */
						    // System.out.println("Not an Integer");
						}			
					}
					
			}
			

		    System.out.println( "Total of integers: "+totalInt );
		    System.out.println( fileToReadFrom+" contain's "+lineCount+" lines" );
			
		    myFile.close();

The file I used contents was:

sortFile
1 1.5
2 2.5
3 3.5
4 4.5
5 5.5

Hope this helps

Thanks again Katana24, I will give your suggestion a try and report back. Please note my text has a mixture of text, integers and float integers looks like the following:

Doe John
25 13.45
Jane Mary
312 245.17
Brown Alex
17 11.9

and so on. My sorting requirement is to sort by text (last name e.g.: Brown) with the corresponding integers. I note with all my efforts my file errors out after the first read because the next line sees an integer and not a string (just my assumption). I also note you are suggesting a Bufferred reader method...I opted for the Scanner since it has distinct methods for text and numbers (e.g.: nextLine() and nextInt() and nextFloat()) which are the types of data in the text. Am I doing something wrong??

Thanks very much.

Forgot the output:

File Name - sortFile
Total of integers: 15
sortFile.txt contain's 6 lines

As promised, I said I would write back on how your suggestion worked with my file. My file essentially has 3 types of data, text string, integers and floats. While the output produced a single line of the results I was expected, I note that all the floats were ignored. I tried the code below but it does not work and instead I get "possible loss of precisions" error.

for (float k = 0; k < array.length; k++)
float y = Float.parseFloat(array[k]); // Here I get a precision error and does not compute
totalFloat += y;

Why does it not work...please help.

Thanks,
Jems

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.