OK so in my class file I have
import java.util.Scanner;
public class PriceArray
{
int n;
Scanner sc = new Scanner(System.in);
double pArray[];
public PriceArray(int nBooks)
{
pArray = new double[n];
n = nBooks;
}
public void pEntry()
{
double p;
for(int i =0;i<n;i++)
{
p=-1;
while(p<0)
{
System.out.println("Please enter a positive price for item #" + i);
p = sc.nextDouble();
pArray[i] = p;
}
}
}
and in my test file I have
public class PriceArrayTest
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n;
do
{
System.out.println("Please enter a positive number of books in the store");
n = sc.nextInt();
}while(n<0);
PriceArray store = new PriceArray(n);
store.pEntry();
when the pEntry method is called I am getting arrayindexoutofboundexception: 0 for the line
pArray[i] = p;
in the entry method, my question is why am I getting this error when the array has been initialized?
You need to switch "n = nBooks;" to happen before "pArray = new double[n];"
Look closely at the value of n when you initialize pArray with new double[n]:
int n;
double pArray[];
public PriceArray(int nBooks) {
pArray = new double[n];
n = nBooks;
}
At that point in the code, n was not assigned a value yet.
Since it's an int, its value defaults to 0 in this case.
As a result, pArray effectively gets initialized with new double[0],
an empty array, so referencing index 0 will be out of bounds.
One way to fix:
public PriceArray(int nBooks) {
pArray = new double[nBooks];
n = nBooks;
}
Another way:
public PriceArray(int nBooks) {
n = nBooks;
pArray = new double[n];
}
You are hiding the value of n in your code, so you don't get the value you read in.
Hiding Fields
(Or as mentioned you may just be using two different n without hiding. The other n is simply uninitialized.)
This variable hides (or at least isn't the same as) the value you use in the other part of your code:
int n;
do
{
System.out.println("Please enter a positive number of books in the store");
n = sc.nextInt(); // <-- This 'n' hides the other n
And the other part of your code, which does not use the same value of n
public class PriceArray
{
int n; // <-- a *DIFFERENT* 'n'
Scanner sc = new Scanner(System.in);
double pArray[];
public PriceArray(int nBooks)
{
pArray = new double[n]; // <-- This 'n' is not the same as the other
n = nBooks;
Related
I bought Head First Java book, and i am trying to do the exercise sink a startup.
After a while the book introduce ArrayList, and show how to use it in the class and its' method.
Problem is once i change everything with arraylist, the MAIN doesn't work, becasue at start i used simple INT, in the array location, now it need array.
How can i change the values of INT into a type that i can put inside the array ?
thx for help, and here the code.
the class with the method:
private ArrayList<String> locationCells;
private int numOfHits = 0;
public void setLocationCells(ArrayList<String> locationCells)
{
this.locationCells = locationCells;
}
public String checkYourself(String guess) {
// creazione stringa miss
String result = "miss";
int index = locationCells.indexOf(guess);
if (index >= 0) {
locationCells.remove(index);
}
if (locationCells.isEmpty()) {
result = "kill";
numOfHits ++;
}else
result = "hit";
System.out.println(result);
return result;
}
and here the MAIN:
public static void main(String[] args) {
java.util.Random randomGenerator = new java.util.Random();
Scanner scan = new Scanner(System.in);
StartUpCorretta dot = new StartUpCorretta();
int manyGuesses = 0;
boolean isAlive = true;
int randomNumbers = randomGenerator.nextInt(5) +1;
int randomNumb = (int) (Math.random() * 5);
ArrayList<String> location = {randomNumbers,randomNumbers +1,randomNumbers +2};
dot.setLocationCells(location);
while(isAlive) {
System.out.println("enter a number");
int guess = scan.nextInt();
String result = dot.checkYourself(guess);
manyGuesses ++ ;
if (result.equals("kill")) {
isAlive = false;
System.out.println("you took" + " " + manyGuesses + " " + "guesses");
}
}
}
Seems, you are taking your input from console as int from this statement
int guess = scan.nextInt();
So, my answer is based on your input data type.
Please, changed your arraylist generic type String to Integer
And Secondly, this is not how you can initialized the arraylist
ArrayList<String> location = {randomNumbers,randomNumbers +1,randomNumbers +2};
Correct way to create collection using new operator like this
ArrayList<Integer> location = new ArrayList<>();
and correct way to add element into arraylist like this
location.add(randomNumbers);
location.add(randomNumbers+1);
location.add(randomNumbers+2);
Hope, it will work for you.
Here I am trying to find the max and min number entered into the array so I'm using a min and a max method(not declared yet) but I'm not quite sure how to access my array in these methods as the array userArray and array are not in the scope of the method and can't be accessed. can someone help me out?
package edu.skidmore.cs106.lab07.problem1;
import java.util.Scanner;
public class numberArray {
//Method to take user input
public int[] getUserData() {
System.out.println("How many numbers will you enter?");
Scanner keyboard = new Scanner(System.in);
// Create variable to store user's desired number of values
int totalNumbers = keyboard.nextInt();
// Declare and initialze an array
int[] userArray = new int[totalNumbers];
// Create a loop to ask for values from the user
// Within the loop, store user input in the array
for (int x = 0; x < totalNumbers; ++x) {
System.out.println("Enter number " + x);
int userInput = keyboard.nextInt();
userArray[x] = userInput;
}
return userArray;
}
public int minNumber() {
for (int y : array)
}
public static void main(String[] args) {
numberArray instance = new numberArray();
int array[] = instance.getUserData();
for (int element: array){
System.out.println(element);
}
}
}
public int minNumber(int[] userDataArray) {
// use userDataArray here
}
...
public static void main(String[] args) {
numberArray instance = new numberArray();
int[] userDataArray = instance.getUserData();
int min = instance.minNumber(userDataArray); // pass userDataArray as argument
}
I'm trying to create a program that asks for 10 integers and puts those numbers into an array of negative, positive, and odd arrays. In the end, I want the program to print out 3 rows of numbers that separate the users 10 numbers into "odd", "even", and negative". When I run this I get "error: 'void' type not allowed here"
import java.util.Scanner;
public class ArrayPractice{
private static void showArray(int[] nums)
{
for (int i=0; i<nums.length;i++)
{
if(nums[i]!=0)
{
System.out.println(nums[i] + " ");
}
}
}
public static void main(String[] args){
int evenArray[] = new int[10];
int evenCount = 0;
int oddArray[] = new int[10];
int oddCount = 0;
int negArray[] = new int[10];
int negCount = 0;
Scanner input = new Scanner(System.in);
for(int i = 0; i<10; i++)
{
System.out.println("Number? " + (i + 1));
int answer = input.nextInt();
if(answer<0)
{
negArray[negCount++] = answer;
}
else
{
if (answer % 2 == 0)
{
evenArray[evenCount++] = answer;
}
else
{
oddArray[oddCount++] = answer;
}
}
}
System.out.println(showArray(evenArray));
System.out.println(showArray(oddArray));
System.out.println(showArray(negArray));
}
}
showArray is void, it does not return anything. And, on inspection, it prints in the method itself. So this
System.out.println(showArray(evenArray));
System.out.println(showArray(oddArray));
System.out.println(showArray(negArray));
should just be
showArray(evenArray);
showArray(oddArray);
showArray(negArray);
Hi there I am super new to coding and I keep getting a '.class' error when I try to run the code below. What am I missing?
import java.util.Scanner;
import java.util.Scanner;
public class PeopleWeights {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
userWeight = new int[5];
int i = 0;
userWeight[0] = 0;
userWeight[1] = 5;
userWeight[2] = 6;
userWeight[3] = 7;
userWeight[4] = 9;
System.out.println("Enter weight 1: ");
userWeight = scnr.nextInt[];
return;
}
}
This is the problem
userWeight = scnr.nextInt[];
Solve this by:
userWeight[0] = scnr.nextInt(); //If you intended to change the first weight
OR
userWeight[1] = scnr.nextInt(); //If you intended to change the value of userWeight at index 1 (ie. the second userWeight)
Should work
PS: As a precaution do not import the Scanner class twice. Doing it once would be enough
I understood your intension and below are two possible ways to implement your thought:
I see you are giving values manually as userWeight[0]=0;
If you wanna give manually I suggest not to go with scanner as below.
public static void main(String[] args) {
int[] userWeight={0, 5, 6,7,9};
System.out.println("Weights are" +userWeight);//as you are giving values.
}
If your intension is to get values at run time or from user, please follow below approach
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("This is runtime and you need to enter input");
int[] userWeight = new int[5];
for (int i= 0; i < userWeight.length; i++) {
userWeight[i] = sc.nextInt();
System.out.println(userWeight[i]);
}
}
PS:
I seen you are using util package import for two times, instead you may import all at once as import java.util.*;
Also you are trying to return. Please note for void methods its not need for return values. VOID excepts nothing in return.
First of all do not import packages more than once, now lets go to the actual "bugs".
Here:
import java.util.Scanner;
public class PeopleWeights {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int userWeight[] = new int[5];//You need to declare the type
//of a variable, in this case its int name[]
//because its an array of ints
int i = 0;
userWeight[0] = 0;
userWeight[1] = 5;
userWeight[2] = 6;
userWeight[3] = 7;
userWeight[4] = 9;
System.out.println("Enter weight 1: ");
userWeight[0] = scnr.nextInt();//I belive that you wanted to change
// the first element of the array here.
//Also nextInt() is a method you can't use nextInt[]
//since it doesn't exists
//return; You dont need it, because the method is void, thus it doesnt have to return anything.
}
}
Also instead of this:
userWeight[0] = 0;
userWeight[1] = 5;
userWeight[2] = 6;
userWeight[3] = 7;
userWeight[4] = 9;
you can do this during the declaration of an array:
int userWeight[] = {0,5,6,7,9};//instantiate it with 5 integers
I'm trying to convert my single dimensional array into a multidimensional array. Convert the existing Interest Calculator Batch application from several single dimensional arrays
into 1 multi-dimensional array. Use the following data type: double[][] values;
Hint: The maximum number of data sets(5) will be your row and the each data array (from the original InterestCalculatorBatch)(7)will be a column.
2.All data will be contained within a
single multi-dimensional array.
3. Modify the sortBySimple and displayInterest methods to accept a single multi-dimensional array instead of multiple single dimensional arrays
I fixed the displayInterest to accept a single multi dimensional array. I am just confused if I have the sortBySimple set up correctly and when the program calculates the interest if I need to fix those or keep them as is. Thank you for the help.
import java.util.Scanner;
public class InterestCalculatorBatchMDA {
public static void main(String[] args )
{
int cnt = 0;
double[][] arrPrincipalAmt = new double[5][7];
double[][] arrInterestRate = new double[5][7];
double[][] arrTerm = new double[5][7];
double[][] arrSimple = new double[5][7];
double[][] arrCompoundMonthly = new double[5][7];
double[][] arrCompoundDaily = new double[5][7];
double[][] arrCompoundWeekly = new double[5][7];
do{
arrPrincipalAmt[cnt] = getPrincipalAmount(1);
arrInterestRate[cnt] = getInterestRate(1);
arrTerm[cnt] = getTerm(1);
arrSimple[cnt] = round(calculateSimpleInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt], arrTerm[cnt]),5);
arrCompoundMonthly[cnt] = round(calculateCompoundInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt],arrTerm[cnt] ,12.0 ),5);
arrCompoundWeekly[cnt] = round(calculateCompoundInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt], arrTerm[cnt], 52.0 ),5);
arrCompoundDaily[cnt] = round(calculateCompoundInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt], arrTerm[cnt], 365.0 ),5);
cnt++;
}while (cnt < 5 && askYesNo("Enter another set of data (Yes/No):"));
displayInterest(arrPrincipalAmt,arrInterestRate,arrTerm,arrSimple,arrCompoundMonthly,arrCompoundWeekly,arrCompoundDaily,cnt);
sortBySimple(arrPrincipalAmt,arrInterestRate,arrTerm,arrSimple,arrCompoundMonthly,arrCompoundWeekly,arrCompoundDaily,cnt);
displayInterest(arrPrincipalAmt,arrInterestRate,arrTerm,arrSimple,arrCompoundMonthly,arrCompoundWeekly,arrCompoundDaily,cnt);
}
/** Round **/
public static double round(double numb1, double numb2) {
double round = ((double) Math.round(numb1*(Math.pow(10, numb2)))/(Math.pow(10, numb2)));;
return round;
}
/** Calculate Simple **/
public static double calculateSimpleInterest(double numb1, double numb2, double numb3) {
double calculateSimpleInterest = ((numb1)*(numb2/100.0)*(numb3/12.0));
return calculateSimpleInterest;
}
/** Calculate Compounded Daily **/
public static double calculateCompoundInterest(double numb1, double numb2, double numb3, double numb4 ) {
double calculateCompoundInterest = (numb1*Math.pow((1.0+((numb2/100.0)/numb4)),(numb4*(numb3/12.0))))-numb1;
return calculateCompoundInterest;
}
/** Get principal amount **/
public static double getPrincipalAmount(double numb1) {
Scanner input = new Scanner(System.in);
double numb2 = 1;
do{System.out.print("Enter Loan Amount: ");
numb2 = input.nextDouble();
if(numb2 > 0);
else{
System.out.println("Data Error: Loan amount must be greater than zero. You entered " +numb2);
}
}while (numb2 < 0);
return numb2;
}
/** Get interest rate **/
public static double getInterestRate(double numb1) {
Scanner input = new Scanner(System.in);
double numb2=1;
do{System.out.print("Enter Yearly Interest Rate (1 to 100 percent): ");
numb2 = input.nextDouble();
double getInterestRate = 0;
if (numb2 >= 0 && numb2 <= 100)
getInterestRate = numb2;
else{
System.out.println("Data Error: Interest rate must be greater than or equal to zero and less than or equal to 100. You entered " +numb2);
}
}while (numb2 <= 0 || numb2 >= 100);
return numb2;
}
/** Get term **/
public static double getTerm(double numb1) {
Scanner input = new Scanner(System.in);
double numb2=1;
do{System.out.print("Enter the Term (in months): ");
numb2 = input.nextInt();
double getTerm = 0;
if (numb2 > 0)
getTerm = numb2;
else{
System.out.println("Data Error: Loan amount must be greater than zero. You entered " +numb2);
}
}while (numb2 <= 0);
return numb2;
}
/** Sort by simple interest **/
public static void sortBySimple(double[][] arrPrincipalAmt ,double[][] arrInterestRate, double[][] arrTerm, double[][] arrSimple, double[][] arrCompoundMonthly, double[][] arrCompoundWeekly, double[][] arrCompoundDaily, double count){
for(int i = 0;i<count;i++)
{
for(int j=i+1; j<count;j++)
{
if(arrSimple[i][j] < arrSimple[i][j])
{
double temp = arrSimple[i][j];
arrSimple[i][j] = arrSimple[i][j];
arrSimple[i][j] = temp;
double temp1 = arrPrincipalAmt[i][j];
arrPrincipalAmt[i][j] = arrPrincipalAmt[i][j];
arrPrincipalAmt[i][j] = temp1;
double temp2 = arrInterestRate[i][j];
arrInterestRate[i][j] = arrInterestRate[i][j];
arrInterestRate[i][j] = temp2;
double temp3 = arrTerm[i][j];
arrTerm[i][j] = arrTerm[i][j];
arrTerm[i][j] = temp3;
double temp4 = arrSimple[i][j];
arrSimple[i][j] = arrSimple[i][j];
arrSimple[i][j] = temp4;
double temp5 = arrCompoundMonthly[i][j];
arrCompoundMonthly[i][j] = arrCompoundMonthly[i][j];
arrCompoundMonthly[i][j] = temp5;
double temp6 = arrCompoundDaily[i][j];
arrCompoundDaily[i][j] = arrCompoundDaily[i][j];
arrCompoundDaily[i][j] = temp6;
double temp7 = arrCompoundWeekly[i][j];
arrCompoundWeekly[i][j] = arrCompoundWeekly[i][j];
arrCompoundWeekly[i][j] = temp7;
}
}
}
}
/** Display Interest **/
public static void displayInterest(double[][] amt ,double[][] interest, double[][] term, double[][] simple, double[][] monthly, double[][] weekly, double[][] arrCompoundDaily, int count){
int i=0;
System.out.println("[Line #] [Principal Amount] [Interest Rate] [Term] [Simple Interest] [Compound Monthly] [Compound Weekly] [Compound Daily]");
do{
System.out.print((i+1)+" ");
System.out.print(amt[i][i]+" ");
System.out.print(+interest[i][i]+" ");
System.out.print(+ term[i][i]+" ");
System.out.print(+simple[i][i]+" ");
System.out.print(+monthly[i][i]+" ");
System.out.print(+weekly[i][i]+" ");
System.out.println(+arrCompoundDaily[i][i]);
i++;
}while(i < count);
}
/**ask yes or no **/
public static boolean askYesNo(String question) {
Scanner input = new Scanner(System.in);
String enteredText;
boolean isAnswerValid;
do{
isAnswerValid = false;
System.out.println(question);
enteredText = input.nextLine();
if (enteredText.length() > 0)
{
enteredText = enteredText.toUpperCase();
if(enteredText.equals("YES") || enteredText.equals("Y") || enteredText.equals("NO") || enteredText.equals("N"))
{
isAnswerValid = true;
}
}
if(isAnswerValid == false)
{
System.out.println("Please enter 'Yes' or 'No'?");
}
} while(isAnswerValid == false);
if(enteredText.equals("YES") || enteredText.equals("Y"))
{
return true;
}
return false;
}
}
Your code looks like an attempt to write C in Java. Java is an OO language, and you will have much more success if you design and write your programs in to make use of that. Data structures that are "smeared" across multiple arrays like that are fundamentally awkward to deal with.
The first thing you need to do to remedy this is to create a class that represents an entry in the arrays.
Trying to fix the program while retaining the current "smeared" data structure design is ... to be blunt ... a waste of time.