I have a simple question. My program asks the user to type a name, range, and length to generate random numbers. The result will be printed into a file from the console. I want to know is it possible to print to the console that the file has been printed when it's done.
Currently this is my set up to print to a file:
Scanner s = new Scanner(System.in);
System.out.println("-----------------------------------------------");
System.out.println("Choose a name to your file: ");
String fn = s.nextLine();
System.out.println("-----------------------------------------------");
System.out.println("Choose your range: ");
String rn = s.nextLine();
System.out.println("-----------------------------------------------");
System.out.println("Choose your length of array: ");
String ln = s.nextLine();
System.out.println("-----------------------------------------------");
int rangeToInt = Integer.parseInt(rn);
int lengthToInt = Integer.parseInt(ln);
File file = new File(fn +".txt");
PrintStream stream = new PrintStream(file);
//System.out.println("File Has been Printed");
System.setOut(stream);
int[] result = getRandomNumbersWithNoDuplicates(rangeToInt, lengthToInt);
for(int i = 0; i < result.length; i++) {
Arrays.sort(result);
System.out.println(result[i] + " ");
}
System.out.println("Current Time in Millieseconds = " + System.currentTimeMillis());
System.out.println("\nNumber of element in the array are: " + result.length + "\n");
}// end of main
```
Don't call System.setOut. When you do that, you can no longer print to the console. Instead of System.out.println to write to the file, just... stream.println to write to the file. Then you can use System.out to print to the console.
I am looking for a little help. I have done quite a bit of googling with little success.
I am new to programming and am sure this is a silly oversight on my part.
The below code is intended to read through a .txt document that is tab delimited. The .txt file is formatted into six columns. Currently, as I move through the file I parse the string to the appropriate value type and assign it to its respective variable. Code is here:
try {
s = new Scanner(new BufferedReader(new FileReader(file))).useDelimiter("\t");
while (s.hasNextLine()) {
group = Integer.parseInt(s.next());
death = Integer.parseInt(s.next());
name = s.next();
sex = s.next();
age = Integer.parseInt(s.next());
fare = Double.parseDouble(s.next());
System.out.println("Class = " + group); // Test that value is being assigned
System.out.println("Death = " + death); // Test that value is being assigned
System.out.println("Name = " + name); // Test that value is being assigned
System.out.println("Gender = " + sex); // Test that value is being assigned
System.out.println("Age = " + age); // Test that value is being assigned
System.out.println("Fare = " + fare); // Test that value is being assigned
}
} finally {
if (s != null) {
s.close();
}
}
When I reach the last column of the first row, the variable fare is set to row 1 column 6 AND row 2 column 1. For some reason the line break is not triggering the while loop to restart.
Can anyone help me understand why the while loop does not restart at the end of the line?
File looks like this:
1 5 Bryan male 25 211.3375
1 2 Jimmy male 22 151.5500
There is about 1200 lines of this. When running this loop I get the below error when attempting to set fare = 211.3375 at the end of the first row. For some reason, the line break isn't resetting the loop. I can only assume that the line break is not interpreted as a tab but do not know how to correct this.
Exception in thread "main" java.lang.NumberFormatException: For input string: "211.3375
1"
You're checking Scanner#hasNextLine() but then reading multiple Scanner#next(), a dangerous thing to do. I suggest if you check for next line, you should read next line, and then parse through that line.
e.g.,
while (s.hasNextLine()) {
String line = s.nextLine();
Scanner lineScanner = new Scanner(line);
group = lineScanner.nextInt();
death = lineScanner.nextInt();
name = lineScanner.next();
sex = lineScanner.next();
age = lineScanner.nextInt();
fare = lineScanner.nextDouble();
lineScanner.close();
System.out.println("Class = " + group); // Test that value is being assigned
System.out.println("Death = " + death); // Test that value is being assigned
System.out.println("Name = " + name); // Test that value is being assigned
System.out.println("Gender = " + sex); // Test that value is being assigned
System.out.println("Age = " + age); // Test that value is being assigned
System.out.println("Fare = " + fare); // Test that value is being assigned
}
But even this is somewhat dangerous because I'm calling Scanner#next...() without first checking. And so perhaps safer would be to do
String[] tokens = line.split("\\s+");
Then count the tokens length to be sure that it's right, and then parse each individual token that needs parsing to numeric type.
Or you could do something like:
while (s.hasNextLine()) {
String line = s.nextLine();
Scanner lineScanner = new Scanner(line);
if (lineScanner.hasNextInt()) {
group = lineScanner.nextInt();
}
if (lineScanner.hasNextInt()) {
death = lineScanner.nextInt();
}
if (lineScanner.hasNext()) {
name = lineScanner.next();
}
if (lineScanner.hasNext()) {
sex = lineScanner.next();
}
if (lineScanner.hasNextInt()) {
age = lineScanner.nextInt();
}
if (lineScanner.hasNextDouble()) {
fare = lineScanner.nextDouble();
}
lineScanner.close();
System.out.println("Class = " + group); // Test that value is being assigned
System.out.println("Death = " + death); // Test that value is being assigned
System.out.println("Name = " + name); // Test that value is being assigned
System.out.println("Gender = " + sex); // Test that value is being assigned
System.out.println("Age = " + age); // Test that value is being assigned
System.out.println("Fare = " + fare); // Test that value is being assigned
}
or use try/catch blocks to check for bad files.
I am currently in my last week of a Java class and our final project requires us to take make a program read a digit and operator (separated by a comma) from a single cell in an Input CSV file, have the program do the math (starting from whatever number I choose, then have the program write the results into an Output CSV file. I have the code down to a conversion error, but I'm sure that is the least of my worries. My understanding of Java is rudimentary and I am pretty much failing the class. I just don't think I have the mind for programming and I have expressed that to the professor. So hopefully I can do well enough on this final project to bump my grade up. Needless to say, I am going to steer away from this degree plan immediately.
-Mike
This is what the Prof wants the output to look like:
Add 2 total 2
Add 6 total 8
Subtract 9 total -1
Multiply 10 total -10
Number of elements = 4, Total = -10, Average = -2.5
Here is the error:
csvRead2.java:37: error: incompatible types: int cannot be converted to String
number[i] = (Integer.parseInt(value[0])); // Change from a String to an integer.
^
import java.io.*;
public class csvRead2 {
public static void main(String args[]) {
String operator[];
String number[];
String total;
int i;
// The name of the file to open.
String inputFile = "mathInput.csv";
// This will reference one line at a time
String line = null;
try { // start monitoring code for Exceptions
// FileReader reads text files in the default encoding.
FileReader read = new FileReader("mathInput.csv");
// Always wrap FileReader in BufferedReader.
BufferedReader buffRead = new BufferedReader(read);
// Assume default encoding.
FileWriter write = new FileWriter("mathOuput.csv", true); // true for append
// Always wrap FileWriter in BufferedWriter.
BufferedWriter buffWrite = new BufferedWriter(write);
// The name of the file to open.
String outputFile = "mathOutput.csv";
while ((line = buffRead.readLine()) != null) {
String[] value = line.split(",");
operator[i] = value[1];
number[i] = (Integer.parseInt(value[0])); // Change from a String to an integer.
// Determine the operator and do the math operation and write to the output file.
if (operator[i].equals("+")) { // if statement for addition operator
total = total + number[i];
buffWrite.write("Add " + number[i] + " total " + total);
buffWrite.newLine();
if (operator[i].equals("-")) { // if statement for subtraction operator
total = total + number[i];
buffWrite.write("Subtract " + number[i] + " total " + total);
buffWrite.newLine();
if (operator[i].equals("*")) { // if statement for multiplication operator
total = total + number[i];
buffWrite.write("Multiply " + number[i] + " total " + total);
buffWrite.newLine();
if (operator[i].equals("/")) { // if statement for division operator
total = total + number[i];
buffWrite.write("Divide " + number[i] + " total " + total);
buffWrite.newLine();
if (operator[i].equals("=")) { // if statement for equals operator
buffWrite.newLine();
}
}
}
}
}
}
// closing BufferedReader and BufferedWriter
buffRead.close();
buffWrite.close();
}
catch(FileNotFoundException ex) { // will catch if file is not found
System.out.println( "Unable to open file '" + inputFile + "'");
}
catch(IOException ex) // catches read and write errors
{
ex.printStackTrace(); // will print read or write error
}
}
}
String number[] should be int number[]. If you are operating on integers, change the data type to int for respective variables. Strings can't be used for addition of numbers.
Even after you fix above exception, you are not flushing the write operation. buffWrite.flush() is required to write data into file. Call flush() before you call close() on bufWrite.
EDIT: There are many logical errors and they have been addressed.
import java.io.*;
public class CSVRead2 {
public static void main(String args[]) {
String operator[] = new String[1];
int number[] = new int[1];
int total = 0;
int i=0;
// The name of the file to open.
String inputFile = "mathInput.csv";
// This will reference one line at a time
String line = null;
try { // start monitoring code for Exceptions
// FileReader reads text files in the default encoding.
FileReader read = new FileReader("mathInput.csv");
// Always wrap FileReader in BufferedReader.
BufferedReader buffRead = new BufferedReader(read);
// Assume default encoding.
FileWriter write = new FileWriter("mathOuput.csv", true); // true for append
// Always wrap FileWriter in BufferedWriter.
BufferedWriter buffWrite = new BufferedWriter(write);
// The name of the file to open.
String outputFile = "mathOutput.csv";
while ((line = buffRead.readLine()) != null) {
String[] value = line.split(",");
operator[i] = value[1];
number[i] = (Integer.parseInt(value[0])); // Change from a String to an integer.
// Determine the operator and do the math operation and write to the output file.
if (operator[i].equals("+")) { // if statement for addition operator
total = total + number[i];
buffWrite.write("Add " + number[i] + " total " + total);
buffWrite.newLine();
}else if (operator[i].equals("-")) { // if statement for subtraction operator
total = total - number[i];
buffWrite.write("Subtract " + number[i] + " total " + total);
buffWrite.newLine();
}
else if (operator[i].equals("*")) { // if statement for multiplication operator
total = total + number[i];
buffWrite.write("Multiply " + number[i] + " total " + total);
buffWrite.newLine();
}
else if (operator[i].equals("/")) { // if statement for division operator
total = total + number[i];
buffWrite.write("Divide " + number[i] + " total " + total);
buffWrite.newLine();
}
else if (operator[i].equals("=")) { // if statement for equals operator
buffWrite.newLine();
}
}
buffWrite.flush();
// closing BufferedReader and BufferedWriter
buffRead.close();
buffWrite.close();
}
catch(FileNotFoundException ex) { // will catch if file is not found
System.out.println( "Unable to open file '" + inputFile + "'");
}
catch(IOException ex) // catches read and write errors
{
ex.printStackTrace(); // will print read or write error
}
}
}
EDIT 2:
mathinput.csv ( no empty lines in the file)
2,+
3,+
9,-
mathOutput.csv
Add 2 total 2
Add 3 total 5
Subtract 9 total -4
First, change the type of number array from String[] to int[]. You are storing an integer into an array of strings, hence the exception.
value is an array of String and number is also an array of String.
Now you're taking a string out of value parse it to an integer and try to put it into a string array again!
You could change the type of String number[] to int number[]!
The same goes for your variable total! Since you store an Integer value in there you should change it's type to int total
EDIT:
Also i noticed you are chaining the if-blocks! I think you might want to think about that concept again! If you receive a "-", your first if-block (if (operator[i].equals("+"))) will result in false and all code in that if-block will not be executed!
I am trying to build a string like 11 11 but I am facing problem I am getting for start the following string 98 11 and not 11 11.
How can I fix that?
I appreciate any help.
Character number = newName.charAt(2); //here number is 1
Character numberBefore = newName.charAt(1); //here numberBefore is 1
try (PrintWriter writer = new PrintWriter(path+File.separator+newName);
Scanner scanner = new Scanner(file)) {
boolean shouldPrint = false;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(numberBefore >0 ){
String start= number+number+" "+number+number; //here start is `98 11`
}
Yes, this is due to the associativity of +.
This:
String start= number+number+" "+number+number;
is effectively:
String start = (((number + number) + " ") + number) + number;
So you're getting number + number (which is performing numeric promotion to int) and then string concatenation.
It sounds like you want:
String numberString = String.valueOf(number);
String start = numberString + numberString + " " + numberString + numberString;
Or alternatively:
String start = String.format("%0c%0c %0c%0c", number);
yes this is because of associativity of +
you can try the below code also
String c1 =Character.toString(number);
String s =c1+c1+" "+c1+c1;
String newName = "111";
Character number = newName.charAt(2); // here number is 1
Character numberBefore = newName.charAt(1); // here numberBefore is 1
if (Character.getNumericValue(numberBefore) > 0) { // checking against numeric rather than ascii
System.out.println("ASCII value of char " + (int) number); // ASCII code for '1' = 49
String start = String.valueOf(number) + String.valueOf(number) + " " + number + number; // here start is `98 11`
System.out.println(start);
}
}
I want to write each elements of arrays into a text file. Eg below will demonstrate more clearly
String[] Name = {"Eric","Matt","Dave"}
Int[] Scores = {[45,56,59,74],[43,67,77,97],[56,78,98,87]}
double[] average = {45.7,77.3,67.4}
I want the following in the text file
Student Eric scored 45,56,59,74 with average of 45.7
Student Matt scored 43,67,77,97 with average of 77.3
Student Dave scored 56,78,98,87 with average of 67.4
I created output file
PrintStream output = new PrintStream(new File("output.txt"));
I used a for loop
for(int i =0;i<=Name.length;i++){
output.println("Student " + Name[i] + " scored " + Scores[i] + " with average of " + average[i]);
}
But this did not work. Please help.
My guess is the compiler didn't like this line:
Int[] Scores = {[45,56,59,74],[43,67,77,97],[56,78,98,87]}
There is not an Int type in Java. Assuming you mean int, the compiler will still complain because [45,56,59,74] is not an int!
What you need is an int[][] and a declaration like: {{45,56,59,74}}
Still, I'm not sure you will be happy with the output...
maybe you forgot to flush or close the PrintStream (I also fixed the errors mentioned above)
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class Main {
public static void main(String[] args) {
String[] Name = {"Eric","Matt","Dave"};
int[][] Scores = {{45,56,59,74},{43,67,77,97},{56,78,98,87}};
double[] average = {45.7,77.3,67.4};
try (
PrintStream output = new PrintStream(new File("output.txt"));
){
for(int i =0;i<Name.length;i++){
String sc ="";
for (int j=0;j<Scores[i].length;j++){
sc+=Scores[i][j]+" ";
}
output.println("Student " + Name[i] + " scored " + sc + " with average of " + average[i]);
}
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
note that this is java7 syntax (the try..catch block with the () )
see: http://blog.sanaulla.info/2011/07/10/java-7-project-coin-try-with-resources-explained-with-examples/
two-dimensional arrays need two brackets instead of one,
Int should be lower-case,
variables should be lower case (scores instead of Scores).
so it should look like this:
int[][] scores = {{45,56,59,74},{43,67,77,97},{56,78,98,87}};
also, the for-loop should run from 0 to one less than length or else you'll go out of bounds.
names.length = 3
names[0] = "Eric"
names[1] = "Matt"
names[2] = "Dave"
so, when you try to access names[3], you'll get an out-of-bounds exception because the array only contains 3 elements.
You must use the FileWriter instead of the PrintStream.
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
"C:/new.txt"), true));
StringBuffer sb = new StringBuffer();
for(int i =0;i<=Name.length;i++){
sb.append("Student " + Name[i] + " scored " + Scores[i]
+ " with average of " + average[i] + "\n");
}
bw.write(sb.toString());
bw.close();