I am almost complete making this app in Eclipse. It is an android app that reads double data values from the text files in the asset directory for my app project. It stores the data values in the array, and I just need to write the square root of the double data values to the output files. I used the adb shell in the Command Prompt, and it shows the data values, but they are not in square root. The data values are still in their original double form. So, I think something must be wrong with the writing part of the code or the method that does the square root. I really don't know about Java, so please explain to me in a very simpler way. Here is the code:
public void srAndSave(View view)
{
EditText edt1;
EditText edt2;
TextView tv;
String infilename;
String outfilename;
tv = (TextView) findViewById(R.id.text_status);
//Get the name of the input file and output file
edt1 = (EditText) findViewById(R.id.edit_infile);
edt2 = (EditText) findViewById(R.id.edit_outfile);
infilename = edt1.getText().toString();
outfilename = edt2.getText().toString();
//Create an array that stores double values (up to 20)
double double_nums[] = new double[20];
int n = 0;//For storing the number of data values in the array
//Open the data file from the asset directory
//and make sure the data file exists
AssetManager assetManager = getAssets();
try
{
Scanner fsc = new Scanner(assetManager.open(infilename));
//Get the data values from the file
//and store them in the array double_nums
n = 0;
while(fsc.hasNext()){
double_nums[n] = fsc.nextDouble();
n++;
}
//Calls on square_root_it method
square_root_it(double_nums, n);
//Display that the file has been opened
tv.setText("Opening the input file and reading the file were "
+ " successful.");
fsc.close();
}
catch(IOException e)
{
tv.setText("Error: File " + infilename + " does not exist");
}
//Write the data to the output file and
//also make sure that the existence of the file
File outfile = new File(getExternalFilesDir(null), outfilename);
try
{
FileWriter fw = new FileWriter(outfile);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
int x;
for(x=0;x < n;x++)
pw.println(double_nums[x]);
pw.close();
}
catch(IOException e)
{
System.out.println("Error! Output file does already exist! You will overwrite"
+ " this file!");
}
} //end srAndSave
public static void square_root_it(double[] a, int num_items)
{
int i;
for(i=0; i < num_items; i++)
Math.sqrt(a[i]);
} //end square_root_it
}
your problem is here:
for(i=0; i < num_items; i++)
Math.sqrt(a[i]);
Math.sqrt(num) returns a value, it does not set the value.
what I would do is create a second array to hold the results and then do:
for(i=0; i < num_items; i++)
results[i] = Math.sqrt(a[i]);
Related
I am new at Java so please bear with me.
I need help for one of my assignments again. Now it involves FileI/O.
The task that I have to do is:
I have to read a .csv file. The values that's inside the file are:
Christopher Lee,54.0
Stanley Wright,90.5
Oliver Stewart,75.8
Jessica Chang,34.65
As the task said, I must store the contents on the file into two arrays. One for the names, and one for the test marks. I should read the file at least twice, once to check how many names are in the file and a couple more times to actually read the file (to get the names and marks). So basically, I should have an array to store the names as Strings, and an array to store the marks of the student as real numbers.
I should line up the arrays (e.g.students[0] should store the name of the first student and marks[0] should store the mark of the first student
After I stored the contents of the .csv file into an array I have to display a following menu to the user. If the user pressed 1, it should prompt the user to enter the name of a student. If the user pressed 2, the program should exit. If the name exists, it should display the test mark for the student entered. If the student does not exist then I must output a message indicating so to the user, yet the program should not end but return to the above menu.
This is my code so far:
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String fileName = "file:///Documents/Java/marks_file.csv"; // Opens the file
String[] arrayString = new String[6]; // String length inside the file
int numLines, selection = 0;
double[] arrayReal = new double[6]; // Number length inside the file
numLines = getNumLines(fileName); // Gets the length of the file
readFile(arrayString, arrayReal, fileName);
// Selection menu
do
{
System.out.println("Select an option:");
System.out.println("1. Display mark");
System.out.println("2. Exit");
selection = sc.nextInt();
if (selection == 1)
{
System.out.println("Enter your full name");
{
// Do something
}
}
else if (selection == 2)
{
System.out.println("Goodbye");
}
}
while (selection == 1);
//System.out.println("Number of arrays: " + numLines);
}
// Method to get the length of the .csv file
public static int getNumLines(String fileName)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
int lineNum = 0;
try
{
fileStrm = new FileInputStream(fileName);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
line = bufRdr.readLine();
while (line != null)
{
lineNum = lineNum + 1;
line = bufRdr.readLine();
}
fileStrm.close();
}
catch (IOException e)
{
try
{
if (fileStrm != null)
{
fileStrm.close();
}
}
catch (IOException ex2)
{
// Nothing to do
}
System.out.println("Error in file processing: " + e.getMessage());
}
return lineNum;
}
// Method to store the values to arrays
public static void readFile(String[] arrayString, double[] arrayReal, String fileName)
{
Scanner sc = new Scanner(System.in);
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
try
{
fileStrm = new FileInputStream(fileName);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
for (int i = 0; i < arrayString.length; i++)
{
line = bufRdr.readLine();
arrayString[i] = processString(line);
arrayReal[i] = processReal(line);
}
}
catch (IOException e)
{
try
{
if (fileStrm != null)
{
fileStrm.close();
}
}
catch (IOException ex2)
{
// Nothing to do
}
System.out.println("Error in file processing: " + e.getMessage());
}
}
// Stores the String lines to array
public static String processString(String line)
{
String string;
String[] lineArray = line.split(",");
return string = lineArray[0];
}
// Stores real number lines to array
public static double processReal(String line)
{
double real;
String[] lineArray = line.split(",");
return real = Double.parseDouble(lineArray[1]);
}
So far, I finished the "reading the file" part and processing the contents from a .csv file to an array.
I am not too sure how to prompt a user to search a string array from a .csv file. I tried looking at other sources, even at this website but I have no luck at all. I tried the Scanner.next() method but that doesn't work at all. Maybe I just missed something. Also, I am not sure if I did the "reading the file twice" right.
Am I on the right track? I am need of some guidance here
First of all I want to say that I'd use a Map instead of two arrays but I'll show you a solution using two arrays.
You were close to the solution. One of you problems is that scanner.next() only reads the input until the first whitespace. That's why you need to use scanner.nextLine(). This method reads the complete line. And the code could look something like that:
Solution with two arrays
Scanner sc = new Scanner(System.in);
System.out.print("Please enter name of student: ");
String name = sc.nextLine();
for(int i = 0; i < arrayString.length; i++){
if(name.equals(arrayString[i])) {
System.out.println(arrayReal[i]);
}
}
Solution with a HashMap
Initialize HashMap
HashMap<String, Double> hm = new HashMap<String, Double>();
Fill HashMap
hm.put("Christopher Lee", 54.0);
Print double value of student
System.out.print("Please enter name of student: ");
String name = sc.nextLine();
System.out.println(hm.get(name));
Instead of storing into arrays, I would rather tell you to pass the data to data into generic arraylist and then query the result using get() method.
You are making simple thing difficult.
Just use a HashMap with name as the keys and test-score as the values.
You open file
You read each line and translate each line to an entry of hash map
When a text is input to the console, you just get it from hash map, if existed return the value, if not then back to number 3
im trying to run a simulator and there are several problems, primarily....
-the code isn't printing out the values at the end of the program
- the code does not actually create the file
-I'm pretty tired so forgive any foolish mistakes I made or details I have left out.
I've searched the website and I found this
What is the simplest way to write a text file in java
and
how to write to text file outside of netbeans
I thought i could edit code from the first link to work for me, but that did not work( whcih is what you see here)
the second page looks more simple but there's no surrounding code so im not sure what the context is and how I would implement it
import java.util.Random;
import java.util.Scanner;
import java.io.*;
/*
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
*/
public class SimClass {
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in) ;
Random randomNumbers = new Random();
//create object from random class
//create self explanaroty input parameters
int pkt_in_q = 0 ;
int pkt_dropped = 0;
int input ;
int output ;
int buffer ;
int x ;
double y ;
//ask for values for buffer size. input rate, output rate
y = randomNumbers.nextDouble();
//attempt to assign a random number to the variable and
/*here you should get user input.
buffer size, # of repitions , if
*/
//fix this
System.out.print("Enter an integer for the input rate ");
input = keyboard.nextInt();
System.out.print("Enter an integer for the output rate ");
output = keyboard.nextInt();
System.out.print("What is the buffer size ");
buffer = keyboard.nextInt();
for (x = 1000000; x >=0 ; x--)
{ /*
simulate # of packets dropped/in the que,
create file, write results to file, output results,
*/
if (y > input/(output/buffer))
{
if (pkt_in_q < buffer)
{
pkt_in_q++ ;
}
else
{
pkt_dropped++ ;
}
//if statement should terminate here
}
else
if (pkt_in_q > 0)
{
pkt_in_q -- ;
}
}
/*
create file, write results to file, output results,
*/
try { /*this seeems to be the problem, the program is either not doing
anything with this or not making the results visible
*/
String content =( " pkt_in_q is " + pkt_in_q +
"pkt_dropped is " + pkt_dropped);
File file = new File("C:/Temp/inputFile.txt");
// if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
try (BufferedWriter bw = new BufferedWriter(fw))
{
bw.write(content);
bw.close();
}
System.out.println("packets dropped value is = " +
pkt_dropped + "packets in q value is = " + pkt_in_q);
}
catch (IOException e)
{
//e.printStackTrace();
}
}
}
I think Code not executing due to file path error.
File file = new File("C:/Temp/inputFile.txt");
There is no folder called "Temp" in the C: drive. If u create Temp folder manually then the code will execute successfully.
File file = new File("D:/Temp/inputFile.txt");
I have created "Temp" folder in D: drive and code executed successfully.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
//create object from random class
//create self explanaroty input parameters
int pkt_in_q = 0;
int pkt_dropped = 0;
int input;
int output;
int buffer;
int x;
double y;
//ask for values for buffer size. input rate, output rate
y = randomNumbers.nextDouble() * 10;
System.out.println("Y++++++" + y);
//attempt to assign a random number to the variable and
/*here you should get user input.
buffer size, # of repitions , if
*/
//fix this
System.out.print("Enter an integer for the input rate ");
input = keyboard.nextInt();
System.out.print("Enter an integer for the output rate ");
output = keyboard.nextInt();
System.out.print("What is the buffer size ");
buffer = keyboard.nextInt();
for (x = 1000000; x >= 0; x--) { /*
simulate # of packets dropped/in the que,
create file, write results to file, output results,
*/
if (y > input / (output / buffer)) {
if (pkt_in_q < buffer) {
pkt_in_q++;
} else {
pkt_dropped++;
}
//if statement should terminate here
} else if (pkt_in_q > 0) {
pkt_in_q--;
}
}
/*
create file, write results to file, output results,
*/
try { /*this seeems to be the problem, the program is either not doing
anything with this or not making the results visible
*/
String content = (" pkt_in_q is " + pkt_in_q + "pkt_dropped is " + pkt_dropped);
String folderPath = "D:" + File.separator + "Temp";
String fileName = folderPath + File.separator + "inputFile.txt";
File folder = new File(folderPath);
File file = new File(fileName);
folder.mkdir();
// if file doesnt exists, then create it
if (!file.exists()) {
//file.mkdir();
file.createNewFile();
System.out.println("File created");
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
try {
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("packets dropped value is = " + pkt_dropped
+ "packets in q value is = " + pkt_in_q);
} catch (IOException e) {
//e.printStackTrace();
}
}
Corrected the code check this and change the file directory and folder directory according to your requirement.
Correction for details:
First you can't define a try block like below
try (BufferedWriter bw = new BufferedWriter(fw))
It should be defined like
try{
}
catch(IOException e)
{
//do something
}
Modified code for that is like below:
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
try
{
bw.write(content);
bw.close();
}
catch (IOException e)
{
//e.printStackTrace();
}
Second you have to create the directory first post that you can create the file inside the directory. so just modified the code to get the directory created and file created.
String folderPath = "D:" + File.separator + "Temp";
String fileName = folderPath + File.separator + "inputFile.txt";
File folder = new File(folderPath);
File file = new File(fileName);
folder.mkdir();
Hope it clarifies your doubt.
I am making an app that keeps username and scores from a game in a txt file. The concept is that when it writes a new username and score to the txt file it should open the .txt file, read it and then make a clone of it adding a new uername and score entry in the txt file.
I am thinking of making this with 2 object arrays. The first is the one that is read in and the new will be the one is writen which will have one more entry.
So if player[i] is readen player[i+1] should be writen with new entry.
I am giving u the code below!
private Player[] myplayer=null;
private Player[] mynewplayer=null;
//open Players.txt
int i;
int n;
String filename="players.txt";
try
{
FileReader fp=new FileReader(filename);
BufferedReader bf=new BufferedReader(fp);
n=Integer.parseInt(bf.readLine());
myplayer=new Player[n];
int x=n+1;
mynewplayer=new Player[x];
for(i=0;i<n;i++)
{
String s=bf.readLine();
String user="",score="";
user=s.substring(0,s.indexOf(","));
s=s.substring(s.indexOf(",")+1);
score=s;
myplayer[i]=new Player(user,Double.parseDouble(score));
for(i=0;i<n;i++)
{
mynewplayer[i]= myplayer[i];
}
mynewplayer[x]=new Player(Username,Double.parseDouble(score));
}
bf.close();
fp.close();
}catch(IOException e)
{
System.out.println("Exception was "+e.getMessage());
}
//----------------------------------WRITE mytxt!-------------
n=myplayer.length;
try
{
filename="players.txt";
FileWriter fp=new FileWriter(filename);
fp.write(""+n+"\n");
for(i=0;i<n+1;i++)
fp.write(""+mynewplayer[i]+"\n");
fp.close();
}catch(IOException e)
{
System.out.println("Exception was "+e.getMessage());
}
//----------------------------------WRITE mytxt!-----------
//Get on Message
String s="";
for(i=0;i<mynewplayer.length;i++)
s=s+mynewplayer[i]+"\n";
JOptionPane.showMessageDialog(null,"Players are \n "+s);
Problem is that when it's written, it returns null for mynewplayer.
I suppose the mynewplayer doesnt really take the entries of the "myplayer" but neither writes the new username.
Compile doesnt show any errors. Just writes NULL to the textfile.
Ask me if u want further info on the code writen!
Thanks in advance!
Here is an edited version of your code, with some improvements and there should be a comment around code that I changed, explaining what I did.
Player[] myPlayer = null; // first word uncapitalized, every
Player[] myNewPlayer = null; // other word begins with a capital
//open Players.txt
int i, n; // combine the variables into 1 line
String filename = "players.txt";
try {
FileReader fp = new FileReader(filename);
BufferedReader bf = new BufferedReader(fp);
n = Integer.parseInt(bf.readLine());
// not needed
//myPlayer = new Player[n];
// NOT NEEDED int x = n + 1;
myNewPlayer = new Player[n + 1];
for (i = 0; i < n; i++) {
String s = bf.readLine();
String user, score; // combine variables, doesnt need to initalize them
String[] items = s.split(","); // Splits the line into array elements on every delimiter -> ,
//user = s.substring(0, s.indexOf(","));
//s = s.substring(s.indexOf(",") + 1);
//score = s;
user = items[0];
score = items[1];
// this line below isnt actually needed
//myPlayer[i] = new Player(user, Double.parseDouble(score));
// Create a new player clone, dont copy the previous one
myNewPlayer[i] = new Player(user, Double.parseDouble(score));
}
// We've read all the variables from the text file, now we create the last one
// Since myNewPlayer is (n+1) size, the range of the array is
// 0 to n
// the last index will be n New Score Variable
myNewPlayer[n] = new Player("Username variable", Double.parseDouble("22"));
bf.close();
fp.close();
} catch (IOException e) {
System.out.println("Exception was " + e.getMessage());
}
//----------------------------------WRITE mytxt!-------------
// This is called a ternary operator
// it is a 1 line if statement
// the format is like so
// booleanLogic ? trueAnswer Execution : falseAnswer Execution;
// if () { true }else { false }
n = myNewPlayer != null ? myNewPlayer.length : 0;
// CHANGED HERE - was using the first array rather than second
// dont need the 1st array
try {
filename = "players.txt";
FileWriter fp = new FileWriter(filename);
// Dont need "" before the items
fp.write(n + "\n");
for (i = 0; i < n; i++) {
fp.write(myNewPlayer[i] + "\n");
}
fp.close();
} catch (IOException e) {
System.out.println("Exception was " + e.getMessage());
}
//----------------------------------WRITE mytxt!-----------
//Get on Message
String s = "";
for (i = 0; i < myNewPlayer.length; i++) {
// s += ""; is like doing s = s + "";
s += myNewPlayer[i] + "\n";
}
JOptionPane.showMessageDialog(null, "Players are \n " + s);
I believe that your problem is this:
for(i=0;i<n;i++)
{
String s=bf.readLine();
String user="",score="";
user=s.substring(0,s.indexOf(","));
s=s.substring(s.indexOf(",")+1);
score=s;
myplayer[i]=new Player(user,Double.parseDouble(score));
for(i=0;i<n;i++)
{
mynewplayer[i]= myplayer[i];
}
mynewplayer[x]=new Player(Username,Double.parseDouble(score));
}
You have nested loops, which is fine, but they use the same counter (the variable i ).
So what is happening is the first line of the file is read, and then added to myplayer[0]. However, instead of just also adding it to mynewplayer[0], you start another loop on i. This loop:
for(i=0;i<n;i++)
{
mynewplayer[i]= myplayer[i];
}
is going to copy the first player into mynewplayer[0]...and then null into every other entry (since myplayer only has the firsdt element filled.
The problem is that after that loop completes, i will equal n, so when you get back to the top of the outer loop, the check $i
Perhaps what you should do is this:
for(i=0;i<n;i++)
{
String s=bf.readLine();
String user="",score="";
user=s.substring(0,s.indexOf(","));
s=s.substring(s.indexOf(",")+1);
score=s;
myplayer[i]=new Player(user,Double.parseDouble(score));
mynewplayer[i]= new Player(user,Double.parseDouble(score));
}
mynewplayer[x]=new Player(<the new username>,Double.parseDouble(<the new score>));
I'm working on a project that takes in criteria supplied by a user, and compares it to an already created list of object containing similar criteria.
Currently, I'm trying to get the program to read the file, but I keep getting my exception and not what I want. My code for the scanner and file is as followed:
package project205;
import java.util.*;
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class HouseList {
ArrayList<House> houseList = new ArrayList<House>();
public HouseList(String fileName)
{
//Open the data file
Scanner myFileIn = null;
try
{
myFileIn = new Scanner(new File("houses.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File: " + "houses.txt" + " is not found");
}
// First piece of data is the number of records
int numRecords = myFileIn.nextInt();
String address1;
int price1;
int area1;
int numBedroom1;
// Temp variable to accumulate the sum
//double sum = 0.0;
//Read the data line by line and build the
//array lists containing names and incomes
for (int k = 0; k < numRecords; k++)
{
address1 = myFileIn.next();
price1 = myFileIn.nextInt();
area1 = myFileIn.nextInt();
numBedroom1 = myFileIn.nextInt();
House house1 = new House(address1, price1, area1, numBedroom1);
houseList.add(house1);
}
// Close the input file
myFileIn.close();
}
public String getHouses(Criteria c)
{
String result = "";
for(int i = 0; i < houseList.size(); i++)
{
House h1 = houseList.get(i);
if (h1.satisfies(c))
{
result = result + h1.toString();
}
}
return result;
}
public void printHouses(Criteria c)
{
System.out.println(getHouses(c));
}
}
My file is in the same package, as I am using eclipse, but I keep getting "File: houses.txt is not found". To be thourough, the error I get is :
File: houses.txt is not found
Exception in thread "main" java.lang.NullPointerException
at project205.HouseList.<init>(HouseList.java:29)
at project205.HouseListTester.main(HouseListTester.java:7)
If anyone could even point me in the direction of what I'm missing here I would greatly appreciate it!
This may help you:
//creating File instance to reference text file in Java
File text = new File("<file location>/houses.txt");
//Creating Scanner instnace to read File in Java
Scanner scnr = new Scanner(text);
//Reading each line of file using Scanner class
while(scnr.hasNextLine()){
//process file
}
Use
System.getProperty("user.dir") + System.getProperty("file.separator") + "houses.txt"
to get the file path if houses.txt and the class file from which you are trying to access shares the same directory.
you can modify
myFileIn = new Scanner(new File("houses.txt"));
//to
myFileIn = new Scanner(new File(System.getProperty("user.dir") + System.getProperty("file.separator") + "houses.txt"));
//or
myFileIn = new Scanner(new File(System.getProperty("file.separator") + "houses.txt"));
Other case is that the file is in some other directory. In this scenario, provide relative path of this file ex.
//current dir is c: and your file is in d: then do
myFileIn = new Scanner(new File("addRelativeFilePathHere" + "houses.txt"));
Above, you need to end addRelativeFilePathHere with file.separator or prefix houses.txt with file separator.
This link to see what these properties points to and their meanings and for more inormation
http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html and
http://docs.oracle.com/javase/7/docs/api/java/io/File.html
I'm having issues reading and storing only integers from a text file. I'm using a int array so I want to do this without list. I'm getting a input mismatch exception, and I don't know how I should go about correcting that issue. The text files being read from also include strings.
public static Integer[] readFileReturnIntegers(String filename) {
Integer[] array = new Integer[1000];
int i = 0;
//connect to the file
File file = new File(filename);
Scanner inputFile = null;
try {
inputFile = new Scanner(file);
}
//If file not found-error message
catch (FileNotFoundException Exception) {
System.out.println("File not found!");
}
//if connected, read file
if(inputFile != null){
System.out.print("number of integers in file \""
+ filename + "\" = \n");
//loop through file for integers and store in array
while (inputFile.hasNext()) {
array[i] = inputFile.nextInt();
i++;
}
inputFile.close();
}
return array;
}
You might use something like this (to skip over any non-int(s)), and you should close your Scanner!
// if connected, read file
if (inputFile != null) {
System.out.print("number of integers in file \""
+ filename + "\" = \n");
// loop through file for integers and store in array
try {
while (inputFile.hasNext()) {
if (inputFile.hasNextInt()) {
array[i] = inputFile.nextInt();
i++;
} else {
inputFile.next();
}
}
} finally {
inputFile.close();
}
// I think you wanted to print it.
System.out.println(i);
for (int v = 0; v < i; v++) {
System.out.printf("array[%d] = %d\n", v, array[v]);
}
}
Change hasNext() to hasNextInt() in your while loop.
What you need to do is before you get a new value and try to put it into the array you need to check to make sure that it is in fact an int and if it isn't then skip over it and move on to the next value. Alternately you could make a string array of all of the values and then copy only the integers into a separate array. However, the first solution is probably the better of the two.
Also... As has been mentioned in the comments it tends to be easier to read the integers in as strings and then parse the values from them...