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.
Related
public class CharacterList {
private char [] charArray;
private int count;
public CharacterList(int arraySize){
charArray = new char[arraySize];
count = 0;
}
private int indexOf(char searchingChar) {
int a = 0;
for (int i = 0; i < charArray.length; i++) {
if(charArray[i] == searchingChar)
a = i;
else
a = -1;
}
return a;
}
public boolean addCharacter(char characterToAdd){
if(indexOf(characterToAdd) == -1){
doubleArrayCapacity();
count ++;
return true;
} else if(indexOf(characterToAdd) == 0){
charArray[0] = characterToAdd;
count++;
return true;
} else
return false;
}
}
I need to construct all the methods given in the attached list. I have done these many so far and the remaining are hard to get. Could someone:
1.) Check if the code I written till now is correct?
2.) Help me with the other constructors
Thank you in advance
Use an IDE, it will tell you that line 31 and 32 are the errors:
c cannot be resolved to a variable
Fix:
Rename c to characterToAdd
The method doubleArrayCapacity() is undefined for the type CharacterList
Fix:
Create method doubleArrayCapacity()
private void doubleArrayCapacity() {
// TODO Auto-generated method stub
}
And your code will compile (doesn't mean that it's working!).
Contructor is ok. Only one think I've found incorrect it your code is lack of method public void doubleArrayCapacity(). Probably you have forgoted implement or you avoid when copy source code here.
Another cause, where could be error is call of this contractor. How you call it? With argument or without? How that looks like?
public void doubleArrayCapacity() {
//create new array of char, which is double length
char [] newCharArray = new char[this.charArray.length*2];
//prescribe values from old array to new one
for(int i=0; i<this.charArray.length-1; i++) {
newCharArray[i] = this.charArray[i];
}
//set newCharArray set new value of your field charArray
this.charArray = newCharArray;
}
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);
}
public class BookLab2
{
public static void main (String [] args)
{
BLab2Cons alph;
char current;
int index;
Scanner scan = new Scanner(System.in);
alph = new BLab2Cons(26);
String answer;
System.out.println("Give me a sentence that ends with a period.");
answer = scan.nextLine();
System.out.println(alph.length);
for (int x = 0; x < answer.length(); x++)
{
current = answer.charAt(x);
index = answer.convertIndex(x); //This is where I am having problems.
}
}
}
public class BLab2Cons
{
int index;
int alph[];
char test;
public int length;
public BLab2Cons(int size)
{
alph = new int[size];
length = alph.length;
}
public int convertIndex(char x) //The method that is not working.
{
index = (int)x - (int)'a';
return index;
}
}
This is the class where I make my methods, and if you test it out, convertIndex does not work. I have been trying for almost an hour now to try to get it to take in a char as an argument but return an int. I am not a very advanced coder so keeping it simple would be much obliged. I have tried to cast the char to an int, which seems to have worked, but when I need to actually use the method in my main code, it seems I always have to use a string as the argument rather than a char.
EDIT: this is the error I get: http://prntscr.com/e3tqsw
The problem is that you're not calling the method correctly. Currently, you have
index = answer.convertIndex(x);
but convertIndex is an instance method defined in your BLab2Cons class. Therefore, the method requires an instance of the class BLab2Cons in order to call it. Also, you're passing in x which is an int but your method is defined to take a char parameter. So the simple fix is to call the method using alph like so,
index = alph.convertIndex(current);
Try this:
index = alph.convertIndex(current);
Pass in current to convertIndex()
As per this, I think you may want to replace 'x' with 'current'
So for an assignment in my class, we have a lab where we have to write code that will do three things:
generate an array of 50 random numbers from 0-9.
Return how many 8's appear in the array.
Return the number of runs in the array.
We were given a .java file to start out with that is this:
package ArrayOfInts;
public class ArrayOfInts {
private int [] intArray;
private int eights;
private int runs;
//Sets intArray to the parameter and initializes all other variables
public ArrayOfInts(int [] x){
}
//Returns how many 8's are in the array.
public int findTheEights(){
return eights;
}
//Returns the number of runs in the array.
public int countTheRuns(){
return runs;
}
}
The code I've written so far is this:
package ArrayOfInts;
public class ArrayOfIntsTester {
public static void main(String [] args){
int [] testArray = new int [50];
for(int i = 0; i < testArray.length; i++){
int x = (int)(Math.random()*9);
testArray[i]= x;
System.out.print(x + ", ");
}
System.out.println();
ArrayOfInts test = new ArrayOfInts(testArray);
System.out.println(test.findTheEights());
System.out.println(test.countTheRuns());
}
}
I honestly have no idea where to start with this. Help?? The code I've written generates the correct type of array, but I don't know how to count what I need to count for it.
For the eights: iterate over the array and do eights++ everytime you find an eight.
if (testArray[i] == 8){
eights++
}
Here is some pseudo code to help you count the eights:
numberOfEights = 0;
for each element in testArray{
if (element equals 8) {
numberOfEights = nnumberOfEight + 1
} else {
nothing to do
}
}
return numberOfEights
Try to turn this to java code.
For the other part, i don't understand what is your runs.
//To count number of eights, iterate through array with a counter and increment it when we see an 8
public ArrayOfInts(int [] x){
eights = 0; //reset our count
for (int currentInt : intArray)
{
if (currentInt == 8)
eights++;
}
//Process runs here
}
To count the number of eight just use another variable which is initialized to 0 , like this :-
int c=0;
for (i=0;i<testArray.length;i++)
{
if (testArray[i] == 8)
{
c++;
}
}
Now your c has the number of 8's present in your array you cant print its value.
--> If that's what you are trying to ask
first initialize the array in constructor
public ArrayOfInts(int [] x){
intArray=x;
}
initialize the eights to 0
private int eights=0;
then update your count method
public int findTheEights(){
for(int current:intArray)
{
if(current==8){ eights++;}
}
return eights;
}
In JavaScript you could do it like the following example.
Counting of eights can be done directly at the initializaion of the array.
And if I understand you right, you'd like to count the instances of the object with the countTheRuns(). That can be done with a class variable.
If you'd like to play with the code, you'll find it here at jsFiddle.
/*So for an assignment in my class, we have a lab where we have to write code that will do three things:
generate an array of 50 random numbers from 0-9.
Return how many 8's appear in the array.
Return the number of runs in the array.
*/
(function() {
var MAX_RANDOM = 50;
var NUM_RANGE = 9; // 0 to 9
function ArrayOfInts() {
this.eights = 0;
this.numbers = [];
this.init();
// class variabe run_counter
ArrayOfInts.run_counter = (ArrayOfInts.run_counter || 0) +1;
this.getNumbers = function() {
return this.numbers;
};
this.getEights = function() {
return this.eights;
};
}
ArrayOfInts.prototype.init = function() {
for (var i=0; i< MAX_RANDOM; i++) {
var randNum = Math.floor(Math.random()*(NUM_RANGE+1));
this.numbers.push(randNum);
if (randNum == 8) this.eights++;
}
};
// demo usage code ---------------------
var array = new ArrayOfInts();
var array2 = new ArrayOfInts();
document.getElementById('output').innerHTML = array.getNumbers();
console.log(array.getNumbers());
document.getElementById('output').innerHTML += '<br/>The array has the following no. of eights: ' + array.getEights();
document.getElementById('output').innerHTML += '<br/>The number generation ran ' + ArrayOfInts.run_counter + ' times.';
})();
<div id="output"></div>
I wanted to know if there's a native method in array for Java to get the index of the table for a given value ?
Let's say my table contains these strings :
public static final String[] TYPES = {
"Sedan",
"Compact",
"Roadster",
"Minivan",
"SUV",
"Convertible",
"Cargo",
"Others"
};
Let's say the user has to enter the type of car and that then in the background the program takes that string and get's it's position in the array.
So if the person enters : Sedan
It should take the position 0 and store's it in the object of Cars created by my program ...
Type in:
Arrays.asList(TYPES).indexOf("Sedan");
String carName = // insert code here
int index = -1;
for (int i=0;i<TYPES.length;i++) {
if (TYPES[i].equals(carName)) {
index = i;
break;
}
}
After this index is the array index of your car, or -1 if it doesn't exist.
for (int i = 0; i < Types.length; i++) {
if(TYPES[i].equals(userString)){
return i;
}
}
return -1;//not found
You can do this too:
return Arrays.asList(Types).indexOf(userSTring);
I had an array of all English words. My array has unique items. But using…
Arrays.asList(TYPES).indexOf(myString);
…always gave me indexOutOfBoundException.
So, I tried:
Arrays.asList(TYPES).lastIndexOf(myString);
And, it worked. If your arrays don't have same item twice, you can use:
Arrays.asList(TYPES).lastIndexOf(myString);
try this instead
org.apache.commons.lang.ArrayUtils.indexOf(array, value);
Use Arrays class to do this
Arrays.sort(TYPES);
int index = Arrays.binarySearch(TYPES, "Sedan");
No built-in method. But you can implement one easily:
public static int getIndexOf(String[] strings, String item) {
for (int i = 0; i < strings.length; i++) {
if (item.equals(strings[i])) return i;
}
return -1;
}
There is no native indexof method in java arrays.You will need to write your own method for this.
An easy way would be to iterate over the items in the array in a loop.
for (var i = 0; i < arrayLength; i++) {
// (string) Compare the given string with myArray[i]
// if it matches store/save i and exit the loop.
}
There would definitely be better ways but for small number of items this should be blazing fast. Btw this is javascript but same method should work in almost every programming language.
Try this Function :
public int indexOfArray(String input){
for(int i=0;i<TYPES,length();i++)
{
if(TYPES[i].equals(input))
{
return i ;
}
}
return -1 // if the text not found the function return -1
}
Testable mockable interafce
public interface IArrayUtility<T> {
int find(T[] list, T item);
}
implementation
public class ArrayUtility<T> implements IArrayUtility<T> {
#Override
public int find(T[] array, T search) {
if(array == null || array.length == 0 || search == null) {
return -1;
}
int position = 0;
for(T item : array) {
if(item.equals(search)) {
return position;
} else {
++position;
}
}
return -1;
}
}
Test
#Test
public void testArrayUtilityFindForExistentItemReturnsPosition() {
// Arrange
String search = "bus";
String[] array = {"car", search, "motorbike"};
// Act
int position = arrayUtility.find(array, search);
// Assert
Assert.assertEquals(position, 1);
}
Use this as a method with x being any number initially.
The string y being passed in by console and v is the array to search!
public static int getIndex(int x, String y, String[]v){
for(int m = 0; m < v.length; m++){
if (v[m].equalsIgnoreCase(y)){
x = m;
}
}
return x;
}
Refactoring the above methods and showing with the use:
private String[] languages = {"pt", "en", "es"};
private Integer indexOf(String[] arr, String str){
for (int i = 0; i < arr.length; i++)
if(arr[i].equals(str)) return i;
return -1;
}
indexOf(languages, "en")