Issue declaring double two dimensional array - java

I am writing a program which lets the user put their own size of columns and rows for an array. I am using doubles so that the user can use decimals. However, I am getting this error that is telling me that I cannot convert doubles to integers. I don't understand why. I am using eclipse. I declare the array before the main method so I can use it freely the methods throughout the program.
import java.util.*;
public class array
{
private double themainarray[][];
Scanner input = new Scanner(System.in);
private double columnsize;
private double rowsize;
public static void main(String[] args)
{
System.out.print("Welcome!");
}
//Below on the last line of the method is where I am getting the error from eclipse.
public void arrayDimensions()
{
System.out.println("How many columns would you like?");
columnsize = input.nextDouble();
System.out.println("How many rows would you like?");
rowsize= input.nextDouble();
themainarray= new double [rowsize][columnsize];
}
}

array size variables should be of type int only.Other are not allowed.
In your code rowSize,columnSize should be of type int.

You need an int for sizing an array.
private double themainarray[][];
Scanner input = new Scanner(System.in);
private int columnsize;
private int rowsize;
Then when reading input from the user use nextInt();

Related

How do I fix the "float cannot be converted into float[]" error in the below code?

I have written a small program to take number of elements from user and the price of those elements and then print the price.
But the 12th line of this code giving error "float cannot be converted into float[]", and I am not able to figure out how to resolve this. Please provide some help or any modification in the code if needed.
import java.util.Scanner;
public class Main{
public static void main( String args[]){
System.out.println("enter the number of elements :" );
Scanner s1= new Scanner(System.in);
int N = s1.nextInt();
System.out.println("enter the price of all the elements in ascending
order: ");
float[] price =new float[N];
for(int i=0; i<N;i++){
price=s1.nextFloat();
System.out.println(price);
}
}
}
In your code, price is an array
float[] price = ...
And an array of type T consists of elements, each of type T. So you need to assign an element of the array to a float e.g.
price[i] = myFloat;
Formatting and nomenclature are a must when you write code as it makes your code more readable and easy to understand. I have formatted your code and also updated for proper inputs.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
System.out.println("enter the number of elements :");
Scanner s1 = null;
try {
s1 = new Scanner(System.in);
int totalElements = s1.nextInt();
System.out.println("enter the price of all the elements in ascending order :");
float[] price = new float[totalElements];
for (int i = 0; i < totalElements; i++) {
price[i] = s1.nextFloat();
System.out.println(Arrays.toString(price));
}
} finally {
if (s1 != null) {
s1.close();
}
}
}
}
Please take care of below things:
Variable names should start with small case and follow camel casing.
Scanner whenever used needs to be closed.
Your error is resolved by assigning float to one position in array and not to the array. E.g. price[i] = s1.nextFloat();
To print an array, use the Arrays.toString() function.
Happy Coding
import java.util.Scanner;
public class Main{
public static void main( String args[]){
System.out.println("enter the number of elements :" );
Scanner s1= new Scanner(System.in);
int N = s1.nextInt();
System.out.println("enter the price of all the elements in ascending
order :");
float[] price =new float[N];
for(int i=0; i<N;i++){
price[i]=s1.nextFloat();
System.out.println(price[i]);
}
}
}
It should be like this because in the printing statement you've called the whole array that won't give you the element but the some numbers and alphabets thing and also the statement where you're reading the prices by scanner you are not telling the computer to put your price at which index of the array that's why it's giving this error.

Having some issues with my java program

I am trying to do my java assignment. I am just struggling with some of the issues. I could not make the program calculates and outputs the information needed. When I try to run the program, and input the social security number, I get an error and a message saying
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Salaries.inputData(Salaries.java:34) at
Salaries.main(Salaries.java:18)
What am I doing wrong?
Thanks.
Here is a description of the program I am suppose to do.
Write a program that reads Social Security numbers and salaries from the keyboard (Test this by only reading 3 or 4 to start). After the data is read in, the program should add a 2% raise to everyone’s salary. After you give the raise, print out 3 nicely formatted columns of information (Social, salary before raise, salary after raise). You will need a 3rd array holding the new salaries. A separate method should be used for the input, raise, and output.
This is the code I got so far.
import java.util.Scanner;
public class Salaries {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
int[] ssNumbers = new int [10];
double[] salaries = new double [10];
int c;
int rais;
c = inputData (ssNumbers, salaries);
raise (salaries, c, ssNumbers);
output (ssNumbers, salaries, nSalary);
}
public static int inputData (int[]ssn, double[]sals){
int c = 0;
Scanner input = new Scanner (System.in);
int ssNum;
System.out.print("Enter social security number");
ssNum = input.nextInt();
while (ssNum != -1) //using while loop.
{
ssn[c] = ssNum;
System.out.print("Enter salary");
sals[c] = input.nextDouble();
c++;
System.out.print("Please input next security numbers or -1 to quit");
ssn[c] = input.nextInt();
}
return c;
}
public static void raise ( double[] salaries, int c, int[] ssNumbers)
{
double salar;
double rais = 0.02;
for (int count = 0; count < c; count++ )
rais+= rais;
System.out.printf("the salary after raise is %f\n", rais);
return;
}
public static void output (int[] ssNumbers, double[] salaries, double[] nSalary )
{
System.out.printf("%10d%-20d%-20f%", ssNumbers, salaries, nSalary);
return;
These statements:
int[] ssNumbers = new int [0];
double[] salaries = new double [0];
double[] nSalary = new double[0];
create an array of size 0. So when you try to add an element to that array, you are adding to an index that is greater than the array size. I would use an ArrayList so you can grow your array dynamically behind the scenes if you do not know the length.
If you have to use arrays, make sure they are big enough for the data you want to put in, eg
int[] ssNumbers = new int [maxSize];
The value of c in the function inputData is exceeding the length of ssn[] (or maybe sals[], can't tell in your code). Your boundary checking is off, try making sure that c is never less than 0, or larger than the size of ssn[].
You are initializing your array to 0 in the below statement,
int[] ssNumbers = new int [0];
double[] salaries = new double [0];
And you are trying to read past 0 in the below statement (inside inputData function)
ssn[c] = ssNum;
That is the error
You are reading till user inputs -1 which means that you didn't know the number of data/user-inputs prehand. Use LinkedList instead of array.

Calling Methods with Arguments

Write the following methods:
13. A method named loadScores that will be passed the size of an array, prompt the user to enter the appropriate number of floating point grades, then return the loaded array.
I wrote the method, but the problem comes when I try to call it. Here's what I have:
public class ArrayHandout {
public static void main(String[] args) {
int size = loadScores(size);
double[] scoresArray = loadScores(size);
} // end main
public static double[] loadScores(int size) {
Scanner input= new Scanner(System.in);
System.out.println("How many scores would you like to enter?");
size = input.nextInt();
double[] scoresArray = new double[size];
int i;
for(i = 0; i < scoresArray.length; i++) {
System.out.println("Please enter a score:");
scoresArray[i] = input.nextDouble();
}// end for
System.out.println(scoresArray[i]);
return scoresArray;
} // end loadScores
} // end class
I have changed a few things in an attempt to correct some errors I was having when I wrote the original code, and unfortunately don't even remember what those changes were or if they fixed the problems since I can't get it to compile now. I do know that the problem I was having when I could get the original to compile was that it was only printing the first number in the array rather than printing the entire array. Like I said, I don't know if that problem has been corrected since now when I try to compile I receive the following error message:
1 error found:
File: C:\Users\HiTechRedneck\Desktop\Fall 2013\PlayingwithJava\ArrayHandout.java [line: 6]
Error: incompatible types
required: int
found: double[]
I know that size needs to be declared in main because previously I was getting the "cannot find variable size" error, but I think the fact that I'm trying to declare int size as loadScores(size) is throwing it off since the variable I'm declaring is also an argument in the method.
Any help would be greatly appreciated.
Your line int size = loadScores(size) is incorrect. loadScores has a return type of double[], so you need to assign that return value as such.
Just delete that one line and everything should work as expected.
int size = loadScores(size); is throwing an error because loadScores returns an array of type double.
Since the task just wants a code snippet you could probably give size an arbitrary value and pass that in. Or you could get rid of size in main and just pass a number in:
public static void main(String[] args) {
double[] scoresArray = loadScores(5);
}
Edit: Also worth noting that the print statement after the for loop will throw an ArrayIndexOutOfBoundsException since i is now greater than the length of the array. If you want to print the contents of the scoresArray you'll need another loop to traverse through each element.
Second edit: If you're prompting the user for a size you should run your prompt for that in the main method and then pass that to loadScores().
You don't need size at all before you call the function as you read it in the function
your declaration could be :
public static double[] loadScores()
and call
loadScores()
in main. Example:
public class ArrayHandout {
public static void main(String[] args) {
double[] scoresArray = loadScores();
//do whatever you want here or change declaration of
//the function to void and do not return anything
}
public static double[] loadScores() {
Scanner input= new Scanner(System.in);
System.out.println("How many scores would you like to enter?");
int size = input.nextInt();
double[] scoresArray = new double[size];
int i;
for(i = 0; i < scoresArray.length; i++) {
System.out.println("Please enter a score:");
scoresArray[i] = input.nextDouble();
}// end for
System.out.println(scoresArray[i]);
return scoresArray;
}
}
if you don't use the returned array it would be better to do it like this:
public class ArrayHandout {
public static void main(String[] args) {
loadScores();
}
public static void loadScores() {
Scanner input= new Scanner(System.in);
System.out.println("How many scores would you like to enter?");
int size = input.nextInt();
double[] scoresArray = new double[size];
int i;
for(i = 0; i < scoresArray.length; i++) {
System.out.println("Please enter a score:");
scoresArray[i] = input.nextDouble();
}// end for
System.out.println(scoresArray[i]);
}
}
(When a method doesn't return anything you have to specify it by using the void keyword in its signature)-You also need validation but I was only answering to the specific problem -without validation your program will still fail if incompatible values are given.

Use a scanner to read integer values from user input

So far I have this code below:
class Card{
private static String[] pairArray{"A,A","K,K","Q,Q","J,J","10,10",
"9,9","8,8","7,7","6,6","5,5","4,4","3,3","2,2"};
public static void generateRandom(){
int minimum = 0;
int maximum = 13;
int randomNum = minimum + (int)(Math.random()* maximum);
System.out.print("Player 1, You have been dealt a pair of: ");
System.out.println(pairArray[randomNum]);
}
public static void main(String[] args) {
generateRandom();
}
}
It randomly assigns an element from the array to player 1.
I need to read a users input of how many players he wants to play with, then produce this 4 times with each player getting a different set of cards. I think I need to use the scanner feature, but I'm unsure of where to include it in this code.
Scanner s = new Scanner(System.in);
int num = s.nextInt();
That'll read the int the user inputs. And you put that before generateRandom(); in your main. Using the number the user gives, you can do whatever you want with it, including making a while loop that makes that many random stuff. You don't provide much info, so this is as much as I can give.

Java Average Functions

I am new to programming and I am trying to figure out a simple average function. I have written a function to average 3 integers. Now I would like to be able to use any collection class and any number class and get the average. The problem is with these classes you can't use + or / to get the average.
So I am wondering if there are any work-arounds to be able to use these two classes?
here is my first function that works:
package refresh;
import java.util.*;
public class Average {
public static void main( String args[]){
int a, b, c;
float average;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter First Number");
a = scanner.nextInt();
System.out.println("Enter Second Number");
b = scanner.nextInt();
System.out.println("Enter Third Number");
c = scanner.nextInt();
average = (float)(a+b+c)/3;
System.out.println("The Average Is "+average );
}
}
Here what I have so far for my problem:
package refresh;
import java.util.*;
public class Average {
public static void main( String args[]){
Collection numbers;
Number count;
Number average;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Numbers to be averaged");
numbers = (Collection) scanner.match();
count++;
average = numbers/count;
System.out.println("The Average Is "+average);
}
}
Any help would be great! Thanks for your time!
It makes no sense to convert a String into a number (which is what Scanner does) if you don't know what kind of number you're trying to convert it into.
You can represent pretty much any number as a Double. If you need arbitrary precision, use BigDecimal.
The averaging code can be fully generic over the Number interface; just use the doubleValue method. If you need BigDecimal, then it's more complicated and you probably need to do things involving instanceof.

Categories

Resources