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;
}
Related
I've got array. I've got an isFull method, which checks if the array is full, but I don't know how to use this to check if it's full, then if it's not full add to the array, otherwise disregard the add call.
The array should take 10 elements and then not accept any more. After 10 elements, it should 'be full' and disregard any addSpy calls.
How would you implement this?
public class ConcreteSubject extends AbstractSubject {
public int arySize;
private int i = 0;
private static AbstractSpy[] spies;
public ConcreteSubject(int a) {
arySize = a;
spies = new AbstractSpy[a];
}
#Override
public void addSpy(AbstractSpy spy) {
if (spies.length < 10) {
spies[i] = spy;
System.out.println("spy added at index " + i);
i++;
}
}
public void isFull() {
//1
boolean b = false;
for (int i = 0; i < spies.length; i++) {
if (spies[i] == null) {
b = true;
}
}
if (!b) {
System.out.println("Array is full");
} else {
System.out.println("Array not full");
}
}
public class TestSpies {
public static void main(String[] args) {
ConcreteSubject cs = new ConcreteSubject(10);
AbstractSpy spy = new ConcreteSpy();
AbstractSpy[] spies = new AbstractSpy[10];
cs.addSpy(spy);
cs.addSpy(spy);
cs.addSpy(spy);
cs.isFull();
}
}
spies.length < 10 isn't correct. It should be spies.length > 0 && i < spies.length to make sure that the following assignment spies[i] = spy; is always valid.
void isFull() should be boolean isFull(). Your implementation looks OK, just return b. full is a tricky word because technically an array is always "full". A better adjective would be populated, filled.
Since addSpy isn't filling null gaps but simply adds a spy to the end, isFull could be rewritten to return spies.length == i;.
The simplest way of doing it would be like that:
#Override
public void addSpy(AbstractSpy spy) {
if (!isFull())
{
spies[i] = spy;
System.out.println("spy added at index " + i);
i++;
}
}
To use that, you should change your isFull method to:
public boolean isFull() {
for (int i = 0; i < spies.length; i++) {
if (spies[i] == null) {
return false;
}
}
return true;
}
Keep a track of the number of filled cells of the array using a variable. And before inserting anything into it, check if the filled cells count strictly less than the size of the array (obviously you want to keep track of the array total size as well).
This may be a very simple question, but I can't seem to find a suitable answer on Google. I have a class called Player, which has a String array called playerInv with a size of 10.
In my Main Activity Class, I want to run a for loop to determine the first index in the array that is empty (""). I then want to populate that with a new string, and then terminate the loop. How do I do this?
Sorry for the nooby question. Like I said, I've tried Google to no avail!
For Loop:
String playerInvTemp[] = thePlayer.getPlayerInv; ERROR -- cannot resolve getPlayerInv
for (int i=0; i < playerInvTemp.length; i++)
{
if ((!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
{
setPlayerInv("Blood Essence", i); ERROR cannot resolve setPlayerInv
//invText.setText();
Blood = true;
break;
}
}
Player Class:
public class Player {
private int playerPos;
private int playerHP;
private String playerInv[];
Player(int startPos, int startHP, String[] newInventory)
{
playerPos = startPos;
playerHP = startHP;
playerInv = newInventory;
}
public int getPlayerPos() {
return playerPos;
}
public void setPlayerPos(int playerPos) {
this.playerPos = playerPos;
}
public int getPlayerHP(){
return playerHP;
}
public void setPlayerHP(int playerHP){
this.playerHP = playerHP;
}
public String getPlayerInv(int pos)
{
return playerInv[pos];
}
public void setPlayerInv(String playerInv[]) {
for (int i=0; i<10; i++)
{
this.playerInv[i] = playerInv[i];
}
}
public void setPlayerInv(String val, int index)
{
this.playerInv[index] = val;
}
public String getPlayerInv()
{
return this.playerInv; *//this gives error "Incompatible types. Required java.lang.string, found java.lang.string[]"*
}
}
Do this
Add these two method in Player class
public void setPlayerInv(String val, int index)
{
this.playerInv[index] = val;
}
public String[] getPlayerInv()
{
return this.playerInv;
}
then change your for loop like this
String playerInvTemp[] = thePlayer.getPlayerInv();
for (int i=0; i < playerInvTemp.length; i++)
{
if (!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
{
setPlayerInv("Blood Essence", i);
//invText.setText();
Blood = true;
break;
}
}
Bunch of problems here, .length() is not valid for an array, it should be .length.
`for (int i=0; i<thePlayer.getPlayerInv(i).length(); i++)`
You most likely mean null or at least need to check for it, here and you need [] not ():
if (thePlayer.getPlayerInv[i] == "" or theplayer.getPlayerInv[i] == null)
This is all wrong, and as a matter of fact you need to post your code and errors, you have many problems and should start with learning some basics about Java.
Try some beginners tutorials (https://www.google.com/search?q=java+tutorials&ie=utf-8&oe=utf-8). You have a lot of both syntax and logic errors.
Do you run an instance of constructor player()??
I did
Player a=new Player();
a.getPlayerInv(0)
and works fine.
Surely the solution to this is the following:
public long myFunc(String name) throws Exception {
for(int i=0;i<amount;i++){
if(this.otherString[i].equals(name))
return longArray[i];
}
throw new Exception("Not found");
}
However, this does not seem to be the case.
You can use Guava, then your code can looks like this
String[] stringArray = {"s1", "s2", "s3"};
int index = Iterators.indexOf(Iterators.forArray(stringArray), new Predicate<String>() {
#Override
public boolean apply(String input) {
return input.equals("s2");
}
});
or simpler
int index = Arrays.asList(stringArray).indexOf("s2");
Your code can also look like this
public class Finder {
private String[] stringArray = {"s1", "s2", "s3"};
public int findIndex(String name) {
for (int i = 0; i < stringArray.length; i++) {
if (stringArray[i].equals(name))
return i;
}
throw new RuntimeException("Not found");
}
public static void main(String... s) {
int index = new Finder().findIndex("s1");
System.out.println(index);
}
}
You can either run your code through a debugger and find out why it doesn't work, or add some println traces to your original code and you'll see what the problem is:
public long myFunc(String name) throws Exception {
System.out.println("Looking for: " + name);
for (int i = 0; i < amount; i++){
if(this.otherString[i].equals(name))
return longArray[i];
System.out.printf("%4d: \"%s\": No match.%n", i, this.otherString[i]);
}
for (int i = amount; i < this.otherString.length; i++)
System.out.printf("%4d: \"%s\": Not checked.%n", i, this.otherString[i]);
throw new Exception("Not found");
}
By the way, make sure you are correctly interpreting the method's behaviour. Could it be that it's finding it but throwing an ArrayIndexOutOfBoundsException because i is greater than longArray.length, and you misinterpret that as the exception you are explicitly throwing?
Turns out '\u0000' was at the end of the string that was meant to be equal. This does not show in printing. Next time I will be more ruthless in the inspection of the debugging. Thank you for all the suggestions though, and sorry for wasting your time.
This might be completely wrong, but isn't the problem just missing curly brackets in the if statement? I am new to the java language and the example is probably messy, but it uses the same structure from your question and works just fine:
public class random_class {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] a = new String[] {"hi!", "hello world!", "ho ho ho world!"};
int b = getHWIndex(a);
System.out.println(b);
}
public static int getHWIndex(String[] stringArray){
int i;
Boolean test = false;
for(i=0;i<stringArray.length;i++){
if(stringArray[i].equals("hello world!")){
test = true;
break;
}
}
if(test == true){
return i;}else{
return i = 0; // this is not a good answer...
//but as you return an int I could not think on a quick way to fix the return when there is no match.
}
}
}
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")
First my call back to increment I know is not correct. I am not sure what to do. I need increment to use temp when it hits that case that requires that call back. I can't change increment to pass a parameter into it because the graders test script wont allow for it. The second problem is that it wont increment any input. For instance if you just call increment on the number 23 it just returns 23. The test script for the grader looks something like this:
public class TestBigNaturalSimple {
public static void main(String[] args) {
BigNatural b1 = new BigNatural(); // default constructor
BigNatural b2 = new BigNatural(23); // one-argument int constructor
BigNatural b3 = new BigNatural("346"); // one-argument String constructor
BigNatural b4 = new BigNatural(b2); // one-argument BigNatural
// constructor
b1.increment();
b3.decrement();
System.out.println(b1.toString()); // should print out 1
System.out.println(b4.toString()); // should print out 23
}
}
My code is:
public class BigNatural {
private String num;
public BigNatural(String input) {
num = input;
}
public BigNatural(BigNatural input) {
num = input.toString();
}
public BigNatural(Integer input) {
num = input.toString();
}
public BigNatural() {
Integer i = 0;
num = i.toString();
}
public void increment() {
Integer first = 0;
Character ch = num.charAt(num.length()-1);
Integer last = Character.digit(ch, 10);
if (num.length() > 1)
{
if (last < 9) {
last++;
}
else
{
if (num.length() >= 2)
{
last = 0;
String temp = new String(num.substring(0, num.length()-2));
increment();
}
else
{
last++;
}
}
}
else
{
if (last < 9)
{
last++;
}
else
{
last = 0;
first = 1;
}
}
String t = last.toString();
if (first > 0)
{
String x = first.toString();
num.concat(x);
}
num.concat(t);
}
public void decrement() {
Character ch = num.charAt(num.length()-1);
Integer last = Character.digit(ch, 10);
if(num.length() > 1)
{
if(last == 0)
{
String temp = new String(num.substring(0, num.length()-2));
decrement();
}
else
{
last--;
}
}
else
{
if(last > 0)
{
last--;
}
else
{
last = 0;
}
}
String t = last.toString();
num.concat(t);
}
public String toString() {
return num;
}
}
That has to be the most complicated way to increment a number I have ever seen. ;) I assume you have to do it that way.
From what I can see you don't change num anywhere. I would expect this to be obvious if you used a debugger. ;)
Try using num = num.concat(t) if you expect num to change.
Note: String is immutable so you cannot change it, you can only replace it.
EDIT: Here is a version provided for your own interest. Your professor will know you didn't write this, so don't copy it. ;)
public void increment() {
num = increment(num);
}
private static String increment(String s) {
if (s.length() <= 0) return "1";
char ch = s.charAt(s.length() - 1);
String top = s.substring(0, s.length() - 1);
return ch < '9' ? top + ++ch : increment(top) + '0';
}
Strings are immutable in Java. Hence, the code
num.concat(t);
in your increment method will not do what you expect.
First, apply the rule don't repeat yourself:
to increment is to add 1
to decrement is to add -1
Thus you simply need to write on function that takes a number as input and add it to your BigNatural:
public void increment() {
add(1);
}
public void decrement() {
add(-1);
}
private void add(int i) {
// Your homework here ...
// You will have only one function to debug and correct, not 2
}
Second: as pointed in other answers, num.concat(t); does not do what you expect, you'll need num = num.concat(t);. Always refer to the Java documentation when you use a function you don't know. If you don't have an editor that allows you to debug your programs, I strongly suggest you get one: Eclipse for instance but other editors might be better as learning tool. The added benefit is that the tools will format the code for you, warn you about lots of mistakes, ...