I've written a method that has some casting errors:
public class Factor {
public static int[] findFactors(ArrayList<Integer> nums){
ArrayList<Integer> factors= new ArrayList();
for(Integer i=new Integer(0);i<nums.size();i++) {
System.out.println(nums.get(i));
for(int j=0;j<nums.get(i);j++) {
if (nums.get(i) %j==0) {
factors.add(j);
}
}
}
int ct=0;
String factorString= factors.toString();
char[] charArray= factorString.toCharArray();
int[] factorArray= new int[(charArray.length+1)/2];
for(int a=0;a<charArray.length;a++) {
if(charArray[a]==',') {
continue;
} else {
String s= Character.toString(charArray[a]);
factorArray[ct]=Integer.parseInt(s);
ct++;
}
}
return factorArray;
}
}
any help would be appreciated
The problem you have that you only escape the , but when you use toString() on a List it is enclose in square brackets []. When you fix that you will discover that size of result array is not valid also you have to subtract 2 (the brackets).
Good Luck with rest. And please read some basic manual about Java.
Related
I was asked to program a method that receives a scanner, and returns a sorted array of words which contain only letters, with no repetitions (and no bigger in length than 3000). Then, I was asked to program a method that checks whether a certain given string is contained in a given vocabulary. I used a simple binary search method.
This is what I've done:
public static String[] scanVocabulary(Scanner scanner){
String[] array= new String[3000];
int i=0;
String word;
while (scanner.hasNext() && i<3000) {
word=scanner.next();
if (word.matches("[a-zA-Z]+")){
array[i]=word.toLowerCase();
i++;
}
}int size=0;
while (size<3000 && array[size]!=null ) {
size++;
}
String[] words=Arrays.copyOf(array, size);
if (words.length==0 || words.length==1) {
return words;
}
else {
Arrays.sort(words);
int end= removeDuplicatesSortedArr(words);
return Arrays.copyOf(words, end);
}
}
private static int removeDuplicatesSortedArr(String[] array) { //must be a sorted array. returns size of the new array
int n= array.length;
int j=0;
for (int i=0; i<n-1; i++) {
if (!array[i].equals(array[i+1])) {
array[j++]=array[i];
}
}
array[j++]=array[n-1];
return j;
}
public static boolean isInVocabulary(String[] vocabulary, String word){
//binary search
int n=vocabulary.length;
int left= 0;
int right=n-1;
while (left<=right) {
int mid=(left+right)/2;
if (vocabulary[mid].equals(word)){
return true;
}
else if (vocabulary[mid].compareTo(word)>0) {
right=mid-1;
}else {
right=mid+1;
}
}
return false;
}
while trying the following code:
public static void main(String[] args) {
String vocabularyText = "I look at the floor and I see it needs sweeping while my guitar gently weeps";
Scanner vocabularyScanner = new Scanner(vocabularyText);
String[] vocabulary = scanVocabulary(vocabularyScanner);
System.out.println(Arrays.toString(vocabulary));
boolean t=isInVocabulary(vocabulary, "while");
System.out.println(t);
System.out.println("123");
}
I get nothing but-
[and, at, floor, gently, guitar, i, it, look, my, needs, see, sweeping, the, weeps, while]
nothing else is printed out nor returned. Both functions seem to be working fine separately, so I don't get what I'm doing wrong.
I would be very happy to hear your thoughts, thanks in advance :)
This has nothing to do with the console. Your isInVocabulary method is entering an infinite loop in this block:
if (!isInVocabulary(vocabulary, "while")) {
System.out.println("Error");
}
If you were to debug through isInVocabulary, you would see that after a few iterations of the while loop,
left = 0;
right = 2;
mid = 1;
if (vocabulary[mid].equals(word)){
// it doesn't
} else if (vocabulary[mid].compareTo("while") > 0) {
// it doesn't
} else {
right = mid + 1;
// this is the same as saying right = 1 + 1, i.e. 2
}
So you'll loop forever.
I read Bert Bates and Katie Sierra's book Java and have a problem.
The Task: to make the game "Battleship" with 3 classes via using ArrayList.
Error: the method setLocationCells(ArrayList < String >) in the type
SimpleDotCom is not applicable for the arguments (int[])
I understand that ArrayList only will hold objects and never primatives. So handing over the list of locations (which are int's) to the ArrayList won't work because they are primatives. But how can I fix it?
Code:
public class SimpleDotComTestDrive {
public static void main(String[] args) {
int numOfGuesses = 0;
GameHelper helper = new GameHelper();
SimpleDotCom theDotCom = new SimpleDotCom();
int randomNum = (int) (Math.random() * 5);
int[] locations = {randomNum, randomNum+1, randomNum+2};
theDotCom.setLocationCells(locations);
boolean isAlive = true;
while(isAlive) {
String guess = helper.getUserInput("Enter the number");
String result = theDotCom.checkYourself(guess);
numOfGuesses++;
if (result.equals("Kill")) {
isAlive = false;
System.out.println("You took " + numOfGuesses + " guesses");
}
}
}
}
public class SimpleDotCom {
private ArrayList<String> locationCells;
public void setLocationCells(ArrayList<String> loc) {
locationCells = loc;
}
public String checkYourself(String stringGuess) {
String result = "Miss";
int index = locationCells.indexOf(stringGuess);
if (index >= 0) {
locationCells.remove(index);
if(locationCells.isEmpty()) {
result = "Kill";
} else {
result = "Hit";
}
}
return result;
}
}
public class GameHelper {
public String getUserInput(String prompt) {
String inputLine = null;
System.out.print(prompt + " ");
try {
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
inputLine = is.readLine();
if (inputLine.length() == 0)
return null;
} catch (IOException e) {
System.out.println("IOException:" + e);
}
return inputLine;
}
}
convert ArrayList to int[] in Java
Reason for Basic Solution
Here's a simple example of converting ArrayList<String> to int[] in Java. I think it's better to give you an example not specific to your question, so you can observe the concept and learn.
Step by Step
If we have an ArrayList<String> defined below
List<String> numbersInAList = Arrays.asList("1", "2", "-3");
Then the easiest solution for a beginner would be to loop through each list item and add to a new array. This is because the elements of the list are type String, but you need type int.
We start by creating a new array of the same size as the List
int[] numbers = new int[numbersInAList.size()];
We then iterate through the list
for (int ndx = 0; ndx < numbersInAList.size(); ndx++) {
Then inside the loop we start by casting the String to int
int num = Integer.parseInt(numbersInAList.get(ndx));
But there's a problem. We don't always know the String will contain a numeric value. Integer.parseInt throws an exception for this reason, so we need to handle this case. For our example we'll just print a message and skip the value.
try {
int num = Integer.parseInt(numbersInAList.get(ndx));
} catch (NumberFormatException formatException) {
System.out.println("Oops, that's not a number");
}
We want this new num to be placed in an array, so we'll place it inside the array we defined
numbers[ndx] = num;
or combine the last two steps
numbers[ndx] = Integer.parseInt(numbersInAList.get(ndx));
Final Result
If we combine all of the code from "Step by Step", we get the following
List<String> numbersInAList = Arrays.asList("1", "2", "-3");
int[] numbers = new int[numbersInAList.size()];
for (int ndx = 0; ndx < numbersInAList.size(); ndx++) {
try {
numbers[ndx] = Integer.parseInt(numbersInAList.get(ndx));
} catch (NumberFormatException formatException) {
System.out.println("Oops, that's not a number");
}
}
Important Considerations
Note there are more elegant solutions, such as using Java 8 streams. Also, it's typically discouraged to store ints as Strings, but it can happen, such as reading input.
I can't see where you call setLocationCells(ArrayList<String>) in your code, but if the only problem is storing integers into an ArrayList there is a solution:
ArrayList<Integer> myArray = new ArrayList<Integer>();
myArray.add(1);
myArray.add(2);
It is true that you can't use primitive types as generics, but you can use the Java wrapper types (in this case, java.lang.Integer).
I have to find a pattern in the array that I am creating and then stop adding numbers to the array when the pattern is seen to be duplicated twice. The pattern that I am trying to find is 4-2-1, so when that is repeated twice in a row in this arithmetic sequence, the program is finished. Currently my output gives me one sequence of the pattern with an error following: [10, 5, 16, 8, 4, 2, 1] Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Size: 0
**YES I HAVE TRIED TO DEBUG USING ECLIPSE BUT I AM STILL STUCK So if someone could help me figure out why it is only printing the sequence with one repetition of the pattern at the end, that would help me profusely. Thanks. My code:
Scanner inData = new Scanner(new File("test.txt"));
ArrayList<Integer> list= new ArrayList<Integer>();
while (inData.hasNext())
{
int numA=inData.nextInt();
int var;
boolean done=false;
list.add(numA);
while(!done)
{
var=list.size();
for(int i=var;i>0;i--)
{
numA=list.get(var-1);
if(numA%2==0)
{
numA/=2;
list.add(numA);
}
else
{
numA=(numA*3)+1;
list.add(numA);
}
var=list.size();
if (var>6)
{
for(int j=1;j>=6;j++)
{
if(list.get(var-1)==1)
{
if(list.get(var-4)==1)
{
if(list.get(var-2)==2)
{
if(list.get(var-5)==2)
{
if(list.get(var-3)==4)
{
if(list.get(var-6)==4)
{
done=true;
}
}
}
}
}
}
}
System.out.print(list);
list.clear();
}
}
}Scanner inData = new Scanner(new File("test.txt"));
ArrayList<Integer> list= new ArrayList<Integer>();
while (inData.hasNext())
{
int numA=inData.nextInt();
int var;
boolean done=false;
list.add(numA);
while(!done)
{
var=list.size();
for(int i=var;i>0;i--)
{
numA=list.get(var-1);
if(numA%2==0)
{
numA/=2;
list.add(numA);
}
else
{
numA=(numA*3)+1;
list.add(numA);
}
var=list.size();
if (var>6)
{
for(int j=1;j>=6;j++)
{
if(list.get(var-1)==1)
{
if(list.get(var-4)==1)
{
if(list.get(var-2)==2)
{
if(list.get(var-5)==2)
{
if(list.get(var-3)==4)
{
if(list.get(var-6)==4)
{
done=true;
}
}
}
}
}
}
}
System.out.print(list);
list.clear();
}
}
}
The simplest approach is using Collections.indexOfSubList. Something like this.
int a [] = {4,2,1,4,2,1};
if(Collections.indexOfSubList(list, Arrays.asList(a))!=-1){
return true;
}
return false
Well, there appear to be a few errors with your code.
I'm going to enumerate some here: fix as many as possible, then check to see if your code works.
int i=var; i>0; i--. Since var is the size of your array, it is outside the bounds. Java uses 0-based arrays, meaning that valid indeces are in the range [0,size-1] (inclusive). Replace with int i=var - 1; i >= 0; i--
The j loop does nothing but prevent anything from happening (nothing can enter, since you start at 1 and immediately break the loop by imposing the restriction >=6 and j is never used. Remove the loop.
i think that the problem is root being null. WOuld someone one teach me how to do it the proper way ? Because i don't know why it is null ... I think the remove function is well implemented, but due to root being null it doesn't continue executing. Help please.
Any recommendation are welcome too :D
public static void main(String[] args) {
Tree t = new Tree("");
String msg;
String[] inputs;
Scanner sc = new Scanner(System.in);
ArrayList <String> palavras = new ArrayList <String>();
int i = 0;
while (true) {
msg = sc.nextLine();
if (msg.equals("")) {
break;
}
inputs = msg.split(" ");
i = 0;
while (i < inputs.length) {
palavras.add(inputs[i]);
i++;
}
}
i = 0;
while (i < palavras.size()) {
if (palavras.get(i).equals("REMOVE")) {
t.remove(palavras.get(i+1));
palavras.remove(i+1);
i+=1;
} else {
t.insert(palavras.get(i).toLowerCase());
i++;
}
}
t.postorder();
t.preorder();
t.inorder();
}
**********************************************************
public void remove( String word)
{
Node father=root;
Node actual=root;
boolean leftnode=true;
if(root!=null){
while(!word.equals(actual.str))
{
father=actual;
if(word.compareTo(actual.str)<0)
{
leftnode=true;
actual=actual.left;
}
else{
leftnode=false;
actual=actual.right;
}
if(actual==null){
return ;
}
}
actual.occ = 0;
}
}
I was implementing Splay tree which works on the same concept as red black tree and at a point I was stuck like this. I will suggest you to draw the flow diagram of your code and then code it again. I hope your problem will be solved as mine.
you can refer this and this articles.
I am writing a program that will add 2 arrays that are 40 elements long together. I have to keep the add() method as a HugeInteger (can’t change it to a integer) so when I try to return the sum of the 2 integers it gives me “HugeInteger#77e1ee5d”. Could someone let me know what this means and also tell me how I could fix it.
Thank you
public class HugeInteger {
private int[] integer ;
public HugeInteger(int num[]){
integer =new int [40];
for(int x=1; x<=39; x++){
integer[x]= num[x];
}
}
public void parse(String s){
for(int i=0; i<=s.length(); i++){
integer[i]=Integer.parseInt(s.substring(i,i+1));
}
}
public HugeInteger add(HugeInteger a1){
HugeInteger sum = new HugeInteger(integer);
int cary=0;
for (int i=39; i>=0; i--){
sum.integer[i]=integer[i]+a1.integer[i]+cary;
if(sum.integer[i]>=10){
cary=1;
sum.integer[i]-=10;
}else{
cary=0;
}
}
return sum;
}}
//This is my test program
public class HugeIntegerTest {
public static void main(String[] args) {
int []num={1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
HugeInteger hi= new HugeInteger(num);
System.out.println("Addition: "+hi.add(hi));
}
}
That's the output of the default Object.toString() method. You need to override toString and provide a better implementation yourself. An example:
#Override
public String toString() {
StringBuilder builder = new StringBuilder(integer.length);
for(int digit : integer) {
builder.append(digit);
}
return builder.toString();
}
Note that this implementation does not trim leading zeros, i.e. it will print "0000...000123" instead of just "123". This is left as an exercise for the reader, erm, programmer. ;-)
Another tip: in your constructor, your loop should start at i=0. Otherwise the most significant digit (integer[0]) will always be zero, for example your test program would give you a HugeInteger representing 0 instead of 1039.
You have to write your own version of the toString() for HugeInteger to make it display correctly.