Trouble with Arrays in Java and for loops [duplicate] - java

This question already has answers here:
Possible lossy conversion from double to int
(3 answers)
Closed 6 years ago.
I keep getting an error but Im not understanding why. The error is about not being able to convert from double to int but I have everything declared in double so I dont understand why im getting this error.
class ConeArray{
public static void main(String[] args) {
double[] coneArray;
for(double i = 0; i < coneArray.length; i++) {
coneArray = Math.PI * Math.pow((i*2),2) * (1/3 * (4 * i));
System.out.println("Volume of cone: " + coneArray[i]);
}
}
}

You have declared double i in your for loop. Array indexes must be ints.
Also, I don't see you actually instantiating the array in the code sample you provided. The current implementation will throw a NPE if you try to access it.

Related

what code can i use to clear the screen(java)? [duplicate]

This question already has answers here:
commands in java to clear the screen
(11 answers)
Closed 5 years ago.
I'm writing a text-based unit converter and I want to be able to run a clear command so that the window that the program I want to know how I can do it.
I think you can System.exec("clear") but that depends on what operating system the program is running on.
This is my choice for clear:
public static void clearConsole() {
String value = "\n\r";
for (int i = 0; i < 5; ++i) {
value = value + value;
System.out.printf(value);
}
}

Variable declaration not allowed here, used in if statement [duplicate]

This question already has answers here:
JAVA Variable declaration not allowed here
(5 answers)
Closed 5 years ago.
After typing that first part of the if statement, I was going to use the next line to declare a variable (costPerCD) but I'm told "Variable declaration is not allowed here." I'm not sure how else to calculate the costPerCD without using this method. This is an example of what I'm trying to do. Any help would be appreciated.
if ((numCDs>=1 && (numCDs<=4))
double costPerCD= 20.99;
You should declare that variable as a class variable. Then you can access the variable throughout your class.
You need to add an additional ")" to your code after your first condition. This should prevent the error you are getting.
public class CDCal {
//Class Variable can be accessed in this class
private costPerCD;
public CDCal(){
//Assign value when object created
costPerCD = 20.99
}
public double calculateCost(int numCDs){
double total = 0;
if((numCDs >= 1) && (numCDs <= 4))
{
//Calculate total cost of CD's based on number and price
total = costPerCD * numCDs;
}
//Return the total at the end of the method.
Return total;
}
If you have an example I will be happy to review it to help you out.

fun(agr++) vs fun(arg+1) in java [duplicate]

This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 6 years ago.
I was trying to reverse String using recursion as follows.
But when I am calling reverse(arr,start++,end--) it is giving stackoverflow error.
I tried using reverse(arr,start+1,end-1) then it is working fine.
public class Reverse {
public static void main(String[] args) {
char inp[] = "TestString".toCharArray();
int n = inp.length;
reverse(inp, 0,n-1);
System.out.println(String.valueOf(inp));
}
public static void reverse(char[] arr, int start, int end){
if(start>=end)
return ;
char tmp;
tmp = arr[start];
arr[start] = arr[end];
arr[end] = tmp;
reverse(arr,start+1,end-1);//error line
}
What is the problem with reverse(arr,start++,end--)?
I want to know why value of start++ and end-- will not get passed to function.
Have a look at this SO question
SO post-increment-and-pre-increment-concept
Post
reverse(arr,start++,end--) when you do this the incremented/decremented value will not be passed to recursive method, means you are calling the method with original value of start and end result in SO error
Pre
When you do reverse(arr,start+1,end-1) or reverse(arr,++start,--end) incremented and decremented value of start and end will be passed to recursive method.
While debugging in Eclipse IDE check the values of start and end in variables panel if not using IDE write start and end values to console in reverse method

Finding duplicate elements in an array without using nested loops [duplicate]

This question already has answers here:
Find duplicate element in array in time O(n)
(24 answers)
Closed 7 years ago.
I recently had an interview which consisted of following problem. Please help with possible solutions.
Write a method in Java to find duplicate elements in an integer array without using nested loops ( for/ while / do while, etc ) and without using library functions or standard API's.
Hey the below solution has complexity O(n) and works fine. Check if it helps.
public class Main {
public static void main(String[] args) {
int a[] = new int[]{10,3,5,10,5,4,6};
String distinctElement="";
String repetitiveTerms="";
for(int i=0;i<a.length;i++){
if(i==0){
distinctElement+=a[i]+" ";
}
else if(distinctElement.contains(""+a[i])){
repetitiveTerms+=a[i]+" ";
}
else{
distinctElement+=a[i]+" ";
}
}
}
}

Working with Generic arrays [duplicate]

This question already has answers here:
Java generics and Array's
(5 answers)
Closed 8 years ago.
Good day. I have been learning java the last few months. So I created a generic array as follows.
public class Implementation<T> implements IMatrix<T>{
private T[][] genMatrix;
private Integer numberRows;
private Integer NumberCols;
public Implementation(){
generateMatrix();
for(int i = 0;i< numberRows;i++)
{
for(int j =0;j< numberCols;j++)
{
JOptionPane.showInputDialog("Enter value for row " + (i+1) + " and for column " + (j+1)))
}
}
multiplyScalar(5);
}
//generate the array
public void generateMatrix(){
String rowString = JOptionPane.showInputDialog("Enter the number of rows!");
numberRows = Integer.parseInt(rowString);
String colString = JOptionPane.showInputDialog("Enter the number of cols!");
numberCols = Integer.parseInt(colString);
final Object[][] arrayO = (T[][])new Object[numberRows][numberCols];
genMatrix = (T[][])arrayO;
}
//writeElements to the array;
public void writeElem(int x, int y, T value){
genMatrix[x][y] = value;
}
//now that those members are done I have created a method to access the data
public T getElem(Integer i, Integer j){
return (T)genMatrix[i][j];
}
This is where my problem now exists. I have made this two dimensional array. I would like to multiply each value in this array by a Integer c. I have attempted it in the following way and all failed.
public IMatrix<T> multiplyScalar(Integer c) throws MatrixException {
// TODO Auto-generated method stub
for(int i = 0; i< numberRows; i++)
{
for(int j=0;j<numberCols;j++)
{
/**
THIS IS THE POINT AT WHICH IT CRASHES
*/
System.out.println(((Integer)(getElement(i, j)) * c));
}
}
return null;
}
}
The program crashes because of a ClassCastException. I have tried everything in my knowledge to get this to work. I can not multiply the two dimensional array with a Integer. Please help. This uses a interface with many more functions that is irrelevant. Please note that there is a strong possibility that this code crashes as I can not upload the original code.
The problem is that Java doesn't support operator polymorphism. You need T to extend Number and then use method calls. Its a bit more verbose than what one might like though. Its explained quiet well here:
Predefining multiplication for generics in java

Categories

Resources