I'm unable to view the println after exiting the "For" and "While" loop.
What am i doing wrong?
Assignment is : to Extract doubles from a txt file that has the numbers split by a "," . once i have the data do some calculations and display it. I've done all except the displaying. which I'm having some difficulty in.
try {
FileInputStream ofile = new FileInputStream("Sales Analysis.txt");
DataInputStream in = new DataInputStream(ofile);
BufferedReader Rreader = new BufferedReader( new InputStreamReader(in));
String Filedata ;
String read;
double[] TotalWeekSales = new double [7];
double[] DailyAverage = new double [7];
double TotalSales = 0;
double[] amount= new double [7];
double AverageSales = 0;
int Topsale = -1 ; // Position of Highest Week Sale
int LowestSale= -1; // Lowest Week Sale
while ((Filedata= Rreader.readLine()) != null) {
String[] Splitt = Filedata.split(",");
//double amount[] =new double [10];
for (int i = 0; i<Filedata.length(); i++)
{
read = Splitt[i];
amount[i] = Double.parseDouble(read);
TotalWeekSales[i] = amount[i];
DailyAverage[i]= (amount[i]/7);
TotalSales += amount[i];
System.out.println("\nWeek: "+(i+1));
System.out.println("\nAmount : $"+amount[i]);
}
};
/********* This part below doesn't Print ***********/
AverageSales = (TotalSales/7);
System.out.println("\nTotal Average Sales: $"+AverageSales);
} catch (Exception e) {
// TODO: handle exception
}
}
}
for (int i = 0; i<Filedata.length(); i++)
should be:
for (int i = 0; i < Splitt.length; i++)
there might be other bugs as well.
Note: it's difficult to read the code since it's not indented properly.
Related
I have created a simple program that sorts integers in an input file using different algorithms. I also use filewriter to output results to another file. Unfortunately no matter how I change my code, file gets overridden. Any advice?
Been searching for answer on google and tried changing the way I input the syntax but nothing works.
important bits:
setting the writer up
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
outputting to the file
out.println("User's own data set sorted using bubble sort.");
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println("Sorted Array looks like this:" + Arrays.toString(intArrayBubble));
out.println(timeToSort + bubbleSortIs + bubbleTime + "ms");
it works fine, however its used in a do while loop, with nested if statements, and each one overrides the other.
Rest of code in case its required - UPDATED - still not working
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class PDD_Sorting {
public static void main (String [] pArgs)
{
//Array for a file
String[] FileOne;
FileOne = new String[0];
int optionOne = 1,
optionTwo = 2,
optionThree = 3,
secondaryOptionOne = 1,
secondaryOptionTwo = 2,
secondaryOptionThree = 3,
userSelection,
subUserSelection;
String unsortedArray = "Unsorted array is: ",
bubbleSort = "Sorted array using bubble sort: ",
selectionSort = "Sorted array using selection sort: ",
insertionSort = "Sorted array using insertion sort: ",
timeToSort = "Time needed to sort this array using ",
bubbleSortIs = "bubble sort is ",
selectionSortIs = "selection sort is ",
insertionSortIs = "insertion sort is ",
welcomeToSorter = "Welcome to the SORTER - program that can sort your txt files containing integeres in an ascending order!",
notFiles = "Integers, not files :)",
pleaseSelect = "Please select one of the following options, by enetering a number asociated with it.",
optionOneUserInput = "1. Sort your own data set - input your own set of data (integers, separated by colons, no spaces) into the Input file.",
optionTwoPredefined = "2. Use predetermind set of data to test the algorythms.",
optionThreeExit = "3. Exit the program.",
subMenuPleaseSelect = "Please select which algorythm would you like to use to sort this file.",
optionBubble = "(1) - Bubble Sort.",
optionSelection = "(2) - Selection Sort.",
optionInsertion = "(3) - Insertion Sort.",
usersDataBubble = "User's own data set sorted using bubble sort.",
sortedArrayLooks = "Sorted Array looks like this:",
msTime = "ms",
usersDataSelection = "User's own data set sorted using selection sort.",
usersDataInsertion = "User's own data set sorted using insertion sort.",
validOption = "Please enter a valid option i.e. 1,2 or 3",
lessThanZero = "If time shown in ms is 0, that means the time needed to conduct the sort is shorter than 1ms.",
fileCreated = "File created.",
terminatingProgram = "Terminating the program.",
unableToWriteFile = "Unable to write to file";
System.out.println(welcomeToSorter);
System.out.println(notFiles);
Scanner tInput = new Scanner (System.in);
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
System.out.println(pleaseSelect);
System.out.println(optionOneUserInput);
System.out.println(optionTwoPredefined);
System.out.println(optionThreeExit);
// Scanner tInput = new Scanner (System.in);
userSelection = tInput.nextInt();
if (userSelection == optionOne) {
//System.out.println("Please enter a valid path for your file.");
String[] splitFile = null;
//String userFile = tInput.next();
FileOne = getAndPrepareFile(splitFile);
System.out.println(subMenuPleaseSelect);
System.out.println(optionBubble);
System.out.println(optionSelection);
System.out.println(optionInsertion);
subUserSelection = tInput.nextInt();
if (subUserSelection == secondaryOptionOne) {
int size = FileOne.length;
int [] intArrayBubble = new int [size];
for(int i=0; i<size; i++) {
intArrayBubble[i] = Integer.parseInt(FileOne[i]);
}
bubbleSort(intArrayBubble);
long bubbleTime = timeCount(intArrayBubble);
out.println(usersDataBubble);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArrayBubble));
out.println(timeToSort + bubbleSortIs + bubbleTime + msTime);
}
else if (subUserSelection == secondaryOptionTwo) {
int size2 = FileOne.length;
int [] intArraySelection = new int [size2];
for(int i=0; i<size2; i++) {
intArraySelection[i] = Integer.parseInt(FileOne[i]);
}
doSelectionSort(intArraySelection);
long selectionTime = timeCount(intArraySelection);
out.println(usersDataSelection);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArraySelection));
out.println(timeToSort + selectionSortIs + selectionTime + msTime);
}
else if (subUserSelection == secondaryOptionThree) {
int size3 = FileOne.length;
int [] intArrayInsertion = new int [size3];
for(int i=0; i<size3; i++) {
intArrayInsertion[i] = Integer.parseInt(FileOne[i]);
}
doInsertionSort(intArrayInsertion);
long insertionTime = timeCount(intArrayInsertion);
out.println(usersDataInsertion);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArrayInsertion));
out.println(timeToSort + insertionSortIs + insertionTime + msTime);
}
else {
System.out.println(validOption);
tInput.next();
}
}
else if (userSelection == optionTwo){
//file being prepared and loaded via function
String[] splitFilePredefined = null;
FileOne = getAndPrepareFilePredefined(splitFilePredefined);
//converting string array into int array so the method can sort it.
int size = FileOne.length;
int [] intArrayBubble = new int [size];
for(int i=0; i<size; i++) {
intArrayBubble[i] = Integer.parseInt(FileOne[i]);
}
int size2 = FileOne.length;
int [] intArraySelection = new int [size2];
for(int i=0; i<size2; i++) {
intArraySelection[i] = Integer.parseInt(FileOne[i]);
}
int size3 = FileOne.length;
int [] intArrayInsertion = new int [size3];
for(int i=0; i<size3; i++) {
intArrayInsertion[i] = Integer.parseInt(FileOne[i]);
}
//inserting pre-prepared int arrays into variables including a timecount method
int bubbleTime = timeCount(intArrayBubble);
int selectionTime = timeCount(intArraySelection);
int insertionTime = timeCount(intArrayInsertion);
//sorting array using various sorts
bubbleSort(intArrayBubble);
doSelectionSort(intArraySelection);
doInsertionSort(intArrayInsertion);
//out.println("Sorted arrray using insertion sort looks like this: " + Arrays.toString(intArrayInsertion));
out.println(timeToSort + bubbleSortIs + bubbleTime + "ms");
out.println(timeToSort + selectionSortIs + selectionTime + "ms");
out.println(timeToSort + insertionSortIs + insertionTime + "ms");
out.println(lessThanZero);
System.out.println(fileCreated);
}
else if (userSelection == optionThree){
System.out.println(terminatingProgram);
System.exit(0);
}
else {
System.out.println(validOption);
tInput.next();
}
out.flush();
out.close();
//tInput.close();
}while (userSelection != optionThree);
}
catch (Exception e)
{
System.out.println(unableToWriteFile);
tInput.next();
}
tInput.close();
}//end main
//method that fetches the file from predefined, hardcoded location and removes comas, esentially prepares the file for the next phase
private static String[] getAndPrepareFile (String[] splitFile)
{
Scanner fileIn = null;
try
{
fileIn = new Scanner(new FileInputStream("C:\\Users\\Greg\\Documents\\Programming\\PDD - Assignment 1\\Input.txt"));
String fileNew = fileIn.next();
splitFile = fileNew.split(",");
//System.err.println(Arrays.toString(splitFile)); //Arrays.toString needed to print the array correctly, otherwise it prints the address of the object
fileIn.close();
}
catch (IOException e)
{
System.out.println("File not found.");
//System.exit(0);
}
return splitFile;
}
//as above but works for predefined file, that can be generated using randomNumber.java program
private static String[] getAndPrepareFilePredefined (String[] splitFilePredefined)
{
Scanner fileIn = null;
try
{
fileIn = new Scanner(new FileInputStream("C:\\Users\\Greg\\Documents\\Programming\\PDD - Assignment 1\\Generated input.txt"));
String fileNew = fileIn.next();
splitFilePredefined = fileNew.split(",");
//System.err.println(Arrays.toString(splitFile)); //Arrays.toString needed to print the array correctly, otherwise it prints the address of the object
fileIn.close();
}
catch (IOException e)
{
System.out.println("File not found.");
//System.exit(0);
}
return splitFilePredefined;
}
//method used to sort a file using bubble sort
private static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
//method used to sort a file using selection sort
private static int[] doSelectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}
//method used to sort a file using sinsertion sort
private static int[] doInsertionSort(int[] input){
int temp;
for (int i = 1; i < input.length; i++) {
for(int j = i ; j > 0 ; j--){
if(input[j] < input[j-1]){
temp = input[j];
input[j] = input[j-1];
input[j-1] = temp;
}
}
}
return input;
}
//method used to calculate how much time has lapsed while using any of the given sort methods, outputs in ms, if less than 1 ms, outputs 0ms
private static int timeCount (int[] anArray)
{
long start = System.nanoTime();
Arrays.sort(anArray);
long end = System.nanoTime();
long timeInMillis = TimeUnit.MILLISECONDS.convert(end - start, TimeUnit.NANOSECONDS);
//System.out.println("Time spend in ms: " + timeInMillis);
return (int) timeInMillis;
}
}//end class
File gets constantly overridden, how do i stop this and make it add to file instead?
You don't need the first FileWriter fileWriter = new FileWriter("Sorted output.txt");; this is actually creating/overwriting the file, after which your PrintWriter opens it again for appending.
So, just change
// ... omitting beginning
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
// ... omitting rest
to
// ... omitting beginning
try {
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
// ... omitting rest
Move out.close() outside the loop
else {
System.out.println("Please enter a valid option i.e. 1,2 or 3");
tInput.next();
}
out.flush();
/* THIS -> out.close(); <- THIS */
//tInput.close();
}while (userSelection != optionThree);
out.close();
}
I tried your code and your problem is not that the file is being overwritten, but that you are closing the outputstream in the first iteration.
I've tried to solve this issue 3 days ago but nothing happens. I hope you can find a solution:
i'm making an application to read a txt file of numbers after that, i captured the data into a String Matrix and to operate them i need to convert it to a double matrix. but an error appear:
Errorjava.lang.NumberFormatException: For input string: "0,95768412 0,770070937"
. ive tried to replace the comma (.) for (.) but nothin happen.
Here a thumbnail of the file info:
0,620966467 0,397670717
0,144506398 0,86070719
0,344924707 0,49886148
0,568299164 0,407224505
0,55644466 0,580297755
0,940100947 0,920269925
0,45667026 0,253952562
0,046970841 0,04214613
0,548769197 0,114155205
0,220420195 0,035404045
0,804653981 0,371228693
0,688345818 0,575313752
0,54377148 0,891464466
i post the code for you can see the program.
try {
BufferedReader br = new BufferedReader(new FileReader("src\\numerosAleatorios.txt"));
//String matriz[][] = new String[99][1];
double matriz[][] = new double[99][2];
int numlineas = 0;
while (((Linea = br.readLine()) != null)) {
String a[] = Linea.split(" ");
for (int i = 0; i < a.length; i++) {
matriz[numlineas][i] = Double.parseDouble(a[i]);
}
numlineas++;
}
//double matrizDoble[][]= new double [99][1];
System.out.println("MATRIZ");
System.out.println("------------------------------");
for (int filas = 0; filas < matriz.length; filas++) {
for (int colum = 0; colum < matriz[filas].length; colum++) {
//matrizDoble[filas][colum]= Double.valueOf(matriz[filas][colum]).doubleValue();
System.out.print(matriz[filas][colum] + "\n");
}
}
System.out.println("\n Numero de parejas: "+numlineas);
} catch (Exception ex) {
System.out.println("Error"+ex);
}
Thanks for answer.!
I have tried your code with replacing ',' with '.' and it works fine for me.
String Linea;
try {
BufferedReader br = new BufferedReader(new FileReader("src\\numerosAleatorios.txt"));
// String matriz[][] = new String[99][1];
double matriz[][] = new double[99][2];
int numlineas = 0;
while (((Linea = br.readLine()) != null)) {
String a[] = Linea.split(" ");
for (int i = 0; i < a.length; i++) {
matriz[numlineas][i] = Double.parseDouble(a[i]);
}
numlineas++;
}
// double matrizDoble[][]= new double [99][1];
System.out.println("MATRIZ");
System.out.println("------------------------------");
for (int filas = 0; filas < matriz.length; filas++) {
for (int colum = 0; colum < matriz[filas].length; colum++) {
System.out.print(matriz[filas][colum] + "\n");
}
}
System.out.println("\n Numero de parejas: " + numlineas);
} catch (Exception ex) {
System.out.println("Error" + ex);
}
1) Split your String by white space:
String a[] = Linea.split("\\s+");
2) Replace "," with "." :
matriz[numlineas][i] = Double.parseDouble(a[i].replace(",", "."));
You're using String.split() with a "space"; however, your stacktrace shows a "tab" between the numbers. No space is found in the string, so it doesn't split. It then tries to parse both numbers in the string at once: "0.620966467 0.397670717" which fails.
Use Scanner and File to read this file of vocabulary scores as measured by the General Social Survey from 1972 to 2004. Compute and display the mean score for both males and females.
I am unsure of how to seperate the lines into chunks by comma and to still retain the correct data.
Example of what the file contains:
Female,7
Male,3
Male,6
Male,10
Female,10
public static void main(String[] args) throws FileNotFoundException {
File file = new File("scores.csv");
Scanner in = new Scanner(file);
String run = "";
int maleCount = 0;
int femaleCount = 0;
int maleScore = 0;
int femaleScore = 0;
while (in.hasNextLine()) {
String current = in.nextLine();
in.useDelimiter(",");
if (current.contains("f")) {
femaleCount++;
// add score onto femaleScore
}
else {
maleCount++;
// add score onto maleScore
}
double femaleAverage = femaleScore / femaleCount;
System.out.println(femaleAverage);
double maleAverage = maleScore / maleCount;
System.out.println(maleAverage);
}
in.close();
}
Your calculation was inside the while loop, meaning it would calculate this average once per line in the file, which is wrong.
The code below assumes the format of the data is the same as stated in your post.
Female,7
Male,3
Male,6
Male,10
Female,10
public static void main(String[] args) throws FileNotFoundException {
File file = new File("scores.csv");
Scanner in = new Scanner(file);
String run = "";
int maleCount = 0;
int femaleCount = 0;
int maleScore = 0;
int femaleScore = 0;
while (in.hasNextLine()) {
String current = in.nextLine();
String[] split = current.split(",");
if (split[0].toLowerCase().contains("f")) {
femaleCount++;
femaleScore += Integer.parseInt(split[1]);
// add score onto femaleScore
} else {
maleCount++;
maleScore += Integer.parseInt(split[1]);
// add score onto maleScore
}
}
double femaleAverage = femaleScore / femaleCount;
System.out.println(femaleAverage);
double maleAverage = maleScore / maleCount;
System.out.println(maleAverage);
in.close();
}
If the data is different, post it here and I will edit the code accordingly
Assuming your input file is structured as below:
male, 4
female, 7
male, 3
female, 5
etc
Then the below code should do what you want. You were pretty close, just had to split the line's on commas and then assess the parts (gender/score) like array.
String filePath = "C:\\Users\\adam\\Documents\\Scores.txt";
File file = new File(filePath);
Scanner scanner = new Scanner(file);
int maleCount = 0;
int femaleCount = 0;
int maleScore= 0;
int femaleScore = 0;
while(scanner.hasNext()){
String line = scanner.nextLine();
String[] split = line.split(",");
String gender = split[0];
String score = split[1];
if(gender.toLowerCase().trim().equals("male")){
maleCount++;
maleScore += Integer.valueOf(score.trim());
}else if(gender.toLowerCase().trim().equals("female")){
femaleCount++;
femaleScore += Integer.valueOf(score.trim());
}
}
scanner.close();
double maleAverage = (double) maleScore / maleCount;
double femaleAverage = (double) femaleScore / femaleCount;
System.out.println("Male Average: " + maleAverage);
System.out.println("Female Average: " + femaleAverage);
I'm working on a pokemon battle simulator, (basically pokemonshowdown gen1), trying to automate making the pokemon array, but running into a Scanner problem. File is formatted as: Name.Type1.Type2.hp.attack.defense.special.speed.list of learnable moves. So:
Aerodactyl.Flying.Rock.80.105.65.60.130.Agility,Bide,Bite,Double-Edge,Double Team,Dragon Rage,Fire Blast,Fly,Hyper Beam,Mimic,Rage,Razor Wind,Reflect,Rest,Sky Attack,Substitute,Supersonic,Swift,Take Down,Toxic,Wing Attack.
I've gotten a method working for both my typeArray and moveArray but for some reason using basically the same loop the scanner is returning empty tokens instead of what's in the file.
Exception:
0 Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at Controller.initPokemonArray(Controller.java:169)
at Controller.<init>(Controller.java:29)
at Driver.main(Driver.java:15)
Here's the whole method, it's throwing the error at the parseInt call for hp.
private Pokemon[] initPokemonArray() {
Pokemon[] pokemonArray = new Pokemon[83];
try {
Scanner inputScan = new Scanner(new File("src/pokemon")).useDelimiter(".");
String name = "";
Type type1 = typeArray[0];
String inputType1 = "";
Type type2 = typeArray[0];
String inputType2 = "";
int hp = 0;
int atk = 0;
int def = 0;
int spc = 0;
int spe = 0;
String[] lm = {};
Move[] learnableMoves;
int counter = 0;
while (counter < 83) {
System.out.print(counter);
if (inputScan.hasNextLine()) {
name = inputScan.next();
System.out.println(name+" ");
//System.out.print("name");
inputType1 = inputScan.next();
for (int i = 0;i < 16;i++)
if (inputType1.equals(typeArray[i].toString()))
type1 = typeArray[i];
System.out.println(type1.toString()+" ");
inputType2 = inputScan.next();
for (int i = 0;i < 16;i++)
if (inputType2.equals(typeArray[i].toString()))
type2 = typeArray[i];
System.out.println(type2.toString()+" ");
hp = Integer.parseInt(inputScan.next());
System.out.println(hp+" ");
atk = Integer.parseInt(inputScan.next());
System.out.println(atk+" ");
def = Integer.parseInt(inputScan.next());
System.out.println(def+" ");
spc = Integer.parseInt(inputScan.next());
System.out.println(spc+" ");
spe = Integer.parseInt(inputScan.next());
System.out.println(spe+" ");
lm = inputScan.next().split(",");
System.out.println();
}
//TODO move this to private helper method
learnableMoves = new Move[lm.length];
for (int i = 0;i < 160;i++) {
for (int j = 0;j < lm.length;j++) {
if (lm[j] == moveArray[i].getName())
learnableMoves[j] = moveArray[i];
}
}
pokemonArray[counter] = new Pokemon(name,type1,type2,hp,atk,def,spc,spe,learnableMoves);
counter++;
}
inputScan.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pokemonArray;
}
DISCLAIMER: this is a project for my java 2 course and also my first post on here so I don't know exactly what I'm supposed to do so just letting it be known down here.
The useDelimiter() method takes the passed String as regex value.https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#useDelimiter-java.lang.String-. A period has a specific meaning in regex. To get the specific character "." use this.
Scanner inputScan = new Scanner(new File("src/pokemon")).useDelimiter("\\.");
In my Java Project, i want to read values from txt file to List method.Values seems like;
1 kjhjhhkj 788
4 klkkld3 732
89 jksdsdsd 23
Number of row changable. I have tried this codes and getting same values in all indexes.
What can i do?
String[] dizi = new String[3];
List<String[]> listOfLists = new ArrayList<String[]>();
File f = new File("input.txt");
try {
Scanner s = new Scanner(f);
while (s.hasNextLine()) {
int i = 0;
while (s.hasNext() && i < 3) {
dizi[i] = s.next();
i++;
}
listOfLists.add(dizi);
}
} catch (FileNotFoundException e) {
System.out.println("Dosyaya ba?lanmaya çal???l?rken hata olu?tu");
}
int q = listOfLists.size();
for (int z = 0; z < q; z++) {
for (int k = 0; k < 3; k++) {
System.out.print(listOfLists.get(z)[k] + " ");
}
}
String [] dizi = new String [3];
dizi is a global variable getting overridden eveytime in the loop. Thats why you are getting same values at all indexes
Make a new instance everytime before adding to the list.
You put the same reference to the list, create a new array in while loop.
while (s.hasNextLine()){
String[] dizi = new String[3]; //new array
int i = 0;
while (s.hasNext() && i < 3)
{
dizi[i] = s.next();
i++;
}
listOfLists.add(dizi);
}