Reading from Array and using Recursive method to check for Palindromes - java

I've been tasked with creating an array by reading from a text file created by myself. The program in concept, is supposed to read the words i entered, and store them in an array. Following, I am to create a recursive method to check and see if each line is a palindrome and print the result. Currently, I'm getting a stack overflow error. Sorry if the code is not commented on too much.
package palindrome;
import java.util.*;
import java.io.*;
/**
*
* #author alexanderrivera
*/
public class Palindrome {
// Static variables can be used in ALL instances of a class
public static String [] Palindromes;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// Establishes a value to Palindromes
Palindromes = new String[10];
int i=0;
// calls the readFile method to read the file
readFile("Palindrome.txt");
FindPalindrome(Palindromes[i]);
}// end of main method
// begining of the readFile method
public static void readFile(String fileName)
{
// sets the int variable to zero
int i = 0;
// establishes the java input for reading the file
java.io.File inputFile = new java.io.File(fileName);
// being try catch block
try{
// establishes instance of the scanner to read the file
Scanner fileReader = new Scanner(inputFile);
// being while statement
while(fileReader.hasNextLine())
{
Palindromes[i] = fileReader.nextLine();
i++;
}// end while statement
// closes the file reader
fileReader.close();
// print the index to see if it was read
}catch (FileNotFoundException e){
System.out.println("Sorry, cannot find the file");
}// end error message
} // end the method
public static void FindPalindrome(String FoundPalindrome) {
int i=0;
{
if (Palindromes[i].length() == 0 || Palindromes[i].length() == 1) {
System.out.println(Palindromes[i] + " This is a Palindrome\n");
}
if (Palindromes[i].charAt(0) == Palindromes[i].charAt(Palindromes[i].length() - 1)) {
FindPalindrome(Palindromes[i].substring(1, Palindromes[i].length() - 1));
}
// otherwise
System.out.println("This is not a Palindrome \n");
}
}
}

In recursive calls to your FindPalindrome method, you're passing strings which you never use, since the FindPalindrome method looks at the first entry in the original array of strings and ignores its parameter. So it just repeatedly calls itself with the same argument until it overflows the stack.
Everywhere in FindPalindrome that you reference Palindromes[i], you should likely be referencing instead the parameter FoundPalindrome, and then it might actually work.

Related

How to retrieve array values and assign to String variable in java

I am trying to store the contents from a file into an array String retval[] , copy that array to String[] fed() and pass the array into main. So far, the array stores and copies but the array method returns null in main String []feed; feed=uio.fed();.
UserIO.java
package fileio;
import classes.*;
import java.util.*;
import java.lang.*;
import java.io.*;
public class UserIO
{
public String search (String line0)
{
String line;
try
{
FileInputStream ufin = new FileInputStream("E:\\3rd sem\\OOP\\Projects\\New folder (2)\\BOOK LIBRARY\\fileio\\user.txt");
Scanner sc = new Scanner(ufin);
while (sc.hasNextLine())
{
line=sc.nextLine();
if(line.contains(line0))
{
String retval[]= line.split(" ");
feed= new String[retval.length];
for (String s: retval)
{
System.out.println("\t\t\tFrom retval:"+s);
}
for (int n=0;n<retval.length;n++)
{
feed[n]=retval[n];
System.out.println("\tFrom feed:"+feed[n]);
}
}
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
return line0;
}
public static String [] feed;
public static String[] fed()
{
String [] fd;
fd= new String[feed.length];
for (int n=0;n<feed.length;n++)
{
fd[n]=feed[n];
System.out.println("From fd:"+fd[n]);
}
return fd;
}
}
Down below is the main method
Execute.java
import java.lang.*;
import java.util.*;
import classes.*;
import fileio.*;
public class Execute
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String adminusername = "a";
String adminpassword = "p";
String readerusername = "r";
String readerpassword = "p";
String nreaderusername;
String nreaderpassword;
Library b = new Library();
UserFileReadWriteDemo ufrwd = new UserFileReadWriteDemo();
UserIO uio = new UserIO();
System.out.println("enter id ");
String id = sc.next();
uio.search(id);
try
{
String []feed;
feed=uio.fed();
//uio.fed()=feed.clone;
for(int s=0;s<feed.length;s+=5)
{
String nid00= null;
feed[0+s]= nid00;
String name00=null;
feed[1+s]= name00;
String age00= null;
feed[2+s]= age00;
String uname00= null;
feed[3+s]= uname00;
String upassword00= null;
feed[4+s]= upassword00;
Reader c00 = new Reader(nid00, name00, age00,uname00,upassword00);
b.insertReader(c00);
System.out.println(" In main"+feed[s]);
}
}
catch (NullPointerException n)
{
n.printStackTrace();
}
}
Your code is a little bit difficult to read and also has a lot of unnecessary repetitions, for example method fed has no role, why not call search and make search return an array with the found elements? You are making search return the line you are searching for which you already know when you gave search that argument in the first place, it is just returning a useless value.
Also it is difficult to understand what search actually does, from what i see it finds the last occurrence of line0 in the file, because it continues to iterate over lines and every time it finds line0 it will create new feed array in UserIO and eliminate all the previous array it found, and will return when all file has been read. If this is your intention then this is not the right way to do it as it is inefficient, because you keep creating arrays that will be discarded. If your intention is the last occurrence of line0 then you can just assign a found line to a String variable and when the iteration finishes just split and return that array as it will be the last occurrence of line0 in the file.
As i see it the only way that fed will return null is if there is no line with line0 in the file because search initializes the array if it finds line0 at least once in the file, this way feed will be an uninitialized array which will be a null pointer.
These lines has no meaning:
String nid00= null;
feed[0+s]= nid00;
String name00=null;
feed[1+s]= name00;
String age00= null;
feed[2+s]= age00;
String uname00= null;
feed[3+s]= uname00;
String upassword00= null;
feed[4+s]= upassword00;
I think you meant nid00 = feed[0+s] and so on, because the way you wrote the assignment to nid00 and the other variables will be always null which will be useless.
Also when you copy arrays try to use Arrays.copyOf methods or System.arraycopy they save you writing several lines and also they are more efficient, read about them in the documentation.
And the last thing, it is not useful to catch nullpointer exception if you wrote your code, in general you must know what your methods do and if there is a nullpointer exception in something you wrote then there is something wrong in your code, if for example a method you wrote returns null then you must know about the possibility of a null return and handle that possible return, this way it will be easier for you to read your code and use it and also for others who use your code.
The nullpointer you are getting is because you trying to get the length of an uninitialized feed inside fed method, you must be very careful.

Read multiple data types from txt file into arrayList - Java

For this program I'm supposed to read from a txt file containing information on the automobile's make, model, mpg, and trunk space in that order. An example is:
hyundai
genesis
24.6
100
and repeated for several different cars.
We had to construct an "Automobile" superclass with the instance variables of make and model. Then a "GasEngineAuto" subclass with instance variable for mpg that extends "Automobile". Then a subclass called "Sedan" that extends "GasEngine
Auto" and has instance variable for trunk space. For the assignment we had to get these classes signed off on to make sure that they made correctly.
Write a method to read the information from the file gas_sedans.txt and store it in the list you created in the previous step. The list should be the only parameter for this method. Within the method, open the file, read the information for each sedan into appropriately-typed variables, call
the parameterized constructor (the one that takes arguments for all attributes) to create the object, then add the object to the list. Call this method from main.
Below is my code so far. I wanted to try to make sure I could read into the arrayList before I used a method to do it.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* #author
*/
public class lab10_prelab {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Sedan> sedanList = new ArrayList<Sedan>();
File myFile = new File(System.getProperty("user.dir")+"/src/gas_sedans (1).txt");
if (!myFile.exists()){
System.out.println("The file could not be found");
System.exit(0);
}
Scanner inputFile = new Scanner(myFile);
while (inputFile.hasNext())
{
Sedan a = new Sedan();
a.setMake(inputFile.nextLine());
a.setModel(inputFile.nextLine());
inputFile.nextLine();
a.setMPG(inputFile.nextDouble());
inputFile.nextLine();
a.setTrunkCapacity(inputFile.nextDouble());
sedanList.add(a);
}
inputFile.close();
}
}
It says that I get a InputMismatchException notice when I try to run the program.
You have typo error:
automobileArray and autombileArray are different.
In your code you are missing o after m in the variable
autombileArray
^
Edited: 06:49am 18/07/20115
It says that I get a InputMismatchException notice when I try to run
the program.
a.setModel(inputFile.nextLine());
inputFile.nextLine();//remove this line
a.setMPG(inputFile.nextDouble());
inputFile.nextLine();
a.setTrunkCapacity(inputFile.nextDouble());
inputFile.nextLine();//add here
I made some changes and arrived at this. Now it says to: Write a method to display the list. The method should have one parameter, an ArrayList of Automobiles. Within the body of the method, call upon the toString method to display each item. Call this method at the end of main. Does this mean make a class like "public String toString()...
or is what I did fine.
public class Smith_lab10_prelab {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Automobile> AutomobileList = new ArrayList<Automobile>();
fillAutomobileList(AutomobileList);
displayAutomobileList(AutomobileList);
}
public static void fillAutomobileList(ArrayList sedanList) throws FileNotFoundException {
File myFile = new File(System.getProperty("user.dir") + "/src/gas_sedans (1).txt");
if (!myFile.exists()) {
System.out.println("The file could not be found");
System.exit(0);
}
Scanner inputFile = new Scanner(myFile);
for (int i = 0; inputFile.hasNext(); i++) {
Sedan a = new Sedan();
a.setMake(inputFile.next());
a.setModel(inputFile.next());
a.setMPG(inputFile.nextDouble());
a.setTrunkCapacity(inputFile.nextDouble());
sedanList.add(a);
}
}
public static void displayAutomobileList(ArrayList automobileList) {
System.out.println(automobileList.toString());
}
}

How to copy contents of array from another method into an array within the main method?

I have an array I created that holds the contents of a file. This array is not in my main method, but another method. I am having trouble figuring out how to copy the array holding the file contents into an array within my main method so I can manipulate/append the information from there. I'm getting an error saying that it can't find the variable dataPieces. Can someone please help me figure this out? Is this even the best way to work with a file so that I can show the user the information and let them append it?
Thanks
/**
Add in javadoc comments
*/
//import statements
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class Try {
public static void main(String[] args){
String dataHolder[] = createFile();
System.out.println(dataHolder);
}
public static String[] createFile(){
//create file holding inventory information
String dataPieces[] = new String[10];
try{
PrintWriter outputFile = new PrintWriter("inventory.txt");
outputFile.println("3000.0");
outputFile.println("Lamps 15.3 400");
outputFile.println("Chairs 19.95 250");
outputFile.print("Desks 95.0 300");
int i =0;
outputFile.close();
File myFile = new File("inventory.txt");
Scanner inputFile = new Scanner(myFile);
while(inputFile.hasNext() && i<dataPieces.length){
dataPieces[i] = inputFile.next();
i++;
}
inputFile.close();
}
catch(IOException e){
System.out.println("File cannot be created."); //what to say???????????<<<<<<<<
}
return dataPieces;
}
}
Your createFile() method already returns an array, so your main method should just assign that array to a variable :
public static void main(String[] args){
String[] dataHolder = createFile();
...
}
There's no reason to call createFile() multiple times.
You have something like:
for(int i=0; i<dataHolder.length; i++){
dataHolder[i] = createFile(dataPieces);
}
Here you are trying to create inventory.txt file 10 times after that reading the same 10 times in a loop as above which is going to return you the same data.
So your method createFile is returning an array i.e. dataPieces, you could just change your for loop to something like:
dataHolder = createFile();
for(int i=0; i<dataHolder.length; i++){
...do something with dataPieces which is referred by dataHolder now.
}
There by reading and writing file just once and then operating on array further in another method.

accessing variable within main method

I am very new to Java and writing this program to shuffle words and fix the suffle words. The following is my program. After I call mix(), I would like to be able to assign the output of word to team array within main.
For some reason, I can call mix() it works but I cannot access word which is in the shuffle function. Since I am in main and all these function within main, I thought I can access the variables. Any ideas what I am missing here?
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Project2
{
public static void main(String[] args)
{
System.out.println("Select an item from below: \n");
System.out.println("(1) Mix");
System.out.println("(2) Solve");
System.out.println("(3) Quit");
int input;
Scanner scan= new Scanner(System.in);
input = scan.nextInt();
//System.out.println(input);
if(input==1) {
mix();
System.out.println(word);
char team[]=word.toCharArray();
for(int i=0;i<team.length;i++){
System.out.println("Data at ["+i+"]="+team[i]);
}
}
else{
System.out.println("this is exit");
}
}
static void mix()
{
String [] lines=new String[1000];//Enough lines.
int counter=0;
try{
File file = new File("input.txt");//The path of the File
FileReader fileReader1 = new FileReader(file);
BufferedReader buffer = new BufferedReader(fileReader1);
boolean flag=true;
while(true){
try{
lines[counter]=buffer.readLine();//Store a line in the array.
if(lines[counter]==null){//If there isn't any more lines.
buffer.close();
fileReader1.close();
break;//Stop reading and close the readers.
}
//number of lines in the file
//lines is the array that holds the line info
counter++;
}catch(Exception ex){
break;
}
}
}catch(FileNotFoundException ex){
System.out.println("File not found.");
}catch(IOException ex){
System.out.println("Exception ocurred.");
}
int pick;
Random rand = new Random();
pick = rand.nextInt(counter ) + 0;
System.out.println(lines[pick]);
///scramble the word
shuffle(lines[pick]);
}
static void shuffle(String input){
List<Character> characters = new ArrayList<Character>();
for(char c:input.toCharArray()){
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while(characters.size()!=0){
int randPicker = (int)(Math.random()*characters.size());
output.append(characters.remove(randPicker));
}
String word=output.toString();
}
}
Return string value from shuffle() method using return statement:
static String shuffle(String input) {
// . . .
return output.toString();
}
...and then use it in mix:
String word = shuffle(lines[pick]);
But it is better to read basic java tutorials before programming.
In Java, variables cannot be seen outside of the method they are initialized in. For example, if I declare int foo = 3; in main, and then I try to access foo from another method, it won't work. From the point of view of another method, foo does not even exist!
The way to pass variable between methods is with the return <variable> statement. Once the program reaches a return statement, the method will quit, and the value after the return (perhaps foo) will be returned to the caller method. However, you must say that the method returns a variable (and say what type is is) when you declare that method (just like you need to say void when the method does not return anything!).
public static void main(String[] args){
int foo = 2;
double(foo); //This will double foo, but the new doubled value will not be accessible
int twoFoo = double(foo); //Now the doubled value of foo is returned and assigned to the variable twoFoo
}
private static int double(int foo){//Notice the 'int' after 'static'. This tells the program that method double returns an int.
//Also, even though this variable is named foo, it is not the same foo
return foo*2;
}
Alternatively, you could use instance variable to have variables that are accessible by all the methods in your class, but if you're new to Java, you should probably avoid these until you start learning the basics of object-oriented programming.
Hope this helps!
-BritKnight

printing arrays

Okay, I'm trying to get file scanner to return the array itemList.
However, I don't understand why everytime I get to return itemList and try with a println form.
It returns:
[Ljava.lang.String;#3d3b5a3a
[Ljava.lang.String;#10cb42cf
[Ljava.lang.String;#482d59a3
[Ljava.lang.String;#18f42160
When the file I'm reading it contains stuff like
apples 10
fish 20
import java.io.*;
import java.util.*;
class loadInventory{ /*This class is used for loading the inventory */
private String[] itemList; /*The lines of the inventory are stored in this array */
private int numItems; /* The number of items is stored in this variable */
public loadInventory(String fileName){ /*We can do everything in the constructor. It gets the fileName from the superMarket
object */
itemList = new String[100]; /*We assume there are not more than 100 items in the inventory */
numItems=0; /*initialize numItems to 0*/
/*Read the file using the try-catch block below. We are not specifically catching any exception.
We will not cover reading or writing of files and exceptions in this unit. So you
don't need to understand this piece of code. */
try{
BufferedReader reader = new BufferedReader(new FileReader(fileName)); /*standard code for reading a file */
String line = reader.readLine(); /*read the next line from the file and store in line */
while (line != null){ /*as long as there are lines */
itemList[numItems]= line; /*store the line in the current location of the array */
numItems++; /*increment the number of items */
line = reader.readLine(); /*read the next line */
}
reader.close(); /*close the reader */
} catch (IOException e){ /*we don't catch any exception */
}
System.out.println(itemList);
}
public String[] getItemList() {
return itemList;
}
}
Print the array of instances like this:
System.out.println(Arrays.toString(itemList));
An array itself uses the default toString() from Object, so it does not print its contents. You will need to use java.util.Arrays.toString(Object[]) to print out the content of the array (or loop over it yourself).
int length = itemList.length;
int count =0;
while(count<length)
{
System.out.println(itemList[count]);
count++;
}
thats a simplest way to iterate the list.
Because you are trying to print the whole array object while doing:
System.out.println(itemList);
Instead you need to print the single String elements stored inside the array:
System.out.println(Arrays.toString(itemList));
Don't print the String[] value directly. use like this,
for (int i = 0; i < itemList.length; i++) {
System.out.println("Value::> " +itemList[i]);
}
Pay attention on this code
while (line != null)
{
itemList[numItems]= line;
numItems++;
line = (String)reader.readLine();
}
Try this.

Categories