Array - The Local Variable Average May Not Have Been Initialized

May 13, 2014

public class Apples{
public static void main (String args[]){
int array[]={21,16,86,21,3};
int sum=0;
int average;
 
[Code] .....

Eclipse: Exception in thread "main" java.lang.Error: Unresolved compilation problem:

The local variable average may not have been initialized

at Apples.main(Apples.java:11)

View Replies


ADVERTISEMENT

Local Variable Not Initialized

Jun 19, 2014

I am reading input from a file that has following information:

line 1 = numbers of integers in array,
line 2 = elements in array1,
line 3 = elements in array2.

These lines constitute a test case. There are 1000 test cases in the input file.

So basically, I read the length of arrays, populate the arrays by reading from the file.

The code is below ( I have not included reading input code):

while(test_case<1000){
if (count == 1){ //count keeps track of lines in input file
vec_length = Integer.parseInt (tokenizer.nextToken());
count++;
continue;
}
if (count == 2){ //populates array1
vector1 = new int[vec_length];
for (int i = 0; i < vector1.length; i++)
vector1[i] = Integer.parseInt (tokenizer.nextToken());
count++;
continue;
}

Array2 is populated using the same as above code. However when I use the following code:

for (int i=0; i<vec_length; i++)
temp += vector1[i]*vector2[i];

I get " local variable vector1 and vector2 have not been initialized error". But both arrays have been initialized in the if{} block. Is it because initialization was local to if block?

View Replies View Related

Are Terms Local Variable And Member Variable Comparable

Oct 27, 2014

The term "Local variable" is related to scope. That is a local variable is one which is defined in a certain block of code, and its scope is confined inside that block of code.And a "Member variable" is simple an instance variable.

I read in a discussion forum that when local variables are declared (example code below), their name reservation takes place in memory but they are not automatically initialized to anything. On the other hand, when member variables are declared, they are automatically initialized to null by default.

Java Code: public void myFunction () {
int [] myInt; // A local, member variable (because "static" keyword is not there) declared
} mh_sh_highlight_all('java');

So it seems that they are comparing local variables and member variables. While I think a member variable can also be be local in a block of code, isn't it?

View Replies View Related

Getting Error - Variable May Not Have Been Initialized

Feb 21, 2015

I know what the error means but I don't think initializing the variable will make my code work as intended so I'm having a little dilemna here... here's the code and I'll highlight the part that is said to be not initialized:

Java Code:

import java.util.Scanner;
public class ItemCost {
public static void main (String []args){
int i=1,item=1,e=1, f=1, g=1;
int items, d ;
double gst, qst, subt, Tot = 1, PriceItems ;

[Code] ....

So I'm supposed to get the following output :

Java Code:

Please input the amount of items bought 2
Please input the price of the item 1 1
Please input the price of the item 2 2
Please input the rate of GST in % 20

Please input the rate of QST in % 18 mh_sh_highlight_all('java');

HOWEVER my program doesn't seem to add input of item 1, and 2 if I initialize subt= 0 initially. It'll only take the last value inputted in the loop. By the way, the increments are counters to count the amount of errors the user might input by accident ( or whatever). Some people have been pointing it out as useless but that's the only way I found it to work.

View Replies View Related

Printing Default Value Of Int - When Is Variable Initialized

Nov 12, 2014

In the following code the print method prints the default value of int(zero) for the first time even when the variable i has been assigned a value of 4. Why?

class A1{
A1()
{
System.out.println("Inside constructor of A1()");
print();
}
void print()
{
System.out.println("A");

[Code] ....

Output:
Inside constructor of A1()
0
Inside constructor of B1()
4

View Replies View Related

Inappropriate Error - Variable Arg Might Not Have Been Initialized

Mar 31, 2014

Consider the following simple code:
 
public class Test {
      private final int arg;
      private final Runnable runnable1 = new Runnable() {
            @Override
            public void run() {
                 // No errors here, exactly as expected
                 System.out.println("ARG: " + arg);

[Code] ....
 
The java compiler (version 1.8.0-b132) produces the following error when compiling this code:

"Error:(14, 46) java: variable arg might not have been initialized"
 
Actually, I do not expect the error here.

Both declarations 'runnable1' and 'runnable2' are essentially the same: these are just Runnable objects accessing value of the 'arg' field (which is initialized in the constructor).

The only difference between the declarations is that 'runnable1' - is an old-fashion instantiation of Runnable, whereas 'runnable2' - is an instantiation of Runnable via a lambda expression.

View Replies View Related

Catch Block Error Variable Might Not Have Been Initialized

Feb 28, 2015

I want to use a try catch block, but I am not sure how to fix this problem:

int a;

try{
a = Integer.parseInt(A.getText());
}
catch (Exception e){
Output1.setText("Error");
}

//do someting with a here

The purpose of the try-catch is to catch blank input.The problem with this is that underneath the try - catch I get an error saying that the variable might not have been initialized. I know why this happens. I know I could initialize the varaible before the try - catch, but there is no default or null I can set an int as. If I initialized it as 0, the blank input will no longer be catched.how to make this problem disappear?

View Replies View Related

Morse Code Conversion - Variable Has Not Been Initialized

Aug 26, 2014

I'm making a program that can read an input of English or Morse code and return an output of Morse code or English back. The English-->Morse works fine, but not Morse-->English. I'm pretty sure my solution lies in displaying the variable 'morseWord', but no matter where I put it, I always get an error saying the variable has not been initialized. Here's what it looks like now:

import java.util.Scanner;
public class pro1
{
static final String[] alpha = {"a", "b", "c", "d", "e", "f", "g", "h", "i",
"j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
"v", "w", "x", "y", "z", " "};
static final String[] morse = {".-", "-...", "-.-/>/>.", "-..", ".", "..-.", "--.", "....", "..",
".---", "-.-/>/>", ".-..", "--", "-.", "---", ".--.", "--.-/>/>", ".-.", "...", "-", "..-",
"...-" ,".--" ,"-..-", "-.-/>/>-", "--..", " | "};

[Code] .....

View Replies View Related

The Value Of Local Variable NextDate Is Not Used

May 12, 2015

As a studyproject I'm currently writing a class the allows me to get al fun dates (like when eastern is in a given year, what day a given date has, calculate the date of tomorrow).

While working on the following method:

public String getNextDate (int day, int month, int year) {
String nextDate;
int nextDay = getNextDay(day, month, year);
int nextMonth = getNextMonth (day, month, year);
int nextYear = getNextYear (day, month, year);
return nextDate = "the day after " + month +"-" + day + "-" + year + " is " +
nextMonth + "-" + nextDay + "-" + nextYear + ".";
}

I get a notion in my lovely IDE (eclipse) reminding me I'm not using nextDate ("The value of the local variable nextDate is not used"). But I feel I really do use nextDay here. So either I'm making a coding(style) mistake giving me this notion or I should just ignore this notion.

View Replies View Related

JSP :: Can't Get Local Variable Value In Value Attribute Of Input Tag

Feb 3, 2014

Here, I have just tried out to take a value from the database and storing it into local variable then I want to have that value in the value attribute of <input> tag but somehow, I can't get it..

Here, below is my code..

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "[URL]....">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

[Code]...

View Replies View Related

Omitting Local Large Variable To Save Memory

Sep 30, 2014

I have a question regarding best practice in using local variables as my method return variable. I have a method like this:

myReturnObject getMyObject(String input) {
myReturnObject myObject = null;
try {
myObject = helperObject.someOtherMethod().getObject(input); //getObject has return type myReturnObject
} catch (Exception e) {
//log any problems
}
return myObject;
}

And I'm wondering if I rewrite like this if I'll see some performance optimization benefit:

myReturnObject getMyObject(String input) {
try {
return helperObject.someOtherMethod().getObject(input); //getObject has return type myReturnObject
} catch (Exception e) {
//log any problems
}
return null;
}

myObject can be quite large -- so I'm wondering if I can omit the myReturnObject local variable instance if it'll save some work from the garbage collector.

View Replies View Related

Printing Out Array And Average Of Array

May 2, 2014

So I'm trying to write a program that will take in 5 numbers, store them in an array and then print out the array and the average of the array. Problem is that every time I run my program I get a "ArrayIndexOutOfBoundsException: 5" error and I don't know who to fix it.

public class ConstructorHomework {
final static int size = 5;
static double[] myArray = new double[size];
public static double average;
public void printArray(){

[code]...

View Replies View Related

How To Get Average Of Strings Using Array

Apr 21, 2014

I'm trying to calculate the average of grades that a user puts in. Here is my code so far:

public static void main(String[] args) {
Scanner input = new Scanner (System.in); 
System.out.println("Please enter an array of grades seperated bt a comma.");
input.nextLine();
String arrayOfGrades = "100,50,100";
String[] grades = arrayOfGrades.split(",");
 
[Code] .....

I think I'm on the right track, the only big error I'm really getting is the line: sum += grades[i]. It's saying string can not be converted into a double.

View Replies View Related

Finding Average Of Multidimensional Array

Mar 2, 2015

public class StuTest {
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args){
int[][] testScores; // [students][tests]
String[] stuNames;

[Code] ....

The method I am having issues with is the "printStudentReport" method. I am trying to calculate the average of a randomly generated number of students and tests. For my "printTestReport" method, I have to calculate the average of the test by test number.

View Replies View Related

Number Closest To Average Sum For Given Array

Oct 19, 2014

Find the numbers which is closest to the average sum for a given array of N (1<=N<=50) of natural numbers. If there are two numbers who meet the requirement, return the smaller of the two.

For example for the array of: 1,2,3,4,5,6 the average sum is 3.5, so both 3 and 4 are the closest to that, but the program has to return 3, because it's smaller than 4.

The array can also contain duplicates. First we type the number of elements in the array, then in each line we add the numbers. Name of the class: Array

**Note**: Create a data structure array and use it.

And this is what they have given to me, I just need to type the code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Array<E> {
public static int closestNumber( ) {

[Code] .....

View Replies View Related

Array Of Numbers Not Able To Get Correct Average Value

May 26, 2015

I have the following methods:

public static int getSum(int[] data) {
int sum = 0;
for (int i = 0; i < data.length; i++) {
sum += data[i];
}
return sum;

[code]....

The input is the following arary (Its from the Junit test that fails this): [Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE].I get an average of 0.0 when it should be -0.2.

View Replies View Related

Finding Simple Moving Average With Array

Apr 8, 2014

How can I find out the simple moving average by just using the numbers stored in an array?

View Replies View Related

Print Inputted Data - Name / Score And Average Using Array

Aug 22, 2014

Conditions : Need to print all the inputted data(name,score) and the average.

import java.util.Scanner;
public class Case2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] score = new int[5];
String[] name = new String[5];
int ave = 0;

[Code] .....

View Replies View Related

Get Information From Array (Variable F)

Apr 8, 2014

I am trying to find the GCD, add, and remove the biggest and smallest fraction, however I am having trouble getting user input into the array and getting the information out of it (Variable f).

Scanner keyb = new Scanner(System.in);
Fraction[] frak = new Fraction[7];

Main_Class
try {
for (Fraction f : frak){ // for each array in frak print f;
System.out.println("Enter Numerator");
int num = keyb.nextInt();
System.out.println("Enter Denominator");
int den = keyb.nextInt();
f = new Fraction(num, den);

[Code] ....

View Replies View Related

Can User Define Array Variable?

Feb 10, 2015

I am writing a program to store books (Book class) in volumes (Volume class). Within the main class (DemoVolume) I am doing a couple different things. I want to ask the user if they are creating a new array, if yes, I was to create a new array with a variable names assigned by the user. Is this possible? The reason is I want to allow the user to be able to search their library of volumes. If no, then the user will enter the book information and I will assign it to an array unassignedVolume that will contain individual books. I would also like to create book objects that are defined with the book name, if this is possible. I'm just messing around and trying to deepen my understanding of JAVA. My main issue is how to allow the user to title the volume (array variable).

import java.util.Scanner;
public class DemoVolume {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String [] volume, unassignedVolume;
Volume volumeOne = new Volume("JAVA", 3, volume);

[Code] ......

View Replies View Related

Array List Requiring Variable Not A Value?

Dec 11, 2014

The IDE says an error of "required variable, found value". I thought you need a index value to get a item in the arraylist.

package SuperHero;
import java.util.ArrayList;
public class Driver
{
public static void main ( String args[]) {
//intallizing the supers

[Code] ....

View Replies View Related

How To Compare Integer To A String Variable Array

Apr 17, 2014

I'm trying to do something like this:

Java Code:

for (int i=1; i<2; i++);
int randomNum = rn.nextInt(range) + 1;
if (randomNum == CardList.CARD_NAME[randomNum]){
} mh_sh_highlight_all('java');

But the CARD_NAME variable is a string. I just want to compare the array to the integer.

View Replies View Related

Variables Not Have Been Initialized

Sep 23, 2014

I continuously get an error for lines 34, 36, and 37 saying that the variables may not have been initialized.

import java.util.Scanner;
import java.util.Random;
public class MathTutor {
public static void main(String[] args) {
Random r = new Random ();
Scanner input = new Scanner (System.in);
/*int min=1;
int max=10;*/
int num1,num2,operation;
int n1= r.nextInt((9+1)+1);
int n2= r.nextInt((9+1)+1);
operation= r.nextInt(3);
int correctAnswer;
int userAnswer;

[code]....

View Replies View Related

Program To Initialize And Display Variable Size Array

Aug 18, 2014

Write a program to initialize and display variable size array.

View Replies View Related

Make Int Variable That Refers To Index Number Of Array

Jan 16, 2014

I'm studying about arrays and I have some questions:

First, is there any difference between these two?

Java Code:

int x[] = new int[3];
int[] x = new int[3]; mh_sh_highlight_all('java');

It seems to me when I try them they do exactly the same, is that correct?

Second, more important question. If I want to make an int variable that refers to the index number of an array, how do I write? For example if we have

Java Code: String[] string = new String[10]; mh_sh_highlight_all('java');

And I want to have a variable "int n" that refers to an index number, so that if I set n = 5 then string[5] is selected. Note that the int n is NOT an array, but just a regular integer variable. How can I do that?

View Replies View Related

How To Use Initialized Applet Class

Apr 3, 2014

How to use initialized applet class?

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved