This is my code in java. There is a problem at System.out.println(averager(A)); . Java said that the Local variable A may not have been initialized.
import java.util.Scanner;
public class Averager {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("How many numbers do you want to average?(2-4 only");
int x;
int[] A;
x = input.nextInt();
int Array4[]={input.nextInt(),input.nextInt(),input.nextInt(),input.nextInt()};
int Array3[]={input.nextInt(),input.nextInt(),input.nextInt()};
int Array2[]={input.nextInt(),input.nextInt()};
if (x=='2'){
A =Array2;
}
else if (x=='3'){
A = Array3;
}
else if (x=='4'){
A= Array4;
}
else{
System.out.println("Error!");
}
System.out.println(averager(A)); // Error
}
public static int averager(int...numbers){
int total=0;
for(int x:numbers){
total+=x;
}
return total/numbers.length;
}
}
Look at your code and consider what happens if x is not '2', '3', or '4'. What is A as of the
System.out.println(averager(A));
line?
Right! You've never given it a value. That's what the compiler is warning you about.
Arrays in java can be initialized = null because if the code doesn't enter an if statements A is never set. Also if by chance you already know the dimensions of the array you can initialize it like this:
int[] A = new int[numberofelements];
you can change your code as
int x = input.nextInt();
int[] A= new int[x];
Your code is wrong.
It reads 9 (4 + 3 + 2) numbers always from STDIN (in Array4 to Array2 part).
What you want to do probably is
int x = input.nextInt();
int[] A = new int[x];
for ( int i = 0; i < x; ++i ) A[i] = input.nextInt();
But if you want to solve only "Local variable A may not have been initialized." warning, return (end the program) after printing the error
else {
System.out.println("Error!");
return;
}
Change: int[] A = null;
Change : int x to int x = 0;. You need to initialize variables in java.
Related
This question already has answers here:
Variable might not have been initialized error
(12 answers)
Closed last year.
When I type this code,
import java.util.*;
public class Example{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("Input an integer : ");
int num = input.nextInt();
int y;
if(num>100){
y=200;
}
if(num<100){
y=200;
}
if(num==100){
y=200;
}
System.out.println(y);
}
}
There is an error saying "variable y might not have been initialized." Why?
This error occurs when we are trying to use a local variable without initializing it. ( accessing it in the print statement)
In your example, you have only written the if statement and compiler will not be able to detect it. To help the compiler, you can either use , the if else block which covers all the cases and it convinces the compiler or you can initialize it with value 0.
int y;
if(num>100){
y=200;
}
else if(num<100){
y=200;
}
else{
y=200;
}
System.out.println(y);
In your code, you are declaring y as a "not initialized" variable int y;. At that point, y is not defined. If you change it to int y = 0; it will be fine.
The compiler knows that an if block may not be executed. So if the variable is only initialized inside the if block, it may not be initialized at all. And that is exactly the error message.
Scanner input = new Scanner(System.in);
System.out.print("Input an integer: ");
final int LIMIT = 100; // less magic numbers
int input = input.nextInt();
int result = 0;
if(input > LIMIT){
result = 200;
}
if(input < LIMIT){
result = 200;
}
if(input == LIMIT){
result = 200;
}
System.out.println(result);
I modified your code a bit to solve the "not initialized" part. Also added a final variable for the 100 value since it is considered a good practice to name every value (no magic numbers).
You can also reduce code on this by changing the if statements a bit:
final int LIMIT = 100;
if (input == LIMIT || input < LIMIT || input > LIMIT) {
result = 200;
}
import java.util.*;
class Example{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
System.out.print("Input an integer : ");
int num=input.nextInt();
int y=0;
if(num>100){
y=200;
}
if(num<100){
y=200;
}
if(num==100){
y=200;
}
System.out.println(y);
}
}
Here is my program which is supposed to create an array and initialize prime numbers to it. The prime numbers should then be printed but the program just keeps running.
import java.util.*;
public class primes
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
int[] prime = new int[x];
int div=2,hold=2;
int c=0;
while (prime[x-1]==0)
{
for(int a=2; div>a;a++)
{
if(div>a && div%a==0)
a=div;
else if(div==(a-1))
hold=div;
}
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
div++;
}
for(int f =0; f<x;f++)
System.out.print(" "+prime[f]+" ");
}
}
I tried changing my loops but I just don't know whats wrong
Like the others mentioned your logic is not right, try something like:
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
List<Integer> primes = getPrimes(x);
Integer[] primeArray = primes.toArray(new Integer[primes.size()]);
for(int i :primes.toArray(primeArray)){ // you could just use for(int i :primes){ if you don't need array
System.out.print(i + " ");
}
}
private static List<Integer> getPrimes(int upperLimit) {
ArrayList primes = new ArrayList();
for (int i = 2; i < upperLimit; i++) {
boolean isPrime = true;
// Is it prime?
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime)
primes.add(i);
}
return primes;
}
The above will print out up to the numbers entered so if you type 5 it will print out 2 3 but not 5.
The following is an other example with Java 8, this one will print as many prime numbers based on the input, if you input 5 you will get 2 3 5 7 11
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
long[] prime = primes(x).toArray();
Arrays.stream(prime).forEach(value -> System.out.print(value + " " ));
}
private static LongStream primes(long max) {
return LongStream.iterate(2, i -> i + 1)
.filter(PrimeNumber::isPrime)
.limit(max);
}
private static boolean isPrime(long x) {
return LongStream.rangeClosed(2, (long)(Math.sqrt(x)))
.allMatch(n -> x % n != 0);
}
Your code is wrong. First correct it, And i think you want to store prime numbers coming in range of 1 to N where N is user provided number. Use arrayList (growable) to store it.
It will keep on running because you have this: while (prime[x-1]==0). Where x is an input from the user. Say 5 for instance, then prime[5-1] initially is going to contain a 0 always, and you are running your while loop on this condition which is always going to turn true, thus never ending. Also, your prime number generation logic is not right!
I ran your code in debugger mode and I found the problem.
I tested your program with x=5.
At the end of the first while loop iteration you have :
prime[0] = 2
div = 3
hold = 2
c = 1
And here's the problem :
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
This part won't ever be reached anymore because :
div is never decrement, so it will always be superior to 2.
hold is
equal to prime[c-1], and never change value.
So prime will always stick to be : 2 0 0 0 0, and your while loop will never end.
I found what was wrong and rewrote the code, it works now. The program asks the user for the number primes they want to see and it prints them after storing them in a basic integer array.
import java.util.*;
public class Prime
{
public static void main(String [] args)
{
Scanner scan= new Scanner(System.in);
int i=0, hold=2, d=2;
boolean flag = true;
System.out.println("Enter the number of primes.");
int[] prime= new int[scan.nextInt()];
for(;flag;){
for(int a=2;d>a;a++){
if(d==(a)||d%a==0){
break;
}
if((d-1)==a){
hold = d;
}
}
d++;
if(hold==2 || hold!=prime[i-1]){
prime[i] = hold;
i++;
}
if(i==prime.length)
flag= false;
}
for(int x=0;x<prime.length;x++)
System.out.print(prime[x]+" ");
System.out.println("");
}
}
After getting an answer from this link, I tried to make a method that returns the oldest member from a list of arrays that contains name and age of each person.
So in the main method I added those lines:
char X;
X = stat.next().charAt(0);
if(X=='a')
System.out.println(X);
oldest(nameStr, ages);
if(X=='b')
System.out.println(X);
//Scanner newAge = new Scanner(System.in);
//int ageToSearchFor = newAge.nextInt();
//maxAge(ageToSearchFor);
if(X=='c')
System.out.println(X);
And I created the following method oldest():
public static void oldest(String[] str, int[] ageInt)
{
int maxAge=0;
String maxName="";
for(int i=1; i<ageInt.length;i++)
{
int temporary=ageInt[0];
if(ageInt[i]>temporary)
{
maxAge = ageInt[i];
maxName = str[i];
}
}
System.out.println("The listener "+maxName+ " is the oldest with an age "+maxAge);
}
But I am getting the same result:
the listener is the oldest with an age of 0
Any help is appreciated.
EDIT
I changed the if into switch case and still the same problem:
System.out.println("Please choose a, b or C:");
Scanner stat = new Scanner(System.in);
char X;
X = stat.next().charAt(0);
switch(X){
case 'a':
//System.out.println(X);
oldest(nameStr, ages);
break;
case 'b':
System.out.println(X);
//Scanner newAge = new Scanner(System.in);
//int ageToSearchFor = newAge.nextInt();
//maxAge(ageToSearchFor);
break;
case 'c':
System.out.println(X);
break;
}
You aren't doing the correct comparison. See corrected, commented code below.
public static void oldest(String[] str, int[] ageInt)
{
int maxAge=0;
String maxName="";
for(int i=0; i<ageInt.length;i++) // start from zero
{
if(ageInt[i]>maxAge) // compare to the current max
{
maxAge = ageInt[i];
maxName = str[i];
}
}
System.out.println("The listener "+maxName+ " is the oldest with an age "+maxAge);
}
Change
if(X=='a')
System.out.println(X);
oldest(nameStr, ages);
to
if(X=='a') {
System.out.println(X);
oldest(nameStr, ages);
}
and please stick to surround if with brackets every time.
In the event the first value of ageInt[] is the greatest value, then maxAge and maxName will never be changed, since those contents are only set in the event the value of ageInt[i] is greater than the temporary value. So instead of initializing your variables via the following.
int maxAge=0;
String maxName="";
Initialize them as such:
int maxAge = ageInt[0];
String maxName = str[0];
Furthermore, ensure that you are declaring
int temporary=ageInt[0];
Outside of the for loop, otherwise you will always be setting temporary to ageInt[0], which will produce an issue if say
ageInt[0] < ageInt[1], and
ageInt[0]< ageInt[2] < ageInt[1]
As your maxAge will be set to ageInt[2] on the its iteration through the for loop. A better way to write this to avoid such an issue would be to check against your current maxAge instead of temporary.
for(int i=1; i<ageInt.length;i++){
if(ageInt[i]>maxAge){
maxAge = ageInt[i];
maxName = str[i];
}
}
I'm trying to compare two Array Ints.
This is what I have so far:
package array;
import java.util.Scanner;
import java.util.Arrays;
public class Array {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int [] lottery_number = new int[49];
int i;
int a = 0;
for (i=0; i<lottery_number.length; i++){
lottery_number[i]=i+1;
}
System.out.println("Please insert 6 numbers");
int [] Number = new int [6];
Number[0] = input.nextInt();
Number[1] = input.nextInt();
Number[2] = input.nextInt();
Number[3] = input.nextInt();
Number[4] = input.nextInt();
Number[5] = input.nextInt();
}
}
I'm trying to compare the user input to certain Lottery_number array.
I point out that I'm not sure of what you are asking, but it makes no sense to compare the lottery numbers array (all natural numbers from 1 to 50) with the player picks array (6 random numbers from 1 to 50.
Using the static method
Arrays.equals(int[] array1, int[] array2)
will return whether the arguments are equals (same number of elements, same value) but eventually this is not the case. Sorry if I have completely misunderstood what you asked.
numberInCommon is a variable that says how many numbers the arrays have in common. I hope this is what you're looking for. You have to import java.util.Arrays
List lotteryNumbers = Arrays.asList(lottery_numbers);
int numbersInCommon = 0;
for(int i : Number){
if(lotteryNumbers.contains(new Integer(i)))
numbersInCommon++;
}
EDIT: You'll also need change
int [] lottery_number = new int[49]; to
Integer [] lottery_number = new Integer[49];
So here's what i'm trying to do. Have user input numbers, store them in an array, then print all those numbers out on one line. I must use a method/function as well. I think i have done quite well so far, it shows no errors in eclipse. What im stuck on is storing their input into an array. i want them to keep inputting numbers one at a time until they're satisifed and type 'quit'. i just havent read about how to store things in an array despite looking around, particularly storing more than one thing, progressively. here is my code so far, and thank you in advance for any help!
import java.util.Scanner;
public class intarray {
public static void main(String[] args) {
System.out.println("Enter a number then hit enter. You may then enter another number or end by typing quit.");
String x;
Scanner input = new Scanner(System.in);
while (true) {
x=input.next();
if (x.equalsIgnoreCase("quit")) {break;}
if (x.equals(null)) throw new Error("You entered nothing. Try again.");
int stringLength = x.trim().length();
if (stringLength == 0) throw new Error("Seems you only entered spaces. Try again.");
isNum(x);
int goingintoarray = Integer.parseInt(x);
int array[];
}
}
public static String isNum(String t) {
int user=Integer.parseInt(t);
String convertback = Integer.toString(user);
return convertback;
}
}
Since you don't know how many elements there will be an array is a bad idea since you will have to resize it quite often as new elements appear (copying arrays is expensive!) or instantiate a large enough array at the beginning (which is a waste and still doesn't protect you in 100% from having to resize it eventually).
Instead using Java's List (preferably LinkedList) sounds like a good idea since you can add elements dynamically without resizing the data structure.
List<Integer> numbers = new LinkedList<>();
while(true) {
// something
numbers.add(goingintoarray);
// something
}
Be careful of other implementations - for instance ArrayList uses an array (d'uh ;-) ) to store the elements so you would have the same problem but the resizing part would be taken care of for you by the implementation.
#Edit: by convention classes in Java are written using CamelCase starting with an uppercase letter.
ArrayList<Integer> inputs = new ArrayList<Integer>();
while (true) {
Scanner input = new Scanner(System.in);
x=input.next();
if (x.equalsIgnoreCase("quit")) {break;}
if (x.equals(null)) throw new Error("You entered nothing. Try again.");
int stringLength = x.trim().length();
if (stringLength == 0) throw new Error("Seems you only entered spaces. Try again.");
inputs.add(Integer.parseInt(x));
}
You don't want the isNum method since it gives same exception here if it gets wrong input for x.
import java.util.Scanner;
public class intarray {
public static int initSize = 5;
public static void main(String[] args) {
System.out.println("Enter a number then hit enter. You may then enter another number or end by typing quit.");
int array[] = new int[initSize];
int pos = 0;
int maxSize = initSize;
String x = null;
Scanner input = new Scanner(System.in);
while (true) {
x = input.next();
if (x.equalsIgnoreCase("quit")) {
break;
}
//input empty string, java io can filter. So , x impossible "null" or null.
//if (x.equals(null))
// throw new Error("You entered nothing. Try again.");
int stringLength = x.trim().length();
if (stringLength == 0)
throw new Error("Seems you only entered spaces. Try again.");
Integer numX = isNum(x);
// if the array is full, extend it
if(pos == maxSize){
int[] newArray = new int[2 * maxSize];
System.arraycopy(array, 0, newArray, 0, maxSize);
array = newArray;
maxSize = array.length;
}
if(null == numX)
System.out.println(x + " isn't a number."); //choose notify or throw error
else
array[pos++] = numX;
}
printArray(array, pos);
}
public static Integer isNum(String t) {
try {
return Integer.parseInt(t);
} catch (NumberFormatException e) {
return null;
}
}
public static void printArray(int[] array, int pos) {
if(null == array || array.length == 0 || pos <= 0)
return ;
for(int i = 0 ; i < pos; i++)
System.out.print(array[i] + " ");
}
}