I have string and i need to print all the combination of the string Char's
Example
For the string "123" the output is:
1,2,3,12,13,21,23,31,32,123,132,213,231,312,321
It must be without loops, only with recursion.
Thanks!
public class CharacterRecursion
{
private String str;
private int counter;
public CharacterRecursion()
{
str = "";
counter = 0;
}
public CharacterRecursion(String str1)
{
str = str1;
counter = 0;
}
public String recurse(String str)
{
if (counter == 15)
{
return ;
}
counter++;
// return (recurse(String str _________) _________) _________;
}
public String [] toString()
{
String [] arr = new String[14];
for (int i = 0; i < 14; i++)
{
arr[i] = this.recurse();
}
return arr;
}
public static void main(String [] args)
{
CharacterRecursion recurse = new CharacterRecursion("123")
System.out.println(recurse.toString);
}
}
I think just giving you the full code would be a little to easy for you. This is the simple set up for the code that you would want. The recurse method is not completely finished, the return statement being one of the things that you will need to fix first. By answer the question, this way, I hope that I am still answering the question, but also still allowing you to fully learn and understand recursion on your one. By the way,
for the public static void main(String [] args) part
You would also put that in a separate class like so:
public class CharacterRecursion
{
private String str;
private int counter;
public CharacterRecursion()
{
str = "";
counter = 0;
}
public CharacterRecursion(String str1)
{
str = str1;
counter = 0;
}
public String recurse(String str)
{
if (counter == 15)
{
return ;
}
counter++;
// return (recurse(String str _________) _________) _________;
}
public String [] toString()
{
String [] arr = new String[14];
for (int i = 0; i < 14; i++)
{
arr[i] = this.recurse();
}
return arr;
}
public class CharacterRecursionClient
{
public static void main(String [] args)
{
CharacterRecursion recurse = new CharacterRecursion("123")
System.out.println(recurse.toString);
}
}
That would work just as well if you are required to have a client class. I hope that this help and cleared up at least a couple of things.
Related
I was asked to write a class NumberOcc with these methods:
-method getNbOcc which takes as arguments a string str and a character 'c' and return the number of occurence of the character 'c'.
-method dspNbOcc which displays the value returned by getNbOcc
-method getNbVoy which returns the number of vowel inside a string str
-method dspNbVoy which displays the value returned by getNbVoy
The problem is the value returned by getNbVoy is wrong, example: for str=stackexchange it returns 34 vowels.
public class NumberOcc {
static int count1=0;
static int count2=0;
public static int getNbOcc(String str, char c) {
for(int i=0;i<str.length();i++) {
if (str.charAt(i)==c)
count1++;}
return count1;
}
public static void dspNbOcc() {
System.out.println(count1);
}
public static int getNbVoy(String str) {
String vowel="aeiouy";
for(int j=0;j<vowel.length();j++) {
count2+=getNbOcc(str,vowel.charAt(j));}
return count2;
}
public static void dspNbVoy() {
System.out.println(count2);
}
}
TestClass
public class TestNumberOcc {
public static void main(String[] args) {
String str="stackexchange";
NumberOcc.getNbOcc(str, 'e');
NumberOcc.dspNbOcc();
NumberOcc.getNbVoy(str);
NumberOcc.dspNbVoy();
}
}
Thanks for helping
Remove the static fields, pass the values to the methods. And use them to display the results. Like,
public static int getNbOcc(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
public static void dspNbOcc(String str, char c) {
System.out.println(getNbOcc(str, c));
}
public static int getNbVoy(String str) {
int count = 0;
char[] vowels = "aeiouy".toCharArray();
for (char ch : vowels) {
count += getNbOcc(str.toLowerCase(), ch);
}
return count;
}
public static void dspNbVoy(String str) {
System.out.println(getNbVoy(str));
}
And then testing everything is as simple as
public static void main(String[] args) {
String str = "stackexchange";
NumberOcc.dspNbOcc(str, 'e');
NumberOcc.dspNbVoy(str);
}
the issue is you're not initializing your count1 (nor count2, but that bug doesn't affect anything in this case) at the beginning of your count method... add this line to the beginning of your getNbOcc method before the loop:
public static int getNbOcc(String str, char c) {
count1 = 0; // add this line
for(int i=0;i<str.length();i++) {
The solution is to apply what you did in your countLetterInString function to countVowelsInString. Just remember to use local variables. You will run into issues with static/global variables if the function is called more than once, but local variables will work the same way every time.
public static int countVowelsInString(String str) {
String vowels = "aeiouy";
// Move counter into the function
int numVowels = 0;
for(int j = 0;j<vowel.length();j++) {
numVowels += getNbOcc(str, vowel.charAt(j));
}
return numVowels;
}
I am new to Java and I am trying to print the student numbers and numbers (cijfer in this case) on 1 line. But for some reason I get weird signs etc. Also when I'm trying something else I get a non-static context error. What does this mean and how does this exactly work?
Down here is my code:
import java.text.DecimalFormat;
import java.util.Arrays;
public class Student {
public static final int AANTAL_STUDENTEN = 50;
public int[] studentNummer = new int[AANTAL_STUDENTEN];
public String[] cijfer;
public int[] StudentNummers() {
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
studentNummer[i] = (50060001 + i);
}
return studentNummer;
}
public String[] cijfers(){
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
DecimalFormat df = new DecimalFormat("#.#");
String cijferformat = df.format(Math.random() * ( 10 - 1 ) + 1);
cijfer[i++] = cijferformat;
}
return cijfer;
}
public static void main(String[] Args) {
System.out.println("I cant call the cijfer and studentnummer.");
}
}
Also I'm aware my cijfer array is giving a nullpointer exception. I still have to fix this.
I am not java developer but try
System.out.print
You could loop around System.out.print. Otherwise make your functions static to access them from main. Also initialize your cijfer array.
Besides the things I noted in the comments, your design needs work. You have a class Student which contains 50 studentNummer and cijfer members. Presumably, a Student would only have one studentNummer and and one cijfer. You need 2 classes: 1 for a single Student and one to hold all the Student objects (StudentBody for example).
public class StudentBody {
// An inner class (doesn't have to be)
public class Student {
// Just one of these
public int studentNummer;
public String cijfer;
// A constructor. Pass the student #
public Student(int id) {
studentNummer = id;
DecimalFormat df = new DecimalFormat("#.#");
cijfer = df.format(Math.random() * ( 10 - 1 ) + 1);
}
// Override toString
#Override
public String toString() {
return studentNummer + " " + cijfer;
}
}
public static final int AANTAL_STUDENTEN = 50;
public Student students[] = new Student[AANTAL_STUDENTEN];
// StudentBody constructor
public StudentBody() {
// Create all Students
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
students[i] = new Student(50060001 + i);
}
}
// Function to print all Students
public void printStudents(){
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
System.out.println(students[i]);
}
}
public static void main(String[] Args) {
// Create a StudentBody object
StudentBody allStudents = new StudentBody();
// Print
allStudents.printStudents();
}
}
Just make all your methods and class variables as static. And then you have access to them from main method. Moreover you have got some errors in code:
public class Student {
public static final int AANTAL_STUDENTEN = 50;
// NOTE: static variables can be moved to local ones
// NOTE: only static method are available from static context
public static int[] StudentNummers() {
int[] studentNummer = new int[AANTAL_STUDENTEN];
for (int i = 0; i < AANTAL_STUDENTEN; i++)
studentNummer[i] = 50060001 + i;
return studentNummer;
}
// NOTE: only static method are available from static context
public static String[] cijfers() {
// NOTE: it is better to use same `df` instance
DecimalFormat df = new DecimalFormat("#.#");
String[] cijfer = new String[AANTAL_STUDENTEN];
for (int i = 0; i < AANTAL_STUDENTEN; i++)
// NOTE: remove `i++`, because we have it in the loop
cijfer[i] = df.format(Math.random() * (10 - 1) + 1);
return cijfer;
}
// NOTE: this is `static` method, therefore it has access only to static methods and variables
public static void main(String[] Args) {
String[] cijfer = cijfers();
int[] studentNummer = StudentNummers();
// TODO you can pring two arrays one element per line
for(int i = 0; i < AANTAL_STUDENTEN; i++)
Sytem.out.println(cijfer[i] + '-' + studentNummer[i]);
// TODO as alternative, you can print whole array
System.out.println(Arrays.toString(cijfer));
System.out.println(Arrays.toString(studentNummer));
}
}
I have this assignment below:
I have two methods that modify strings simultaneously.
I have searched on many posts but couldn't find the answer.
I want the second method to modify (call) the result of the first one.
I am a neophyte to Java so thanks for your patience and understanding.
Assignment:
Part 1 - Normalize Text
Write a method called normalizeText which does the following:
Removes all the spaces from your text
Remove any punctuation (. , : ; ’ ” ! ? ( ) )
Turn all lower-case letters into upper-case letters
Return the result.
The call normalizeText(“This is some \“really\” great. (Text)!?”)
should return
“THISISSOMEREALLYGREATTEXT”
Part 2 - Obfuscation
Write a method called obify that takes a String parameter (the message to be obfuscated) and returns a string in which every vowel (A, E, I, O, U, Y) is preceded by the letters “OB” (be sure to use capital letters).
If we call obify on “THISISSOMEREALLYGREATTEXT”, it should return
“THOBISOBISSOBOMOBEROBEOBALLOBYGROBEOBATTOBEXT”
My code:
public class CryptoAssessment {
public static void main(String[] args) {
normalizeText("This is some \“really\” great. (Text)!?");
}
public static void normalizeText(String string_to_encrypt){
String upper_string = string_to_encrypt.toUpperCase();
String Capital_Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String Result_after_Normalization = "";
for (int i = 0; i < upper_string.length(); i++) {
if (Capital_Letters.contains(Character.toString(upper_string.charAt(i))))
{
Result_after_Normalization = Result_after_Normalization + Character.toString(upper_string.charAt(i));
}
}
System.out.print(Result_after_Normalization);
}
public static void Obfuscation(String string_to_Obfuscate){
String Vowel_Letters = "AEIOUY";
String Result_after_Obfuscation = "";
for (int i = 0; i < string_to_Obfuscate.length(); i++) {
if (Vowel_Letters.contains(Character.toString(string_to_Obfuscate.charAt(i))))
{
Result_after_Obfuscation = Result_after_Obfuscation + "OB" + Character.toString(string_to_Obfuscate.charAt(i)) ;
}
else {
Result_after_Obfuscation = Result_after_Obfuscation + Character.toString(string_to_Obfuscate.charAt(i));
}
}
System.out.print(Result_after_Obfuscation);
}
}
To pass the result of a call to method1() to a call to method2():
method2(method1("foo"))
To complete your assignment:
public static void normalize(String str) {
return str.replaceAll("\\W", "").toUpperCase();
}
public static void obfuscate(String str) {
return str.replaceAll("[AEIOU]", "OB$0");
}
Ah, I get your problem. You don't want to simply pring on the Console System.out - you need to return those strings back to the caller.
public static String normalizeText(String string_to_encrypt){
String upper_string = string_to_encrypt.toUpperCase();
String Capital_Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String Result_after_Normalization = "";
for (int i = 0; i < upper_string.length(); i++) {
if (Capital_Letters.contains(Character.toString(upper_string.charAt(i))))
{
Result_after_Normalization = Result_after_Normalization + Character.toString(upper_string.charAt(i));
}
}
System.out.print("After normalization: "+Result_after_Normalization);
return Result_after_Normalization;
}
And lets make the other one return a String as well
public static String Obfuscation(String string_to_Obfuscate){
String Vowel_Letters = "AEIOUY";
String Result_after_Obfuscation = "";
for (int i = 0; i < string_to_Obfuscate.length(); i++) {
if (Vowel_Letters.contains(Character.toString(string_to_Obfuscate.charAt(i))))
{
Result_after_Obfuscation = Result_after_Obfuscation + "OB" + Character.toString(string_to_Obfuscate.charAt(i)) ;
}
else {
Result_after_Obfuscation = Result_after_Obfuscation + Character.toString(string_to_Obfuscate.charAt(i));
}
}
System.out.print("After obfuscation: "+Result_after_Obfuscation);
return Result_after_Obfuscation;
}
And now the main() becomes this:
public static void main(String[] args) {
String result = obfuscate(normalizeText("This is some \“really\” great. (Text)!?"));
System.out.println("Result after doing both: "+result);
}
Was typing this out last night when i ran out of battery, so ergo the delay in answering.
You can use a method's return as another method's argument, as long as the type match.
First change your methods' signature like this(make them to return a value):
public static String normalizeText(String string_to_encrypt){...}
public static String Obfuscation(String string_to_Obfuscate){...}
Then you can use the return value:
String temp = normalizeText("This is some \“really\” great. (Text)!?");
String result = Obfuscation(temp);
Or:
String result = Obfuscation(normalizeText("This is some \“really\” great. (Text)!?"));
public class InputRealNums1
{
static double [] numArr = new double [(int) (Math.random()*100)];
static String res = "";
public static void main(String[] args)
{
inputArray();
displayArray();
}
static void inputArray()
{
for (int i = 0 ; i < numArr.length ; i++)
{
numArr[i] = Math.random()*100;
}
}
static void displayArray()
{
System.out.println(res.inputArray());
}
}
The aim of this code is to seperate the input and the output. The program would generate certain numbers and then it will display them. I just want to know how to seperate the the input and output with the above methods.
You can display that array by using this method.
public static void displayArray()
{
for (int i = 0 ; i < numArr.length ; i++)
{
System.out.println(numArr[i]);
}
}
But this is not a good way. You can do this by passing parameters to the method.
public static void displayArray(Double[] myArray)
{
for (int i = 0 ; i < myArray.length ; i++)
{
System.out.println(myArray[i]);
}
}
public static void main(String[] args){
// some code in here
displayArray(numArr);
}
The program is to find all of the words in a text file and count how many times each word is found. Our definition of a "word" will be relatively crude and will be done by splitting the line based on characters that are not alphabetic. I know there are easier ways to go about this but we were required to use a class and a search method like the one I attempted. I can't figure out why it's not incrementing word's that are already in wordList. I believe it's either completely skipping over my if (foundAt >=0, or it's not incrementing it correctly, I'm leaning toward my search method being wrong, but I can't figure out the problem. Any and all help is much appreciated, thanks for your time.
public class Hmwk {
public static void main(String[] args) throws FileNotFoundException {
int n=0;
WordCount[] wordList= new WordCount[10000];
Scanner words = new Scanner(new File("input.txt"));
while (words.hasNextLine() && n < 10000)
{
String line = words.nextLine();
String[] tokens = line.split("[^\\p{Alpha}]");
for (int i=0;i<tokens.length;i++)
{
if (tokens[i].length()>0)
{
WordCount word = new WordCount(tokens[i]);
int foundAt = search(wordList, word, n);
if (foundAt >= 0)
{
wordList[foundAt].increment();
}
else
{
wordList[n]=word;
n++;
}
}
}
}
//Arrays.sort(wordList);
String alphabeticFileName = "alphabetic.txt";
String frequencyFilename = "frequency.txt";
PrintWriter output = new PrintWriter(alphabeticFileName);
for (int i=0; i<n;i++)
{
output.println(wordList[i].toString());
}
output.close();
//Sort on frequency somehow
PrintWriter output2 = new PrintWriter(frequencyFilename);
for (int i=0; i < n; i++)
{
output2.println(wordList[i].toString());
}
output2.close();
}
public static int search(WordCount[] list,WordCount word, int n)
{
int result = -1;
int i=0;
while (result < 0 && i < n)
{
if (word.equals(list[i]))
{
result = i;
}
i++;
}
return result;
}
}
class WordCount
{
String word;
int count;
static boolean compareByWord;
public WordCount(String aWord)
{
setWord(aWord);
count = 1;
}
private void setWord(String theWord)
{
word=theWord;
}
public void increment()
{
count=+1;
}
public static void sortByWord()
{
compareByWord = true;
}
public static void sortByCount()
{
compareByWord = false;
}
public String toString()
{
String result = String.format("%s (%d)",word, count);
return result;
}
}
Output:
Peter (1)
Piper (1)
picked (1)
a (1)
peck (1)
of (1)
pickled (1)
peppers (1)
A (1)
peck (1)
of (1)
pickled (1)
peppers (1)
Your increment function is wrong. You've written:
count =+1;
Which only sets the count to one. To increment count by one you put:
count += 1;