Using imported data Java - java

I'm just learning to use File I/O and struggling to figure out how to use the data. For example, I have a .txt file that is setup with a name and list of scores that apply to that name, each list ending with a -1. I have successfully imported the file and was able to print it on the console but I need to add this information to an ArrayList so I can sort it, find the high and low, and the average and median. When I attempt to enter the data into an ArrayList I get a Exception I don't know how to handle. Here is the code I have so far, any help would be appreciated.
public static void main(String[] args) throws IOException {
File file = new File("Project11input.txt");
Scanner inFile = new Scanner(file);
ArrayList<Integer> TerryCrews = readNextSeries(inFile);
int median = getMedian(TerryCrews);
System.out.println("The median is " + median);
int average = getAverage(TerryCrews);
System.out.println("The average is " + average);
}
private static ArrayList<Integer> readNextSeries(Scanner inScanner) {
ArrayList<Integer> Input = new ArrayList<Integer>();
int thesex = 0;
while(thesex >= 0){
thesex = inScanner.nextInt();
Input.add(thesex);
}
System.out.println("End of input");
return Input;}
private static int getMedian(ArrayList<Integer> inList) {
int last = 0;
int power = (inList.size()/2) - 1;
int pow=0;
int ful = power+1;
int wap =0;
int onetwo = inList.size()%2;
if(onetwo == 1){
last = inList.get(ful);}
else{
pow = inList.get(power);
wap = inList.get(ful);
last = (pow + wap);
last=last/2;
}
return last; }
to clarify, I basically need the numbers in the File "file" to be in an ArrayList so they can be used.

Related

read lines from external file and store elements in array

I am new here so please show some patience. I am trying to read the data from an external file and store the info in 2 arrays.
The file looks like this:
0069 723.50
0085 1500.00
0091 8237.31
I am using 2 scanners to read the input and I think they work ok because when I try to print, the result looks ok.
My first problem is that I am able to read the first numbers on the list using nextInt(), but cannot use nextDouble() for the double ones as I get the "java.util.InputMismatchException" message. For that reason I read it as a String. The part with the other two scanners is supposed to do what the first parts should do, for a different input file, but the problem is the same.
My next and biggest problem, until now, is that am not able to store the values from the two columns in two distinct arrays. I have tried several ways (all commented) but all fail. Please help and thanks.
Here is my code:
import ui.UserInterfaceFactory;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Scanner;
import ui.UIAuxiliaryMethods;
public class Bank {
static final int MAX_NUMBER_OF_ACCOUNTS = 50;
PrintStream out;
Bank(){
UserInterfaceFactory.enableLowResolution(true);
out = new PrintStream(System.out);
}
void readFiles(){
Scanner balanceFile = UIAuxiliaryMethods.askUserForInput().getScanner();
while(balanceFile.hasNextLine()){
String balance_Line = balanceFile.nextLine();
Scanner accountsFile = new Scanner(balance_Line);
int account = accountsFile.nextInt(); //works
out.printf("%04d ",account);
/*int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS]; //does not store the values properly
int account = accountsFile.nextInt();
for(int j=0; j < accounts_array.length; j++){
accounts_array[j] = account;
}*/
/*int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS]; //java.util.InputMismatchException
for(int j=0; j < accounts_array.length; j++){
accounts_array[j] = accountsFile.nextInt();
//out.printf("%04d \n",accounts_array[j]);
}*/
String balance = accountsFile.nextLine(); //problem declaring balance as a double
out.printf("%s\n",balance);
/*String [] balance_array = new String [MAX_NUMBER_OF_ACCOUNTS]; //java.util.NoSuchElementException
for(int j=0; j < balance_array.length; j++){
accountsFile.useDelimiter(" ");
balance_array[j] = accountsFile.next();
//out.printf("%04d \n",accounts_array[j]);
}*/
}
Scanner mutationsFile = UIAuxiliaryMethods.askUserForInput().getScanner();
while(mutationsFile.hasNext()){
String mutation_Line = mutationsFile.nextLine();
Scanner mutatedAccountsFile = new Scanner(mutation_Line);
int mutated_account = mutatedAccountsFile.nextInt();
out.printf("%04d ",mutated_account);
int action = mutatedAccountsFile.nextInt(); //deposit or withdrawal
/*if (action == 1){
}else{
}*/
out.printf(" %d ",action);
/*Double amount = mutatedAccountsFile.nextDouble();
out.printf(" %5.2f ",amount);*/
String amount = mutatedAccountsFile.nextLine();
out.printf("%s\n",amount);
}
}
void start(){
new Bank();readFiles();
}
public static void main(String[] args) {
new Bank().start();
}
}
The InputMismatchException occurs because you try to read a double using the nextInt() function. To solve this issue, you can first read the tokens as Strings using the next() function and convert them appropriately.
while(mutationsFile.hasNext()){
mutation_Line = mutationsFile.next();
if(mutation_Line.indexOf(".") == -1)
//token is int
else
//token is double
}
Since you already know what the contents of the two columns are, you can store the integers and doubles in two lists and then, if you want, get them into an array.
List<Integer> intList = new ArrayList<Integer>();
List<Double> doubleList = new ArrayList<Double>();
Now replace the if statements in the first snippet with this:
if(mutation_Line.indexOf(".") == -1)
intList.add(new Integer(Integer.parseInt(mutation_Line)));
else
doubleList.add(new Double(Double.parseDouble(mutation_Line)));
In the end, you can get them into arrays:
Object[] intArr = intList.toArray(),
doubleArr = doubleList.toArray();
//display the contents:
for(int i=0; i<intArr.length; i++)
out.printf("%04d\t%.2f\n", Integer.parseInt(intArr[i].toString()),
Double.parseDouble(doubleArr[i].toString()));
OUTPUT:
0069 723.50
0085 1500.00
0091 8237.31
First off, you don't need to use 2 scanners. The Scanner object is simply reading your file, one scanner is plenty to accomplish the task of reading a file.
If you're trying to read the integers/doubles from file and are having trouble with nextInt() and nextDouble(), consider a different approach to parsing (e.g. parse the line into a string, split the line into 2 parts based on a space character, then trim both resulting strings and convert to respective integers/doubles).
Now back to the Scanner parsing the two values, remember first that when you use a next() or nextInt(), etc. those methods consume the next respective token. So parsing a line as a string from the file into another Scanner object is redundant and unnecessary in this case.
If you know your max number of accounts, and it's simply 50, then go ahead an allocate that prior to the while loop.
Here's an alternative approach with the code you posted.
public class App {
static int MAX_NUMBER_OF_ACCOUNTS = 50;
static PrintStream out;
static void readFiles() {
Scanner balanceFile = null;
try {
balanceFile = new Scanner(new File("C:\\Users\\Nick\\Desktop\\test.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (balanceFile == null)
return;
int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS];
double [] balance_array = new double [MAX_NUMBER_OF_ACCOUNTS];
int currentIndex = 0;
while (balanceFile.hasNextLine()) {
int account = balanceFile.nextInt();
double balance = balanceFile.nextDouble();
System.out.print("acc = " + account + " ");
System.out.println("bal = " + balance);
//out.printf("%04d ", account);
accounts_array[currentIndex] = account;
//out.printf("%s\n", balance);
balance_array[currentIndex] = balance;
currentIndex++;
}
balanceFile.close();
}
static void start() {
readFiles();
}
public static void main(String[] args) {
start();
}
}
Please note the excessive use of static could also be avoided in the future, but for the sake of the example it spread like the plague.
As you can see in the logic leading up to the while loop, the scanner object is made from a file I copied your example data into a file on my desktop. The arrays are allocated prior to the while loop (note: see #progy_rock and their use of ArrayList's - may help improve your code in the long run). And finally, note the index count to move the position along in the array to which you are inserting your lines to.

How to modify a text file using Java?

http://pastebin.com/E5TspHfK - Object Class, named PhoneBookEntryhttp://pastebin.com/Ce94SJzB - Method Class, named PhoneBook
http://pastebin.com/ENsVT0jJ - Tester Class, named PhoneBookTester
Basically my aim with these three classes is to make a "Phone Book" -- a text-based program that allows people to create a database of their contacts that they can add entries to, edit/delete/display the entries of, search, and sort the entries.
The PhoneBookEntry object array that the program is creating is output to a text file, which displays them in the format "fName\tlName\tnumber". These are obviously the various variables that can be stored in the PhoneBookEntry class.
The question is, to write to the text file I have to use the PrintWriter class, but how do I make it so that the text file is updated if the order of the array is rearranged? Because I don't send added entries to the array, I send them to the text file itself, but if you use the sort or edit function, you modify the content of the array, not the text file.
So how do I make it possible to modify the contents of the text file itself if you can't 'write backwards' with the PrintWriter class? Relevant bits of code are pasted below.
PhoneBook:
public static int filledTil=-1;
FileWriter fw = new FileWriter("C:\\Users\\Hana\\Desktop\\PhoneBook.txt");
PrintWriter output = new PrintWriter(fw);
static PhoneBookEntry[] phoneBook = new PhoneBookEntry[500];
public PhoneBook() throws IOException {
Scanner input = new Scanner(new File("C:\\Users\\Hana\\Desktop\\PhoneBook.txt"));
while(input.hasNext()){
Scanner sc = new Scanner(input.nextLine());
String fName = sc.next();
String lName = sc.next();
String number = sc.next();
filledTil++;
phoneBook[filledTil] = new PhoneBookEntry(fName, lName, number);
}
input.close();
}
PhoneBook Sort Methods
public static int partition(){
int lo = 0;
int hi = filledTil;
PhoneBookEntry temp;
PhoneBookEntry pivot = phoneBook[(lo + hi) / 2];
while(lo <= hi){
while(phoneBook[lo].lName.compareTo(pivot.lName) < 0){
lo++;
}
while(phoneBook[lo].lName.compareTo(pivot.lName) > 0){
hi--;
}
if(lo <= hi) {
temp = phoneBook[lo];
phoneBook[lo] = phoneBook[hi];
phoneBook[hi] = temp;
lo++;
hi--;
}
};
return lo;
}
public static void quickSort(int lo, int hi){
int index = partition();
if(lo < (index - 1)){
quickSort(lo, (index-1));
}
if(index < hi){
quickSort(index, hi);
}
}
PhoneBook Quit Method
public void quit(){
output.close();
System.exit(0);
}

Using standard input in java, how to input an entire array of integers? [duplicate]

This question already has answers here:
How to read array of integers from the standard input in Java?
(2 answers)
Closed 8 years ago.
So my code looks like this so far:
public class PancakeSort {
public static int flip(int n) {
int temp = 0;
for (int i = 0; i < (n+1) / 2; ++i) {
int[] pancakes = new int[n];
temp = pancakes[i];
pancakes[i] = pancakes[n-i];
pancakes[n-i] = temp;
}
return temp;
}
public static void sort (int[] pancakes) {
for (int i=0; i<pancakes.length; i++){
if (pancakes[i] > pancakes[i+1]){
flip(i+1);
}
}
System.out.println(pancakes);
}
public static void main(String[] args) {
}
}
But how I input a whole array of integers using standard input (StdIn.readLine())? I understand that the code might not be correct and I'm working on figuring that out,and I'm also aware that this question has been asked before in this site, but not specifically using the standard library and that is where I'm stuck.
You can send integer array as input
PancakeSort pancakeSort = new PancakeSort();
pancakeSort.sort(new int[] { 100, 50, 89, 2, 5, 150 });
or Use scanner class as
int arr[] = new int[10];
Scanner sc = new Scanner(System.in);
int i = 0;
while (sc.hasNextInt()) {
arr[i] = sc.nextInt();
i = i + 1;
}
PancakeSort pancakeSort = new PancakeSort();
pancakeSort.sort(arr);
But in last case you must not increased the size of array.Otherwise it will give arrayIndexOutOfBoundException
I believe you may be referencing StdIn such as a class like this one?
http://introcs.cs.princeton.edu/java/stdlib/StdIn.java.html
If so, then to get an int from the console you just call StdIn.readInt. An example of how you could approach this is:
public static void main(String[] args)
{
System.out.println("Enter number of pancakes, or enter 0 to quit");
int[] pancakeArray = new int[0];
while (true)
{
try
{
int entry = StdIn.readInt();
if (entry == 0)
{
break;
}
int[] expandedArray = new int[pancakeArray.length + 1];
System.arraycopy(pancakeArray, 0, expandedArray, 0, pancakeArray.length);
expandedArray[pancakeArray.length] = entry;
pancakeArray = expandedArray;
}
catch (Exception e)
{
System.out.println("Invalid entry detected, closing input");
break;
}
}
System.out.println("Pancake array length: " + pancakeArray.length);
sort(pancakeArray);
System.out.println("Final pancake array in order:");
for (int entry : pancakeArray)
{
System.out.println("Pancake value: " + entry);
}
}
This would read int after int until they entered 0 or an invalid value, then it would call your sort routine from there. There are issues in your sort routine but you said you wanted to look at that, so I will let you figure that part out.

IndexOutOfBoundsException while accessing List

I'm working on a project for a class, and I think I've got it mostly figured out, but it keeps giving me different Exception errors and now I'm stumped.
The instructions can be found here: http://www.cse.ohio-state.edu/cse1223/currentsem/projects/CSE1223Project11.html
Here is the code I have thus far, currently giving me and IndexOutOfBounds exception in the getMaximum method.
Any help would be much appreciated.
import java.io.*;
import java.util.*;
public class Project11a {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an input file name: ");
String fileName = keyboard.nextLine();
Scanner in = new Scanner(new File(fileName));
System.out.print("Enter an output file name: ");
String outFile = keyboard.nextLine();
PrintWriter outputFile = new PrintWriter(outFile);
while (in.hasNextLine()) {
String name = in.nextLine();
List<Integer> series = readNextSeries(in);
int mean = getAverage(series);
int median = getMedian(series);
int max = getMaximum(series);
int min = getMinimum(series);
outputFile.printf("%-22s%6d%n", name, mean, median, max, min);
}
in.close();
outputFile.close();
}
// Given a Scanner as input read in a list of integers one at a time until a
// negative
// value is read from the Scanner. Store these integers in an
// ArrayList<Integer> and
// return the ArrayList<Integer> to the calling program.
private static List<Integer> readNextSeries(Scanner inScanner) {
List<Integer> nextSeries = new ArrayList<Integer>();
while (inScanner.hasNextInt()) {
int currentLine = inScanner.nextInt();
if (currentLine != -1) {
nextSeries.add(currentLine);
} else {
break;
}
}
return nextSeries;
}
// Given a List<Integer> of integers, compute the median of the list and
// return it to
// the calling program.
private static int getMedian(List<Integer> inList) {
Collections.sort(inList);
int middle = inList.size() / 2;
int median = -1;
if (inList.size() % 2 == 1) {
median = inList.get(middle);
} else {
try {
median = (inList.get(middle - 1) + inList.get(middle)) / 2;
} catch (Exception e) {
}
}
return median;
}
// Given a List<Integer> of integers, compute the average of the list and
// return it to
// the calling program.
private static int getAverage(List<Integer> inList) {
int average = 0;
if (inList.size() == 0) {
return 0;
}
for (int i = 0; i < inList.size(); i++) {
average += inList.get(i);
}
return (average / inList.size());
}
// Given a List<Integer> of integers, compute the maximum of the list and
// return it to
// the calling program.
private static int getMaximum(List<Integer> inList) {
int max = inList.get(0);
for (int i = 1; i < inList.size(); i++) {
if (inList.get(i) > max) {
max = inList.get(i);
}
}
return max;
}
// Given a List<Integer> of integers, compute the maximum of the list and
// return it to
// the calling program.
private static int getMinimum(List<Integer> inList) {
int min = inList.get(0);
for (int i = 1; i < inList.size(); i++) {
if (inList.get(i) < min) {
min = inList.get(i);
}
}
return min;
}
}
Seemed like that your list is empty.
What can triggered the exception is the statement:
int max = inList.get(0);
So your inList do not have the value in the first index,which means the inList is empty.

Binary search gives incorrect output Java

I'm having a problem with my code. We're working on binary search, and I can't seem to get the right output whenever I input a number. We were given a list of 60 numbers already in order(external file), and whatever number we input, the program should search and return the position. If the number is not on the list, it should return a -1.
My code:
import java.io.*;
import java.util.*;
public class Prog489
{
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number to search for: ");
int search = scan.nextInt();
Scanner kbReader = new Scanner(new File("C:\\Users\\Guest\\Documents\\java programs\\Prog489\\Prog489.in"));
int[] num = new int[60];
int i = 0;
System.out.println(binarySearch(num, search));
while(kbReader.hasNextInt())
{
num[i++] = kbReader.nextInt();
}
}
private static int binarySearch(int[] num, int search)
{
int lb = 0;
int ub = num.length - 1;
while(lb<=ub)
{
int mid = (lb+ub)/2;
if(num[mid] == search)
{
return mid;
}
else if(search>num[mid])
{
lb=mid+1;
}
else
{
ub = mid-1;
}
}
return -1;
}
}
So the part with the return should only return -1 if the number is not on the list. But whenever I do enter a number on the list (such as 60), it still returns a -1. Everything compiles, so I'm not really sure what I'm missing, or if it's something really obvious that I'm forgetting. Could someone please help me identify the error? Any guidance/feedback is greatly appreciated.
Move the call to print the output of binarySearch to after you populate the array:
int[] num = new int[60];
int i = 0;
while(kbReader.hasNextInt())
{
num[i++] = kbReader.nextInt();
}
System.out.println(binarySearch(num, search));

Categories