package dspermutation;
import java.util.Scanner;
public class DSPermutation {
String s;
char[] c;
int n;
public static void main(String[] args) {
DSPermutation ds=new DSPermutation();
ds.input();
}
private void input() {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
s=sc.next();
c=s.toCharArray();
n=c.length;
permutation(c,n-1,0);
}
private void permutation(char[] cc,int nn,int ii) {
if(ii==nn)
{
System.out.println(cc);
}
else
{
for(int j=ii;j<=nn;j++)
{
swap(cc[ii],cc[j]);
permutation(cc,nn,ii+1);
swap(cc[ii],cc[j]);
}
}
}
private void swap(char p, char c0) {
int x=s.indexOf(p);
int y=s.indexOf(c0);
/*1*/ char temp=c[x];
/*2*/c[x]=c[y];
/*3*/c[y]=temp;
/*c[x]=c0;
c[y]=p;*/
}
}
The above program is for printing all permutations of a given string.The result is coming true but in swap() method if i replace line 1,2,3(written in comment) by logic written in comment(after line 1,2,3) then answer comes wrong. Why could this be happening?
Your mistake is assuming c[x] == p and c[y] == c0. But the indexes x and y are derived from the immutable string s, which doesn't reflect the values in c in its shuffled state.
You are swapping values of character array using immutable string's position (i.e String always holds the same initial values). To make your commented code work you have to add this s = String.valueOf(c);at the end of swap function.
private void swap(char p, char c0) {
int x = s.indexOf(p);
int y = s.indexOf(c0);
// char temp = c[x];
// c[x] = c[y];
// c[y] = temp;
c[y] = p;
c[x] = c0;
s = String.valueOf(c);
}
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 wrote this code. My aim is to write the string in char.
But i'm getting ArrayIndexOfBoundsException error.
public class Charwork {
char[] letter;
int keepInt;
public Charwork()
{
letter = new char[keepInt];
}
public void copy(String nameToCoppy)
{
this.keepInt = nameToCoppy.length();
System.out.println(this.keepInt);
for(int x = 0; x < this.keepInt;x++)
{
letter[x] = nameToCoppy.charAt(x);
System.out.println(letter[x]);
}
}
}
Your issue is your array is instantiated with a int that is null or 0. Moving that one line in your constructor to the copy function after getting string length should do the trick.
public Charwork()
{
}
public void copy(String nameToCoppy)
{
this.keepInt = nameToCoppy.length();
letter = new char[keepInt];
System.out.println(this.keepInt);
for(int x = 0; x < this.keepInt;x++)
{
letter[x] = nameToCoppy.charAt(x);
System.out.println(letter[x]);
}
}
You create an object Charworkwhile instantiating variable char[] letter with length keepInt - but keepInt is zero at the moment, beacuse int is primitive and instantinated with default 0 value.
Then, in copy method you change value of keepInt, but that's irrelevant, because an array char[] letter is already set with length 0.
// Line in Main Code
public class Assignment7 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input;
char userChoice;
int newVal, index;
IntegerList intList = null;
printMenu();
do {
System.out.print("Please enter a command or type? ");
input = scan.nextLine();
if (input.length() != 0)
userChoice = input.charAt(0);
else
userChoice = ' ';
switch (userChoice) {
case 'a':
System.out.print("How big should the list be? ");
intList = new IntegerList(scan.nextInt());
scan.nextLine();
System.out.print("What is range of the values for each random draw? ");
intList.randomize(scan.nextInt());
scan.nextLine();
break;
case 'b':
System.out.println(intList.toStrng());
break;
The above code is part of my main code, where I get user input and as them to set the boundary conditions of the array. case 'b' asks to print out the array by calling the function in the class which should return the array as a string with 10 elements per line.
// line in class
import java.util.Arrays;
import java.util.Random;
public class IntegerList {
private int arrSize;
public IntegerList(int size) {
size = arrSize;
}
private int[] IntArray = new int[arrSize];
public void randomize (int num) {
for(int i = 0;i<IntArray.length;i++) {
IntArray[i] =(int) (Math.random()*(num+1));
}
}
public void addElement(int newVal, int index) {
for(int i = index;i<IntArray.length;i++) {
int temp = IntArray[i];
IntArray[i]=newVal;
IntArray[i+1]=temp;
if(i == IntArray.length){
increaseSize(IntArray);
}
}
}
private static void increaseSize(int[] x) {
int[] temp = new int[2*x.length];
for(int i = 0; i<x.length;i++) {
temp[i]=x[i];
}
x = temp;
}
public void removeFirst(int nextInt) {
// TODO Auto-generated method stub
}
public String range() {
// TODO Auto-generated method stub
return null;
}
public String toStrng() {
String arrayOut = " ";
for(int i = 0; i<IntArray.length; i++ ) {
if(i%10 == 0 ) {
arrayOut+="\n";
}
arrayOut += IntArray[i] + " " ;
}
return arrayOut;
}
}
I'm trying to convert the array into a string and then return int and have it display 10 elements per line. I'm pretty sure I have the logic right, however, when I run the code, it does not display the array at all. How should I go about fixing this?
Look at how you are creating your array of integers through your current constructor...
public IntegerList(int size) {
size = arrSize;
}
private int[] IntArray = new int[arrSize];
When you call
intList = new IntegerList(scan.nextInt());
in your menu program, your array list won't magically know it needs to be re-initialized. It will be 0 since the value of arrSize is always 0 when you create your IntegerList object. Furthermore you have the assignment of the variables switched. Change your constructor to the following
private int[] IntArray = null;
public IntegerList(int size) {
arrSize = size;
IntArray = new int[arrSize];
}
Everything seems to work because the size of your array was always 0 and your methods just return.
You did not initialize your arrSize
You can modify your constructor to initialize arrSize
public IntegerList(int size) {
arrSize = size;
}
Also, in you toStrng method, you can just make use of arrSize instead of IntArray.length
The code is close to correct, but I cannot see how I can move from System.out.println to a toString() method here, what am I missing?
import java.util.Scanner;
class Histogram
{
private int[] numCount;
int size=0;
public Histogram(String line)
{
setList(line);
}
public void setList(String line)
{
numCount = new int[20];
for(int i=0;i<10;i++)
numCount[i]=0;
Scanner chopper = new Scanner (line);
while (chopper.hasNextInt())
{
int num = chopper.nextInt();
numCount[num]++;
}
for(int i=0;i<10;i++)
System.out.println(i+"::"+numCount[i]);
System.out.println();
System.out.println();
}
}
First, in setList() the default value of the primitive int is 0. And if you're using decimal math you only need 10 digits. And remove the println(s);
public void setList(String line) {
numCount = new int[10]; // <-- base 10
Scanner chopper = new Scanner(line);
while (chopper.hasNextInt()) {
int num = chopper.nextInt();
numCount[num]++;
}
// once the loop is done, you can do
System.out.println(this); // <-- will call toString so
}
Next override toString(). You might use Arrays.toString(int[]) which Returns a string representation of the contents of the specified array like
#Override
public String toString() {
return Arrays.toString(numCount);
}
Finally, I personally would have preferred an implementation of setList(String) like
private int[] numCount = new int[10]; // <-- base 10
public void setList(String line) {
for (char ch : line.toCharArray()) {
numCount[Character.digit(ch, 10)]++;
}
}
I am writing a program to reverse a word using a stack data structure. The way it's supposed to work is that I input a string, insert each character of the string in a stack object, then I would pop each object out of the stack and print them. The word will be in the reverse order of the original input since that's just how stacks work.
I keep getting an index out of bounds exception; debugging makes me suspect that it has to do with the initial array initialization within the Stack class, but it could also have to do with the push() function.
Here's the entire code:
public class Stack // object to emulate stack data structure
{
private int stackMaxSize;
private char stackArray[];
private int currentSize;
public Stack() // if initialized without any parameters
{
this(100);
}
public Stack(int maxSize) // if initialized with parameter
{
maxSize = stackMaxSize;
stackArray = new char[stackMaxSize];
currentSize = -1;
}
public void push(char c) //pushes new character into stack
{
stackArray[++currentSize] = c;
}
public char pop() //pops character out of stack
{
return stackArray[currentSize--];
}
public char peek() // returns character on top of stack
{
return stackArray[currentSize];
}
public boolean isEmpty() // returns whether stack is empty or not
{
return (currentSize < 0);
}
}
and here's the main:
import java.util.Scanner;
public class ReverseWord
{
public static void main(String[] args)
{
Stack wordStack = new Stack(100); // default size is 100
System.out.print("Enter the word to be reversed: ");
String word = getString();
for (byte i = 0; i <= word.length(); i++) // inserts word into stack char by char
{
wordStack.push(word.charAt(i));
}
System.out.print(wordStack.pop());
}
static String getString()
{
Scanner input = new Scanner(System.in);
String s = input.nextLine();
return s;
}
}
Thanks a lot!
JLL
In your Stack(int) constructor
maxSize = stackMaxSize;
should be
stackMaxSize = maxSize;
The corrected and working code as follows: (Note that, the main function is written in Stack class for simplicity and corrected code lines are commented)
public class Stack // object to emulate stack data structure
{
private final int stackMaxSize;
private final char stackArray[];
private int currentSize;
public Stack() // if initialized without any parameters
{
this(100);
}
public Stack(final int maxSize) // if initialized with parameter
{
this.stackMaxSize = maxSize; /* corrected: assignment reversed */
this.stackArray = new char[this.stackMaxSize];
this.currentSize = -1;
}
public void push(final char c) // pushes new character into stack
{
this.stackArray[++this.currentSize] = c;
}
public char pop() // pops character out of stack
{
return this.stackArray[this.currentSize--];
}
public char peek() // returns character on top of stack
{
return this.stackArray[this.currentSize];
}
public boolean isEmpty() // returns whether stack is empty or not
{
return this.currentSize < 0;
}
public static void main(final String[] args) {
Stack wordStack = new Stack(100); // default size is 100
System.out.print("Enter the word to be reversed: ");
String word = getString();
/* corrected: i <= word.length() >> i < word.length() */
for (byte i = 0; i < word.length(); i++) // inserts word into stack char by char
{
wordStack.push(word.charAt(i));
}
/* corrected: while loop added to consume the entire stack */
while (!wordStack.isEmpty()) {
System.out.print(wordStack.pop());
}
}
static String getString() {
Scanner input = new Scanner(System.in);
String s = input.nextLine();
return s;
}
}
The problems with the original program was that:
1) For loop should be:
for (byte i = 0; i < word.length(); i++)
instead of <= (thanks to ovunccetin)
2) In the constructor of the Stack class
maxSize = stackMaxSize;
should be:
stackMaxSize = maxSize;
Thanks to Ravi Thapliyal