How to add String output to an array within a recursion - java

I am writing a recursive procedure to return a permutation of a string
I get the desired output printed to the console. However, I would like to add the output to an array to be able to work on it further. How can I achieve it?
import java.util.*;
public class Permutation {
public static void main(String args[]) {
permute("A", "BCD");
}
public static void permute(String FirstElement, String Remainder) {
List<String> mylist_tobuild = new ArrayList<String>();
if (Remainder.length() <= 1) {
FirstElement = FirstElement+Remainder;
// System.out.println(FirstElement);
mylist_tobuild.add(FirstElement);
System.out.println(mylist_tobuild);
}
else
for (int i = 0; i < Remainder.length(); i++) {
try {
String newString = Remainder.substring(0, i) + Remainder.substring(i + 1);
permute(FirstElement + Remainder.charAt(i), newString);
} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
}
I get: [ABCD] [ABDC] [ACBD] [ACDB] [ADBC] [ADCB]
I would like to have: [ABCD, ABDC, ACBD, ACDB, ADBC, ADCB,]

You can supply the List as an argument:
public static void main(String args[]) {
List<String> perms = new ArrayList<>();
permute("A", "BCD",perms);
System.out.println(perms);
}
public static void permute(String FirstElement, String Remainder, List<String> perms) {
if (Remainder.length() <= 1) {
FirstElement = FirstElement+Remainder;
perms.add(FirstElement);
} else {
for (int i = 0; i < Remainder.length(); i++) {
try {
String newString = Remainder.substring(0, i) + Remainder.substring(i + 1);
permute(FirstElement + Remainder.charAt(i), newString, perms);
} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
}

You are creating a new list every time you go through the permute method. To fix that, you can take your list creation out of the method (e.g. create a static field), so you don't create a new list every time you go through the loop. Then add your print statement after your permutation method in your main class, so you can get the final result.
private static ArrayList<String> mylist_tobuild;
public static void main(String args[]) {
mylist_tobuild = new ArrayList<>(); //initialize list here once
permute("A", "BCD");
System.out.println(mylist_tobuild);
}

Related

How do I need read a file with commas and words and only store numbers in an array?

I need to store only numbers that have 8 digits and not a word into an array, and if it is not then just to print it to the console. Once in the array i have to sort them and print them into the right side and the left side has the unsorted list.
So I am stuck at a file with commas it only works when it has not commas or space. I am supposed to use the method "compareTo" and the "StringTokenizer" I know how they both work but just does not do what i want, maybe I am putting it in the wrong function. I also need to separate this file and put in a separate file the GUI functions not sure what to put on that file.
public class Project1 {
static final int LIST_SIZE = 10;
static int ssnSize;
static String line;
static String[] ssnList;
static TextFileInput inFile;
static String inFileName = "Dates.txt"; //save the file in Lab12 folder on BB in your project folder
static JFrame myFrame;
static Container myContentPane;
static TextArea left, right;
public static void main(String[] args) {
initialize();
readNumbersFromFile(inFileName);
printSSNList(ssnList,ssnSize);
printSSNtoJFrame(myFrame,ssnSize);
}
public static void initialize() {
inFile = new TextFileInput(inFileName);
ssnList= new String[LIST_SIZE];
ssnSize=0;
line ="";
left = new TextArea();
right = new TextArea();
myFrame = new JFrame();
myFrame.setSize(400, 400);
myFrame.setLocation(200, 200);
myFrame.setTitle("");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void readNumbersFromFile(String fileName)
{
String ssn;
ssn = inFile.readLine();
while (ssn != null) {
assert (isValidDate(ssn)): "SSN not valid";
if (!isValidDate(ssn))
throw new IllegalArgumentException("Invalid SSN");
else
storeDates(ssn,ssnList);
ssn = inFile.readLine();
} //while
} //readSSNsFromFile
public static void printSSNList(String[] list, int size)
{
assert (isValidList(list)): "The array is not valid";
if (!isValidList(list)){
throw new IllegalArgumentException("Invalid list)");
}
for (int i=0;i<size;i++)
if (!isValidDate(list[i]))
System.out.println("Invalid SSN: "+list[i]);
else
System.out.println(list[i]);
}
public static void storeDates(String s, String[] list)
{
assert (isValidDate(s)): "The SSN is not valid";
assert (isValidList(list)): "The array is not valid";
if (isValidDate(s) && isValidList(list))
list[ssnSize++]=s;
assert (isValidList(list)):"Resulting list not valid";
}
public static void printSSNtoJFrame(JFrame jf, int size)
{
assert (isValidList(ssnList)): "The array is not valid";
if (!isValidList(ssnList)){
throw new IllegalArgumentException("Invalid list)");
}
jf.setLayout(new GridLayout(1, 2));
myContentPane = jf.getContentPane();
TextArea myLeftArea = new TextArea();
TextArea myRightTextArea = new TextArea();
myContentPane.add(myLeftArea);
myContentPane.add(myRightTextArea);
for (int i=0;i<size;i++)
{
if (!isValidDate(ssnList[i]))
myLeftArea.append("Invalid SSN: "+ssnList[i]+"\n");
else
{
myLeftArea.append(ssnList[i]+"\n");
}
}
sortOnlyNumbers(ssnList);
for(int j=0; j< size; j++)
{
myRightTextArea.append(ssnList[j]+"\n");
}
jf.setVisible(true);
}
private static void sortOnlyNumbers(String[] array)
{
List<Integer> indexes = new ArrayList<Integer>();
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
try {
numbers.add(Integer.parseInt(array[i]));
indexes.add(i);
} catch (NumberFormatException e) {
// don't care
}
}
Collections.sort(numbers, Collections.reverseOrder());
for (int i = 0; i < numbers.size(); i++) {
array[indexes.get(i)] = String.valueOf(numbers.get(i));
}
}
public static boolean isValidDate(String s)
{
if (s.length() != 8) {
throw new IllegalArgumentException("An SSN length must be 9");
}
for (int i=0;i<8;i++)
if (! Character.isDigit(s.charAt(i))) {
throw new IllegalArgumentException("SSN must have only digits.");
}
return (true);
}
public static boolean isValidList(String[] list)
{
if (list == null){
return false;
}
if (ssnSize == list.length){
return false;
}
return (true);
}
}
the text file has the following:
20161001
20080912,20131120,19980927, \n
20020202,hello
20120104
You can use a regular expression to perform this. An appropriate one for your requirement would be:
(\d{8})
This regex matches groups of 8 consecutive digits in your input data.
I tested this using the snippet below and was able to retrieve all 8-digit numbers from your input string.
public class Snippet {
public static void main(String[] args) {
String input = "20161001 20080912,20131120,19980927, \n 20020202,hello 20120104";
List<String> matches = get8DigitNumbersOnly(input);
System.out.println(matches);
}
public static List<String> get8DigitNumbersOnly(String inputData) {
Pattern pattern = Pattern.compile("(\\d{8})"); // This is the regex.
Matcher matcher = pattern.matcher(inputData);
List<String> matches = new ArrayList<String>();
while(matcher.find()) {
String match = matcher.group();
matches.add(match);
}
return matches;
}
}
Give it as shot. Hope this helps!

Passing System.out.println(); as an argument in a method

I want to pass System.out.println(); as an argument but the compiler won't allow me to return a void type as an argument. here is what I want it for.
public class Array {
public static void main(String args[]) {
a(data());
}
static void a(e) {
System.out.println(e);
}
static void data() {
...
}
}
So What is want a(data()); to look like after it is compiled is something like this.
a(data()) = System.out.println(data(){...});
Eventually I want to shorthand System.out.println().
What you are doing here is not passing System.out.println() as an argument; you are trying to pass an argument to System.out.println()
Try changing the return type of data() to String, or int, or anything other than void, and return something of that type from it.
Also change the parameter type of e in the function definition of a() to match the return type of data().
After you make these changes, calling a(data()); will actually print something out.
Example:
public static void main(String args[]) {
a(data());
}
// shorthand for System.out.println
static void a(String e) {
System.out.println(e);
}
// a method that returns some data
static String data() {
// replace this with whatever actual data you want to return
return "This is some data...";
}
If you just want to shorthand System.out.println, then have a method with return type void that accepts a string argument and inside of the method just do:
System.out.println(argument)
As mentioned by others, you don't want/need to pass System.out.println as a method argument. However, if you would like to do that (one never knows...), you could do that in Java 8 with Lambda expressions.
Create a functional interface:
#FunctionalInterface
public interface Action {
void run(String param);
}
Passing this interface to a method:
public class MyClass {
public void execute(Action action){
action.run("Hello!");
}
}
Use this class:
MyClass c = new MyClass();
c.execute(System.out::println);
Simply save your println statements to String and return it for printing
Your code:
static void data() {
int array[] = {1,5,6};
int alength = array.length;
System.out.println(" Location\tData");
for(int i=0;i<alength;i++) {
System.out.println(" " + i + "\t\t" + array[i]);
}
}
Change to:
static String data() {
int array[] = {1,5,6};
int alength = array.length;
//Note extra \n symbol for new line
String result = " Location\tData\n";
for(int i=0;i<alength;i++) {
result += " " + i + "\t\t" + array[i] + "\n";
}
return result;
}
then modify your a() method to accept String as a parameter:
static void a(String result) {System.out.println(result);}
A working example could look like this:
public class Array {
public static void main(String args[]) {
println(data());
}
// I strongly advise to use understandable naming
// a() is completely uninformative
static void println(String result) {
System.out.println(result);
}
static String data() {
int array[] = { 1, 5, 6 };
int alength = array.length;
// Note extra \n symbol for new line
String result = " Location\tData\n";
for (int i = 0; i < alength; i++) {
result += " " + i + "\t\t" + array[i] + "\n";
}
return result;
}
}
While the compiler may not allow you to pass a function pointer, it should allow you to pass blocks.
In Objective-C; a block as the following syntax:
void (^action)(NSString *s) = ^(NSString *s){ NSLog(s); }
You can then pass your "action" block around as a parameter, and call it whenever required:
action(#"Hello World");
Blocks are available in all recent variations of C, Wikipedia has a nice article on the subject at http://en.wikipedia.org/wiki/Blocks_(C_language_extension).
I want to change this code
package Array;
import java.util.Random;
public class Array {
public static void main(String args[]) {
data();
a();
random();
a();
array();
a();
rows();
a();
System.out.println("average " + average(45,15,15,48,97,45));
}
static String s() {
return "helloWorld";
}
static void a() {System.out.println();}
static void data() {
int array[] = {1,5,6};
int alength = array.length;
System.out.println(" Location\tData");
for(int i=0;i<alength;i++) {
System.out.println(" " + i + "\t\t" + array[i]);
}
}
static void random() {
Random rdm = new Random();
int freq[] = new int[7];
for(int i=1;i<1000;i++) {
++freq[1+rdm.nextInt(6)];
}
System.out.println("Face\tFrequency");
int frequence = freq.length;
for(int face=1;face<frequence;face++) {
System.out.println(face+"\t"+freq[face]);
}
}
static void array() {
String po[] = {"lala","po","tinkiwinki","disty"};
for(String lala: po) {
System.out.print(lala + " ");
}
System.out.println();
}
static void rows() {
int arrays[][]= {{1,5,78,15},{45,67},{875,15687,158,4515,23,2,2}};
for(int i=0;i<arrays.length;i++) {
for(int j=0;j<arrays[i].length;j++) {
System.out.print(arrays[i][j]+"\t");
}
System.out.println();
}
}
static int average(int...numbers) {
int total=0;
for(int x:numbers)
total += x;
return total/numbers.length;
}
}
class time {
int h, m, s;
void setTime(int hour,int minute,int second) {
h = ((hour>=0 && hour<=24) ? hour : 0);
m = ((minute>=0 && minute<=60) ? minute : 0);
s = ((second>=0 && second<=60) ? second : 0);
}
into this type of code for main.
a(data());
a(random());
a(array());
a(rows());
a("average " + average(45,15,15,48,97,45));

How to combine if statements in a loop

I have this class and in the printVotes method I had to do the if statement every time to print each votes. Is there any way to combine both the if statements. Could I print all the names of the candidates and the number of votes they got at the same time?
public class TestCandidate {
public static void main(String[] args)
{
Canidate[] canidate = new Canidate[5];
// create canidate
canidate[0] = new Canidate("John Smith", 5000);
canidate[1] = new Canidate("Mary Miller", 4000);
canidate[2] = new Canidate("Michael Duffy", 6000);
canidate[3] = new Canidate("Tim Robinson", 2500);
canidate[4] = new Canidate("Joe Ashtony", 1800);
printVotes(canidate) ;
}
public static void printVotes(Canidate [] List)
{
double max;
int index;
if (List.length != 0)
{
index = 0;
for (int i = 1; i < List.length; i++)
{
}
System.out.println(List[index]);
}
if (List.length != 0)
{
index = 1;
for (int i = 1; i < List.length; i++)
{
}
System.out.println(List[index]);
return;
}
}
}
If you pass in a List<Candidate> candidates; and assuming that each candidate has a List<Integer> Votes:
List<Integer> votes= new ArrayList<Integer>() ;
for(Candidate c:candidates)
{
votes.add(c.GetVote()) ;
}
for(Integer v:votes)
{
System.out.println(v);
}
You could override the Candidate class's toString() method like so:
public String toString() {
return "Candidate Name: " + this.name + "\nVotes: " + this.votes;
}
Then your printVotes method would look something like this:
public static void printVotes(Candidate[] list) {
for(Candidate c : list) {
System.out.println(c);
}
}
As someone else mentioned, avoid using capital letters in variable names especially in cases where words such as List are used. List is a collection type and can be easily confused.

Writing on an output file

I am stuck on this part where it does not write to an output file
the first class is contact I had to modify this is not my class is the authors class
I just had to use it
//********************************************************************
// Contact.java Author: Lewis/Loftus
//
// Represents a phone contact.
//********************************************************************
public class Contact implements Comparable
{
private String firstName, lastName, phone;
//-----------------------------------------------------------------
// Constructor: Sets up this contact with the specified data.
//-----------------------------------------------------------------
public Contact (String first, String last, String telephone)
{
firstName = first;
lastName = last;
phone = telephone;
}
//-----------------------------------------------------------------
// Returns a description of this contact as a string.
//-----------------------------------------------------------------
public String toString ()
{
return lastName + ", " + firstName + "\t" + phone;
}
//-----------------------------------------------------------------
// Returns true if the first and last names of this contact match
// those of the parameter.
//-----------------------------------------------------------------
public boolean equals (Object other)
{
return (lastName.equals(((Contact)other).getLastName()) &&
firstName.equals(((Contact)other).getFirstName()));
}
//-----------------------------------------------------------------
// Uses both last and first names to determine ordering.
//-----------------------------------------------------------------
public int compareTo (Object other)
{
int result;
String otherFirst = ((Contact)other).getFirstName();
String otherLast = ((Contact)other).getLastName();
if (lastName.equals(otherLast))
result = firstName.compareTo(otherFirst);
else
result = lastName.compareTo(otherLast);
return result;
}
//-----------------------------------------------------------------
// First name accessor.
//-----------------------------------------------------------------
public String getFirstName ()
{
return firstName;
}
//-----------------------------------------------------------------
// Last name accessor.
//-----------------------------------------------------------------
public String getLastName ()
{
return lastName;
}
}
this class oes the sorting this is fine. it does the sorting no prblem
public class Sorting {
public static void bubbleSortRecursive(Comparable[] data, int n)
{
if (n < 2)
{
return;
}
else
{
int lastIndex = n - 1;
for (int i = 0; i < lastIndex; i++)
{
if (data[i].compareTo(data[i + 1]) > 0)
{ //swap check
Comparable tmp = data[i];
data[i] = data[i + 1];
data[i + 1] = tmp;
}
}
bubbleSortRecursive(data, lastIndex);
}
}
public static void selectionSortRecursive(Comparable[] data, int n)
{
if (n < 2)
{
return;
}
else
{
int lastIndex = n - 1;
int largestIndex = lastIndex;
for (int i = 0; i < lastIndex; i++)
{
if (data[i].compareTo(data[largestIndex]) > 0)
{
largestIndex = i;
}
}
if (largestIndex != lastIndex)
{ //swap check
Comparable tmp = data[lastIndex];
data[lastIndex] = data[largestIndex];
data[largestIndex] = tmp;
}
selectionSortRecursive(data, n - 1);
}
}
}
this is the part I need help with. It is not outputing to he p4output.txt, i dont know what the problem is.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class TestProject4 {
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
doSelectionSortRecursive();
}
private static void doBubbleSortRecursive()
{
Contact[] contacts = createContacts();
System.out.println("Before bubbleSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
Sorting.bubbleSortRecursive(contacts, contacts.length);
System.out.println("\nAfter bubbleSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
}
private static void doSelectionSortRecursive()
{
Contact[] contacts = createContacts();
System.out.println("Before selectionSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
Sorting.selectionSortRecursive(contacts, contacts.length);
System.out.println("\nAfter selectionSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
}
private static void printContacts(Contact[] contacts)
{
try
{
// this part I need help with it is not outputing in the text file
File file = new File("p4output.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (Contact contact : contacts)
{
bw.write(contact.toString());
}
bw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("\t" + contacts);
}
public static Contact[] createContacts()
{
return new Contact[]
{
new Contact("John" , "Smith" , "610-555-7384"),
new Contact("Sarah" , "Barnes" , "215-555-3827"),
new Contact("Mark" , "Riley", "333-333-3333"),
new Contact("Laura" , "Getz" ,"663-555-3984"),
new Contact("Larry" , "Smith" , "464-555-3489"),
new Contact("Frank" , "Phelps" , "322-555-2284"),
new Contact("Mario" , "Guzman" , "804-555-9066"),
new Contact("Marsha" , "Grant" , "243-555-2837"),
};
}
}
According to Eclipse, you never call/use printContacts(Contact[] contacts); method
Your printContacts(Contact[] contacts); contains the statements to write a file.
You don't appear to call the function printContacts() in your program. Try calling it after you do your contact creation and sorting.
It might look like this:
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
doSelectionSortRecursive();
printContacts(contactArray);//inserted code
}
Also, when you call your sorting methods, doSelectionSortRecursive(), you don't return the list of contacts. Make a return statement for it and then put the contact array into your printContacts function.
Here's an example:
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
Contact[] contacts = doSelectionSortRecursive();
printContacts(contacts);
}
public static Contact[] doSelectionSortRecursive(){
Contact[] contacts = createContacts();
//your sorting code
return contacts;
}
Using this method allows you to get the array of contacts from the method once it has been sorted.

How to parse the command parameter in java?

For example, the user run my programme like this
myprogram -p1 my_name, -p2 my_address, -p3 my_gender
But the user may type this, and it still valid:
myprogram -p2 my_address, -p1 my_name,-p3 my_gender
How can I parse it in Java? Thanks.
You can use something like this:
public static void main (String[] args) {
for(int i = 0; i < args.length; i++) {
if(args[i].equals("-p1")) {
// args[i+1] contains p1 argument
} else if(args[i].equals("-p2")) {
// args[i+1] contains p2 argument
}
}
}
Make sure to check whether the i+1 argument is there, otherwise an exception will be thrown.
There are more advanced methods of going this, you could e.g. use hashing to map the flag to the processing function. But, for this purpose, I guess this will do.
What I do not understand is the use of comma's in your sample. What are they used for?
If you're looking for a DIY, then maybe this might be starting point.
public class Foo
{
private static final String[] acceptedArgs = { "-p1", "-p2", "-p3" };
public void handleCommandArgs(String... args)
{
if (args != null)
{
for (int argIndex = 0; argIndex < args.length; argIndex++)
{
for (int acceptedIndex = 0; acceptedIndex < acceptedArgs.length; acceptedIndex++)
{
if (args[argIndex] != null && args[argIndex].equals(acceptedArgs[acceptedIndex]))
{
String arg = args[argIndex], param = args[argIndex + 1];
performRoutine(arg, param);
}
}
}
}
}
private void performRoutine(String arg, String param)
{
System.out.println(arg + " ->" + param.replace(",", ""));
}
public static void main(String[] args)
{
(new Foo()).handleCommandArgs(args);
}
}
Sample from Java Tutorials #Oracle
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
The params come in a vector of String.

Categories