Arrays with printwriter and displaying them - java

What im trying to do is make this txt file into an array, then with the numbers that are incorrect(not numbers) put them into the pw wrong.txt and display them
import java.util.*;
import java.io.*;
public class MorenoJonathonTranslator
{
public static void main(String[] args) throws IOException
{
Scanner file = new Scanner(new File("numbers.txt"));
ArrayList<String> alphabeticPhoneNumbers = new ArrayList<String>();
int i = 0;
System.out.println("Original: ");
System.out.println("Numberical: ");
while(file.hasNextLine() ){
alphabeticPhoneNumbers.add(file.next());
alphabeticPhoneNumbers.add(file.next());
file.nextLine();
System.out.println(alphabeticPhoneNumbers.get(i));
i+=2;
}
PrintWriter pw = new PrintWriter("wrong.txt");
for( i = 0; i < 8; i++){
pw.print(alphabeticPhoneNumbers.get(i));
pw.print(alphabeticPhoneNumbers.get(i+1));
pw.println();
i++;
}
pw.close();
}
}

What is it that you're trying to achieve? I'd think that your program is broken and doesn't print anything because you're somehow incrementing i to a value that's already greater than 7 so your second loop doesn't do anything. Just a guess though as I don't know how your data looks like. Try not reusing index variables like i.

I'm not exactly sure what you are trying to achieve. If you only want to display them while the program's execution, you could use a System.out.println within the last for loop.

Related

can I print empty int array withou zero aprearing in java

this is my code can i print my array without zero if it is empty?
import java.util.Arrays;
import java.io.*;
public class Stacks{
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("what is the size of your stack? :");
int size = Integer.parseInt (br.readLine());
int get = size;
int[] Array = new int[size];
System.out.println("type: push , pop , exit");
System.out.println("remember! you can EXIT anytime");
System.out.println(Arrays.toString(Array));
/*there still a code here but this is just what i needed to show..*/
}
}
please help me.. PS I don't want to import stacks..
Since your not using your Array as an array, but ultimately as a stack, you will not want to use Arrays.toString() which is designed for printing arrays as arrays. You need to write your own method, bearing in mind the stack your creating maybe smaller than the size of the array you're populating.
Without knowing how you're stack is implement, a basic model would be
public static String arrayAsStack(int[] array, int elements_in_stack) {
String out = "[";
for(int i=elements_in_stack-1; i>=0; i--)
out += arrary[i] + " ";
out+="]";
return out;
}
This method of course may not be right, depending on the way you format your stack-array. Note the elements_in_stack should start at 0. Once you get the right implementation of this method for you stack you can just print the results in the natural way.
if you just want your array to be displayed without the zeros you can just use a if statement.
for( int i = 0; i < Array.length; i ++ ){
if( Array[i] != 0 ){
System.out.print( Array[i] + " ");
}
}
This will just iterate through your array and test if the value is zero. If it is not it will display the value, if it is, it disregards it.
instead of using int type i created it using object
import java.util.Arrays;
import java.io.*;
public class Stacks{
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("what is the size of your stack? :");
int size = Integer.parseInt (br.readLine());
int get = size;
Object[] Array = new Object[size];
System.out.println("type: push , pop , exit");
System.out.println("remember! you can EXIT anytime");
/* here i use the code of Ryan*/
for( int i = 0; i < Array.length; i ++ ){
if( Array[i] != null ){
System.out.print( Array[i] + " ");
}
}
/*there still a code here but this is just what i needed to show..*/
}
}
now i can display 0 if I input it..

Java Beginning Scanner

I am a novice programmer and I am trying to do projects that I find fun to help me learn more about the language then my school classes have been able to provide. I have wanted to try reversing a string but instead of having the string defined in a string I have added a scanner to be able to allow a user to input what they want. After searching for any help I haven't been able to find my issue that I am having. So far I have this:
import java.util.ArrayList;
import java.util.Scanner;
public class Reverse {
static ArrayList<String> newString = new ArrayList();
static int inputLength = 0;
static String PlaceHolder = null;
static String beReturned = null;
static int lengthArray = 0;
static String ToBeReversed;
static String hold = null;
public static void reversal(){
inputLength = ToBeReversed.length();
for (int e = 0; e <= inputLength; e++)
{
PlaceHolder = ToBeReversed.substring(inputLength -1, inputLength);
newString.add(PlaceHolder);
}
}
public static String putTogether()
{
int lengthcounter = 0;
lengthArray = newString.size();
for (int i = 0; i < lengthArray; i++)
{
beReturned = beReturned + newString.get(lengthcounter);
if (lengthcounter < lengthArray)
{
lengthcounter++;
}
}
return beReturned;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //create a new scanner
ToBeReversed = input.nextLine();
Reverse.reversal();
Reverse.putTogether();
}
}
For any input that I input there is no result. I don't get an Error Message or any form of return... The output is blank. I am just wondering if I made a mistake with the scanner or if it is how I am trying to store the characters/access them from the ArrayList I created. I am trying to not have others give me the answer completely with all the fixes, I hope I can just get a pointer or a hint to where I am messing up. Thank you for your time and help.
You need to print the output, for example
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //create a new scanner
ToBeReversed = input.nextLine();
System.out.println("ToBeReversed = " + ToBeReversed);
Reverse.reversal();
System.out.println("newString = " + newString);
System.out.println(Reverse.putTogether());
}
I don't want to give a complete answer, as that would spoil your fun (and steal an opportunity for your to get started with using a debugger), but here are some hints...
You can use String#charAt to get an individual character from a String at a given index
Java is generally 0 indexed, that means that things like arrays, String, List start at index 0 and go through to length - 1
null + String = nullString ;)
You can run a loop backwards. for-loop doesn't have to run from 0-x in ascending order, they can run x-0 in descending order ;)

How to use portion of an array

Sorry if everyone sees me post a lot of silly questions today (just a preface). However this is the final for a summer class and my teacher stopped caring/explaining how to do things for my first coding class.
For this project I have to print a list of integers from a .dat file into a program in reverse order with a max of 40 possible values in the array (Did all that) The problem I am encountering is that he said the program should also be flexible enough to deal with less than 40 values. However given my current code I always encounter an error saying "nosuchelementexception". Any help would be greatly appreciate. Below is a copy of what I have:
import java.io.*; //Imports any file operation (ie Reading or Writing)
import java.util.Scanner; //Imports scanner class
public class program3
{
public static void main(String [] ars) throws IOException
{
double [] Values; // creating array called value
Values = new double [40]; // establishing array with 40 cells
int k; // creating counter integer
Scanner InputFile = new Scanner( new FileReader("temp.dat")); // input file you wish to open.
for (k = 0 ; k < Values.length ; k++)
Values[k] = InputFile.nextDouble();
for (k = Values.length - 1 ; k >= 0 ; k--)
System.out.println("Cell " + k + " contains the value " + Values[k]);
InputFile.close();
}
}
The problem you are having is that the length attribute of an array refers to the declared length, not the amount of data in it.
When you try to use the length (in this case 40) to control the loop you use for reading data, you will get an error if there are fewer elements to read.
What you want to do is read more input only while there exists more input to get:
int k = 0;
while (inputFile.hasNextDouble()) {
Values[k++] = inputFile.nextDouble();
}
Also, consider using an ArrayList instead of an array. The ArrayList class allows you to store a dynamic amount of data, so you don't have to worry about pre-allocating storage space:
ArrayList<Double> values = new ArrayList<>();
while (inputFile.hasNextDouble()) {
values.add(inputFile.nextDouble());
}
You can use a while loop and a counter
import java.io.*; // Imports any file operation (ie Reading or Writing)
import java.util.Scanner; // Imports scanner class
public class program3
{
public static void main(String [] ars) throws IOException
{
double [] Values; // creating array called Values
Values = new double [40]; // establishing array has 40 cells
int counter = 0; // creating counter integer
Scanner inputFile = new Scanner( new FileReader("temp.dat")); //input file you with to open.
while(inputFile.hasNextDouble()){
Values[counter] = InputFile.nextDouble();
counter++;
}
for (i = counter - 1 ; i >= 0 ; i--)
System.out.println("Cell " + i + " contains the value " + Values[i]);
InputFile.close();
}
}
If you do not have to use an Array, use an ArrayList<Double>. This allows you to call values.add(value) to add to the list. The length is variable and you can use your same code (just replace values[i] with values.get(i))
However, if you do have to use arrays, created a method that adds to the array. Start with a 0 length array, and when an element is added, create a new array of length+1, then copy the old elements in, and add the new element at the end.
There are many other ways to go about this, but these two allow you to use your existing working code.
Array approach:
values = new double[0];
public void add(double x){
double[] temp = new double[values.length +1];
for(int i =0; i< values.lenght; i++){
temp[i] = values[i];
}
temp[temp.length-1] = x;
values = temp;
}
you should use an arrayList instead so you don't have to initially set the size of the array. This would make it so that you never have empty elements in the array.
Another option would be to initialize the array with placeholder values like -1, and then only perform the switch if the value is not -1.
Add a counter that keeps track of how many item you put into the array and use that to determine where to stop when you go to print them out.
Is there 40 elements in your .dat file. If there isnt your code probably gave the exception.
for (k = 0 ; k < Values.length ; k++)
Values[k] = InputFile.nextDouble();
If your .dat file doesn't contain 40 elemennts then value[39] can't be filled in.
An Array has a fixed size after initialising it, so you may want to use dynamic datastructure or instead use a while loop as posted below. I personally would recommend an ArrayList in this case.
You should also use the method
Scanner.hasNext() or in your particular case Scanner.hasNextDouble() Docs
to get any new elements.
So your program would then look like this:
import java.io.*; //Imports any file operation (ie Reading or Writing)
import java.util.Scanner; //Imports scanner class
import java.util.ArrayList;
public class program3
{
public static void main(String [] ars) throws IOException
{
ArrayList<Double> doubles = new ArrayList<Double>();
Scanner inputFile = new Scanner( new FileReader("temp.dat"));
while (inputFile.hasNextDouble()) {
doubles.add(inputFile.nextDouble());
}
inputFile.close();
for (Double value : doubles) {
System.out.println(value);
}
}
}
Java has convenient methods in it's Collections class to allow sorting. You may want to check this out if you haven't already.
I admire your grit getting on Stack Overflow.
To reward you here's your answer.
The first for loop you have iterates over your new, empty array. That would be find except you are RETRIEVING information from the Scanner object, InputFile.
So you should in fact be iterating over that object! Not your array. No shame though. Classic mistake.
Here's my version of your code:
import java.io.FileReader;
import java.io.IOException; //Imports any file operation (ie Reading or Writing)
import java.util.Scanner; //Imports scanner class
public class program3
{
public static void main( String [] ars ) throws IOException
{
double [] Values; // creating array called value
Values = new double [40]; // establishing array has 20 cells
int k; // creating counter integer
//input file you with to open.
Scanner InputFile = new Scanner( new FileReader( "temp.dat" ) );
for ( k = 0; InputFile.hasNextDouble(); k ++ )
Values[k] = InputFile.nextDouble();
for ( k = Values.length - 1; k >= 0; k-- )
System.out.println( "Cell " + k + " contains the value " + Values[k] );
InputFile.close();
}
}
Hope this helps!

How do I make an array from a file containing numbers in Java?

Im fairly new to java, and I have a project to make a program that reads a file containing a list of numbers and calculates them. I want to make an array after reading the file, but can't seem to use the array 'scores[]' that I created in my makeArray method. Could someone please show me how to fix this error? I believe it is something to do with scope, I just can't figure it out. Also, I know lists can work instead of arrays but I can't use the for this project. Thanks!
P.S. sorry If my codes ugly
import java.io.*;
import java.util.*;
class GradeFiles {
public static void main(String[] args)
throws FileNotFoundException {
Scanner console = new Scanner(System.in);
Scanner input = promptUser(console);
for(int i = 0; i<= scores.length-1; i++) {
double[] printArray = scores[i];
System.out.print(printArray);
}
}
public static Scanner promptUser(Scanner console)
throws FileNotFoundException {
Scanner isThere = null;
while(isThere == null) {
System.out.print("Enter name of file: ");
String fileName = console.next();
try {
isThere = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.print("File Not Found. ");
}
}
System.out.print("");
return isThere;
}
public static double[] makeArray(Scanner input) {
int length = 0;
while(input.hasNext()) {
double a = input.nextDouble();
length++;
}
double[] scores = new double[length-1];
while(input.hasNext()) {
for(int i = 0; i <= length - 1; i++) {
double num = input.nextDouble();
scores[i] = num;
}
}
return scores;
}
}
you are going to the end of the file in an attempt to find the number of double values you need to store so that you can decide the length of the array. So when you are again using
input.hasNext(); it returns null because you are already at the end of the file.
You can use an arrayList to read the numbers if you are unsure about how many you have to read. If you want you can cast it back to array
public static double[] makeArray(Scanner input) {
int length = 0;
ArrayList<Double> list = new ArrayList<Double>();
while(input.hasNext()) {
list.add(input.nextDouble());
}
double[] scores = new double[list.size()];
int i = 0;
for (double e : list)
scores[i++] = e;
return scores;
}
Look at the makeArray method you've written. in the first loop you advance the scanner pointer to the end of the file.
surly if you try to read additional data there will be no more (next()).
the most simple solution is that you reconstruct your scanner passing it the same file after completing the first loop.
makeArray will always return an empty array. After you scan through input.hasNext() you have consumed all of your input. The second while loop will exit immediately because there is no more input.

Parsing a text file into strings (JAVA)

I am trying to write a coded that reads in a text file into an array list. However, I am unsure how to parse my text file into strings to correctly be put into an array list. Here is a sample text file that I need to use.
This should be the sample question.
2
one
two
three
four
0
4
6
My Java code below:
package javaapplication8;
import java.util.*;
import java.io.*;
public class JavaApplication8 {
public static void main(String[] args) throws IOException{
Scanner inScan = new Scanner(System.in);
String file_name;
System.out.print("What is the full file path name?\n>>");
file_name = inScan.next();
Scanner fScan = new Scanner(new File(file_name));
int numItems = Integer.parseInt(fScan.nextLine());
ArrayList<String> Questions = new ArrayList<String>();
for(int i=0; i < numItems; i++)
{
Questions.add(fScan.nextLine());
}
System.out.print("The array is: " + Questions);
}
From your comment about the variable numLines below, you don't need to parse integers from the content so you can remove the line:
int numItems = Integer.parseInt(fScan.nextLine());
Then to output every line to the array, you can use Scanner.hasNextLine():
while (fScan.hasNextLine()) {
questions.add(fScan.nextLine());
}

Categories