I'm trying to write a program that takes an array of 200 numbers (1-200), randomizes them, and then outputs those numbers to a text file.
I've been struggling for the whole day and I can't figure out why nothing is working.
Main method:
public static void main (String[] args)
{
int[] numbers= new int [201];
for (int i=0; i < numbers.length; i++)
{
numbers[i]=i;
}
}//end main method
Randomize method:
public static int[] randomizeArray(int[] numbers)
{
Random gen= new Random(10);
for (int i=0; i < numbers.length; i++)
{
int n= gen.nextInt(200);
numbers[i]=n;
}
return numbers;
}//end randomizeArray method
And the print method:
public static int[] outputArray(int[] numbers) throws IOException
{
FileOutputStream output;
output= new FileOutputStream("RandomOut.txt");
new PrintStream(output).println(randomizeArray(numbers));
output.close();
return numbers;
}//end method outputArray
Any help would be great, I know I'm overlooking something or doing something incorrectly.
Shouldn't you call outputArray at the end of your main method?
One of your problems is the line:
new PrintStream(output).println(randomizeArray(numbers));
This will probably print something like:
[I#10769dd
yes? You need to write a for loop to output the numbers, something like:
for (int i=0; i < numbers.length; i++) {
new PrintStream(output).println(numbers[i]);
}
except that you don't want to create the PrintStream each time in the loop.
Your main method initializes an array of 201 elements (instead of 200), and doesn't do anything with this array. So obviously, there is no randomization and now writing to any file. The main method should call randomizeArray and then outputArray.
The initialization of the array elements in main is useless, since the elements will be reinitialized by the randomizeArray method. This method, by the way, doesn't need to return anything.
Finally, the outputArray method should loop through the array and println each element. The stream should be closed in a finally block. It should not return anything either.
1) you need to use Arrays.toString(int[] arr) to print that array.
2) if you mean to reorder the array input, that requires code tht is very diferent.
otherwise, get rid of the input and use a new array.
3) call your helper methods!
EDIT: added this psuedocode:
boolean[] used=new boolean[200];
make old[] and new[]
for(i=0;i<200;i++){
int n=random number from 0 to 199;
while(used[n]) n=(n+1)%200;
new[i]=old[n];
used[n]=true;
}
return new;
Couldn't resist...
String filename = "random200.txt";
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 1; i < 201; i++)
{
numbers.add(i);
}
StringBuilder sb = new StringBuilder();
while (!numbers.isEmpty())
{
int position = new SecureRandom().nextInt(numbers.size());
Integer randomNumber = numbers.remove(position);
sb.append(randomNumber + "\n");
}
try
{
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "UTF8"));
out.append(sb.toString());
out.close();
}
catch (Exception ex)
{
throw new RuntimeException(ex);
}
Related
Here are the instructions:
Exercise 2
Write a program in a single file that:
Main:
Creates 10 random doubles, all between 1 and 11,
Calls a method that writes 10 random doubles to a text file, one number per line.
Calls a method that reads the text file and displays all the doubles and their sum accurate to two decimal places.
SAMPLE OUTPUT
10.6269119604172
2.737790338909455
5.427925738865128
1.3742058065472509
1.1858700262498836
4.180391276485228
4.910969998930675
5.710858234343958
7.790857007373052
3.1806714736219543
The total is 47.13
I have it all written but nothing is coming out on the txt file. I need help with the second method because I think I need to change something but I'm not sure what.
public class Program2 {
public static void main(String[] args) {
double[] nums = new double[10];
for (int i = 0; i < nums.length; i++) {
nums[i] = 1 + Math.random() * 11;
}
printNum(nums);
sumNum(nums);
}
public static void printNum(double[] values) {
try {
java.io.File randomNums = new java.io.File("Project1.txt");
randomNums.createNewFile();
java.io.PrintWriter output = new java.io.PrintWriter(randomNums);
for (int i = 0; i < values.length; i++) {
output.println(i);
}
}
catch (Exception ex) {
System.out.print("EX");
}
}
public static void sumNum(double[] ints) {
Scanner input = new Scanner("Project1.txt");
double sum = 0;
for (int i = 0; i < ints.length; i++) {
sum = sum + i;
}
System.out.printf("\n%-.2f", "The total is ", sum);
input.close();
}
}
Method printNum
There are two reasons why you may see no output in the file: Some error occurred or the file is not flushed/closed by the time you read from it.
Be sure to flush and close the PrintWriter before leaving the method:
output.flush();
output.close();
In case some error occurs, you just print EX, hiding what is actually going on. So use this catch block:
catch (Exception ex) {
System.out.print("EX");
ex.printStackTrace(System.out);
}
Read what the program is trying to tell you.
And last but not least: You are not printing the random numbers but the loop count. Use this:
for (int i = 0; i < values.length; i++) {
output.println(values[i]);
}
Method sumNum
You need to open the file for reading. Your line does not do it:
Scanner input = new Scanner("Project1.txt");
Use this instead:
Scanner input = new Scanner(new File("Project1.txt"));
Next, you are not reading from the scanner. Inside your loop use
sum = sum + input.nextDouble();
input.nextLine();
Finally you need to print the result, as mentioned by OldProgrammer:
System.out.printf("The total is %f", sum);
Main method
The random numbers you generate are not in the defined range. You can figure this out.
My code will not compile and I can not figure out how to fix the error. It is a compile time run error I think. My error is in my method to print out array. Then, it says that there is something wrong with my closing bracket for the class. I am using a scanner class and I did import it, it is just not shown. Any help?
My code:
public static void main (String[] args){
int[] getArray; //reference to an int array of type and takes no parameters
System.out.println("How many numbers would you like to enter?" );
int size = scan.nextInt();
int[] nums; //reference to nums array of type int
nums = new int[size]; /* new array of type int. assigned to nums.
size, to specify number of elements array will have */
for(int i=0; i<nums.length; i++){
System.out.println("Enter a number." +(i+1)+ "left");
nums[i] = scan.nextInt(); //storing user input into array
return nums;
}//closing for loop
int[] minimumValue;
min = scan.nextInt();
min = nums[0]; //assigning min value to first element in array
return min;
for(int i=0; i<min.length; i++){
if(i<min){
min = nums[0];
}
}
return min;
public static void printArray (int[] getArray){ //method to print out array
for(int i = 0; i < nums.length; i++){
System.out.print(nums.length); //print out array
}
}
public static void printArrayInReverse(int[] getArray){ //method for arrayInReverse
for(int i = nums.length - 1; i >= 0; i--){
System.out.print(nums[i]);
}
}
int[] numbers = getArray();// calling getArray method
public static void main (String[] args){
System.out.print("************");
printArray(numbers); //calling printArray method and passing numbers through it
printArrayInReverse(numbers);// calling printArrayInReverse method and passing numbers through it
System.out.print(minimumValue(numbers)); /* calling minVal through print statement and passing
numbers through it*/
}
}
}
It is very hard to tell what you are trying to accomplish here from your code. There is no class here which means your program will not even compile, please remember to post all applicable code to your question as it makes it easier for people to help you.
Firstly, you can only have one entry point (ie. main(String[] args) for each class. This is better explained here Can there exist two main methods in a Java program?.
Within this main method, you cannot have any other methods, you can only call other methods and perform operations ad such.
The variable "scan" cannot ever do anything if it is not instantiated prior to use. The variable getArray is being used as a method, which it is not.
Please take a look at Simple Java array program where it shows more in-depth how to use arrays.
Take a look at this as see if it even accomplishes what you want to do, which is still somewhat unclear. I shortened everything so that it is simpler, with a program this small multiple methods are not needed unless there is some logic to denote when to print the array or when to print the array reversed.
import java.util.Scanner;
public class CLASSNAME {
static Scanner scan = new Scanner(System.in);
static int[] nums;
public static void main(String[] args){
// Get Size Of Array
System.out.println("How many numbers would you like to enter?" );
int size = scan.nextInt();
nums = new int[size];
// Fill Array
for(int i = 0; i < nums.length; i++){
System.out.println("Enter a number." +(i+1)+ "left");
nums[i] = scan.nextInt();
}
// Set 0th Number To
System.out.println("Enter 0th Number");
int min = scan.nextInt();
nums[0] = min;
// Print Array
System.out.println("\n" + "Printing Array Index 0 -> ArraySize");
for(int i = 0; i < nums.length; i++){
System.out.print(nums.length);
}
// Print Array Reversed
System.out.println("\n" + "Printing Array Index ArraySize -> 0");
for(int i = nums.length - 1; i >= 0; i--){
System.out.print(nums[i]);
}
}
}
you need to create a Scanner object to use it
you can't create more than one main method
you must create methods outside the main method
Example:
import java.util.Scanner;
public class a {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//code here
}
public static void method_name() {
//code here
}
//If you want to return integer value for example
public static int method_name() {
//code here
}
}
I'm writing some code to read an input file of book titles, and putting the read lines into an array and trying to print out the array. But when I try to print out the array, it just returns 'null' for each read line. I'm not sure what I'm doing wrong or what my code is doing. Any suggestions? Thanks!
Code:
import java.io.*;
import java.util.*;
public class LibraryInputandOutputs {
public static void main(String args[]) throws IOException{
int lineCount = 0;
File inputFile = new File("bookTitles.inp.txt");
Scanner reader = new Scanner(inputFile);
while(reader.hasNextLine()) {
reader.nextLine();
lineCount++;
}
String[] bookArray = new String[lineCount];
while (reader.hasNextLine()) {
for (int i = 0; i < lineCount; i++) {
bookArray[i] = reader.next();
}
}
for (int k = 0; k < lineCount; k++) {
System.out.println(bookArray[k]);
}
reader.close();
inputFile.close();
}
}
My text file I'm reading from is 20 book titles, all on different lines.
My output on the terminal is 20 lines of null.
Lets break this down:
This reads every line of the input file, counts each one, and then discards them:
while(reader.hasNextLine()) {
reader.nextLine();
lineCount++;
}
You are now at the end of file.
Allocate a string array that is large enough.
String[] bookArray = new String[lineCount];
Attempt to read more lines. The loop will terminate immediately because reader.hasNextLine() will return false. You are already at the end of file.
So you the statement assigning to bookArray[i] won't be executed.
while (reader.hasNextLine()) {
for (int i = 0; i < lineCount; i++) {
bookArray[i] = reader.next();
}
}
Since bookArray[i] = ... was never executed above, all of the array elements will still be null.
for (int k = 0; k < lineCount; k++) {
System.out.println(bookArray[k]);
}
One solution is to open and read the file twice.
Another solution is to "reset" the file back to the beginning. (A bit complicated.)
Another solution would be to use a List rather than an array so that you don't need to read the file twice.
Another solution is to search the javadocs for a method that will read all lines of a file / stream as an array of strings.
(Some of these may be precluded by the requirements of your exercise. You work it out ... )
The nested loop in step 3 is also wrong. You don't need a for loop inside a while loop. You need a single loop that "iterates" the over the lines and also increments the array index (i). They don't both need to be done by the loop statement itself. You could do one or the other (or both) in the loop body.
Stephen C has already pointed out the main problems with your logic. You're trying to loop twice through the file but you've already reached the end of the file the first time. Don't loop twice. "Merge" both the while loops into one, remove that for loop inside the while loop and collect all the book titles. You can then use the size of the list to print them later on. My Java might be rusty but here it goes -
import java.io.*;
import java.util.*;
public class LibraryInputandOutputs {
public static void main(String args[]) throws IOException {
// int lineCount = 0; - You don't need this.
File inputFile = new File("bookTitles.inp.txt");
Scanner reader = new Scanner(inputFile);
// Use an array list to collect book titles.
List<String> bookArray = new ArrayList<>();
// Loop through the file and add titles to the array list.
while(reader.hasNextLine()) {
bookArray.add(reader.nextLine());
// lineCount++; - not needed
}
// Not needed -
// while (reader.hasNextLine()) {
// for (int i = 0; i < lineCount; i++) {
// bookArray[i] = reader.next();
// }
// }
// Use the size method of the array list class to get the length of the list
// and use it for looping.
for (int k = 0; k < bookArray.size(); k++) {
System.out.println(bookArray[k]);
}
reader.close();
inputFile.close();
}
}
I agree with Stephen C. In particular, using a List is usually better than an array because it's more flexible. If you need an array, you can always use toArray() after the List is filled.
Are your book titles on separate lines? If so you might not need a Scanner class, and could use something like a BufferedReader or LineNumberReader.
I am trying to take a set of 25 numbers from a text file and convert it into a array. But I am lost.
I have read some other questions similar to this, but all of them used imports and extras, and I don't want to use any imports besides import java.io.*; nor any list.
Also the for loop within this is method is me just messing with it, because I couldn't figure it out.
public static int[] processFile (String filename) throws IOException, FileNotFoundException {
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
int[] a = new int[25];
while (( line = inputReader.readLine()) != null){
int intValue = Integer.parseInt(line); //converts string into int
for (int i = 0; i < a.length; i++){
a[intValue]++;
}
}
return a;
}
public static void printArray (int[] a) {
for (int i = 0; i<a.length; i++) {
System.out.println (a[i]);
}
}
public static void main(String[] args) throws IOException, FileNotFoundException {
int [] array = processFile("C:\Users\griff_000\Desktop\TestWeek13.txt");
printArray(array);
}
I'm unclear about your whole import restriction, why exactly are you trying to limit the number of imports you have?
Anyway, looking at your code, it seems like the concept of arrays isn't all that clear with you.
Arrays are accessed under the syntax:
array[index] = value;
looking at your code, the line a[intValue]++; is actually finding the array index intValue (the number read from file) and incrementing it by one. Not only is this not what you want, numbers over the array length will cause an ArrayIndexOutOfBoundsException.
Making said amendments we get:
public static int[] processFile (String filename) throws IOException, FileNotFoundException{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
int[] a = new int[25];
int i = 0; // We need to maintain our own iterator when using a while loop
while((line = inputReader.readLine()) != null){
int intValue = Integer.parseInt(line); //converts string into int
a[i] = intValue; // Store intValue into the array at index i
i++; // Increment i
}
return a;
}
note the additional variable i being used in this context to facilitate the incrementing index number being used to access the array. If you examine this method carefully, a input file longer than 25 elements would also throw ArrayIndexOutOfBoundsException due to the variable i becoming 25 (beyond the limits of the array). To fix, I'd suggest changing the loop structure to a for-loop (assuming your input array is of fixed size) as follows:
public static int[] processFile (String filename) throws IOException, FileNotFoundException{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
int[] a = new int[25];
for(int i = 0; i < a.length; i++){
String line = inputReader.readLine(); // Move the readline code inside the loop
if(line == null){
// We hit EOF before we read 25 numbers, deal appropriately
}else{
a[i] = Integer.parseInt(line);
}
}
return a;
}
Note how the for loop integrates the iterator variable into one nice elegant line, keeping the rest of the code neat and readable.
Your mistake is in the line a[intValue]++;. You are telling Java to find the element at [intValue] and add 1 to it's current value. From your question, I understood that you want to put intValue as the array element.
Since you are using i as the iterator, to add the element simply use:
a[i] = intValue;
What you are doing here:
a[intValue]++;
is increasing the array position of the read value by one. If the number read is 2000 you are increasing a[2000]
you might want to do this
a[i]=intValue;
I want to sort a input.txt file and save it in output.txt for instance. I use the insertion sort algorithm. Now my problem: the compareTo method seems to work incorrectly (or at least not how I want to to work). It returns integer greater than 1 thus the algorithm does not really especially for negative numbers. I hope you guys can help me with that problem, thanks!
Thats my code:
import java.util.ArrayList;
import java.io.*;
class Isort
{
public static void main(String[] args)
{
if(args[0].equals("int"))
{
ArrayList<Integer> array = new ArrayList<Integer>();
sort(array, args[1], args[2]);
}
else if(args[0].equals("float"))
{
ArrayList<Float> array = new ArrayList<Float>();
sort(array, args[1], args[2]);
}
else if(args[0].equals("String"))
{
ArrayList<String> array = new ArrayList<String>();
sort(array, args[1], args[2]);
}
else
{
//do nothing
}
}
public static <T extends Comparable<T>> void sort(ArrayList<T> array, String input, String output)
{
try
{
File file = new File(input);
BufferedReader reader = new BufferedReader(new FileReader(file));
reader.mark((int)file.length() + 1);
int count = 0;
while(reader.readLine() != null)
{
count++;
}
reader.reset();
for(int i = 0; i<count; i++)
{
array.add((T)(reader.readLine()));
}
reader.close();
int j;
T temp;
for(int i = 1; i < array.size(); i++)
{
j = i;
while(j > 0 && array.get(j-1).compareTo(array.get(j)) > 0)
{
temp = array.get(j);
array.set(j,array.get(j-1));
array.set(j-1,temp);
j -= 1;
System.out.println(array);
}
}
PrintWriter writer = new PrintWriter(output);
for(int i = 0; i<array.size(); i++)
{
writer.write(String.valueOf(array.get(i)));
writer.write(System.getProperty ("line.separator"));
}
writer.flush();
writer.close();
}
catch(FileNotFoundException e)
{
}
catch(IOException e)
{
e.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
I believe you are confused by the use of generics. You are making generic ArrayLists of Integer, Long and String. You are then reading a line of text and attempting to cast it to T.
This will not do anything at runtime due to type-erasure. In all of the cases above (int, long and string) you will be passing an ArrayList<Object> and adding String to the list. When you read the String from the file the cast doesn't do anything except cast it to an Object which String already is. So unless the compareTo of String matches your requirements for int and long this will not work.
In reply to comment...
That's the point. Casting to T or really using generics at all in this case don't do what you need. In all cases you are reading and comparing String. Instead you need to have three methods readInt, readLong and readString and call the appropriate one based on what you are expecting. One option would be to use an interface of readNextValue and pass in an appropriate implementation depending on the situation.
I suggest you to using a "Comparator" class in "Collections.sort(...)" method. You can find an example here-> http://www.vogella.com/blog/2009/08/04/collections-sort-java/.