int not initialized compilation error [duplicate] - java

This question already has answers here:
Java: Why am I required to initialize a primitive local variable?
(5 answers)
Closed 9 years ago.
Ok, so I searched for a similar thread like this one but couldn't find the answer I'm looking for.
I'm trying to program something that generates random numbers and turns them into a question.
I'm not even sure it's even properly written but I'm having a compilation error.
"Variable answer1 might not have been initialized"
Here's the code :
import java.util.Scanner;
import java.util.Random;
public class random{
public static void main (String [] args){
System.out.println("Random number generated");
Random obj= new Random();
Scanner scan = new Scanner(System.in);
int answer1;
int rgen= obj.nextInt(100);
int rgen1= obj.nextInt(1000);
System.out.println(rgen + " + " + rgen1 + " = ? ");
scan.nextInt();
if (answer1 == rgen + rgen1)
System.out.println("Correct");
else
System.out.println("Wrong");
}
}

Define answer1 to be some initial value.
int answer1 = 0;
You can't use a variable that you haven't initialized, which is what you attempt to do with if (answer1 == rgen + rgen1).
It'd likely be that you want to read in the next integer, so you could also do this:
int answer1 = scan.nextInt();
Or, before you hit your if block, you can change the statement of scan to put the value into the variable instead:
answer1 = scan.nextInt();

You probably want this:
answer1 = scan.nextInt();
Otherwise, the call of scan.nextInt() reads and discards the value, while answer1 remains uninitialized. You should probably combine initialization with declaration, too: remove
int answer1;
and replace it with
int answer1 = scan.nextInt();
on the line where you read the int from the Scanner.

The code
int answer1;
reserves space on the stack for that variable. It doesn't put anything in there, so whatever is in that variable is whatever was in memory at that location at the time.
It hasn't been initialized because you haven't put anything in there yet. The warning will go away if you change it to
int answer1 = 0;
But honestly I'm not sure what your code is trying to do.

Related

How to start debugging this Java code? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm very new at programming, and I have no idea why this doesn't work.
What I want to do is like:
pmmd = plus - minus - multi.. - divide..
code:
import java.util.Scanner;
class MyCalculator{
public static void main(String args[]){
Scanner ScanN = new Scanner(System.in);
Scanner ScanT = new Scanner(System.in);
Double fnum, snum, answer;
Boolean pmmd;
System.out.println("Enter First Number");
fnum = ScanN.nextDouble();
System.out.println("Enter Second Number");
snum = ScanN.nextDouble();
System.out.println("Enter minus, plus, multi or divide");
pmmd = ScanT.nextBoolean();
Object plus = "+";
Object minus = "-";
Object multi = "*";
if(pmmd.equals(plus)) {
answer = fnum + snum;
}
else if(pmmd.equals(minus)) {
answer = fnum - snum;
}
else if(pmmd.equals(multi)) {
answer = fnum * snum;
}
else {
answer = fnum / snum;
}
System.out.println(answer);
}
}
Here:
System.out.println("Enter minus, plus, multi or divide");
pmmd = ScanT.nextBoolean();
A boolean is about true/false. But "+" is a string, not a true/false value!
You want a String, like
String operator = scanT.next();
Beyond that, there are many other things that don't make much sense in your code. For example this:
Object plus = "+";
should be
String plus = "+";
for example.
And you would rather do something like:
switch(operatorGivenByUser) {
case "+":
...
instead of putting up such an if/else chain.
I know, it seems hard, but the point is: when you write code, be sure to understand what each line is doing. If you don't understand it - read about it.
Beyond that, there are more subtle problems like:
Bad naming: "pmmd" says nothing about the intent of that variable. I renamed it to "operator"; or "operatorGivenByUser" - which gives you at least a hint what the content of that variable is about!
Bad naming (II): you should read about java coding style conventions. Variable names start lowercase; so it is scanT ; not ScanT. (where again; that name actually says nothing, just call it scanner for example)
Insufficient checking: when doing divisions, make sure that the denominator is not 0.

The constructor Scanner is undefined [duplicate]

This question already has answers here:
How to get the user input in Java?
(29 answers)
Closed 5 years ago.
I'm very very new to Java. I got stuck in this error where it states:
The constructor Scanner() is undefined
and
The method nextInt(int) in the type Scanner is not applicable for the arguments (InputStream).
import java.util.Random;
import java.util.Scanner;
public class NumberGenerator
{
public static void main(String[] args)
{
Scanner input = new Scanner();
Random randomNumber = new Random();
System.out.println("Please enter the maximum value: ");
int maxValue = input.nextInt(System.in);
for (int counter = 1; counter <= 1; counter++)
{
int number = randomNumber.nextInt(maxValue);
System.out.println("Your random number is: " + number);
}
}
}
As you may be able to see, I'm very new and I really appreciate your help.
You need to specify what the scanner is supposed to read from. I assume you want it to read from the console, in which case you would want to write:
Scanner input = new Scanner(System.in);
Also, nextInt() does not take parameters. Change it to:
int maxValue = input.nextInt();
The answer to both of your problems is here https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html. The Scanner class has only constructors that require arguments and the nextInt method either takes no argument or an int.
Advice: Googling " javadoc" is a good habit.

Cannot invoke nextint() on the primitive type int

So I'm learning Java and maybe he didn't explain well enough how scanners work and their limits or maybe I'm looking over something silly... but I'm getting an error on answer = answer.nextInt(); I don't get this error for bomb but it's used pretty much the same way...
Code:
Scanner yesNo = new Scanner(System.in);
Scanner input = new Scanner(System.in);
//
//answer auto set to no. goes to first if, then asks for confirmation,
// then check answer again and go to if, else if or else.
//
int answer = 0;
while (answer != 1)
if (answer == 0) {
System.out.println("In how many seconds should we detonate?");
int bomb = input.nextInt();
//this number will be used later in else if (answer == 1)
System.out.println("Is " + bomb + " seconds correct? 1 for yes, 0 for no");
answer = answer.nextInt();
//error above "Cannot invoke nextint() on the primitive type int"
//Need this to grab a number from user to assign a new value to answer
What do? Thanks.
First of all, you have one Scanner instance with paramether System.in, so it will "record" your keyboard (I assume that yesNo scanner is not used). Then, you have a int variable called "answer" which you assign zero value. Finally you have another variable called "bomb" where you will get your requested value.
As I see in your answers' comments, you're wrong in one thing: "input.nextInt()" is an int value. When you use input.nextInt(), you're sending it a message that says "Hey bro, give me the first int that this stupid human have pressed", but you aren't doing anything more. "input" is only a scanner (as it class name says) that records keystrokes.
So in fact, when you do "input.nextInt()" you'll get an int value, and when you do "bomb = input.nextInt()" or "answer = input.nextInt()" the only thing that you're doing is giving "bomb" or "answer" that int value.
int is a primitive value. It is not an Object and it has no methods.
probably you want to do
answer = input.nextInt();
nextInt() is a function that is part of the object type Scanner. In order to call .nextInt() you must have an object of type Scanner.
So the line "int bomb = input.nextInt();" works fine, since "input" is an object of class Scanner. That function runs and it returns another object, an integer, from input, which is stored in int bomb.
The line "answer = answer.nextInt();" fails to compile because "answer" is an object of class integer. integer does NOT have a function called nextInt().
The appropriate line is "answer = input.nextInt();" using your Scanner object to return another integer to store in "answer".
int answer = 0;
answer = answer.nextInt();
You are calling nextInt() on an int. You need to call it on the scanner:
answer = input.nextInt();

Java String automatically assigned null value [duplicate]

This question already has answers here:
Java calculator not executing if-statement [duplicate]
(3 answers)
Closed 9 years ago.
In the code below, in the first iteration of the first for loop, boxes[a] is automatically assigned a null value.
The remainder of the iterations are fine (user input is accepted). Only the first has the issue where a null value is automatically assigned.
Does anyone know why this may be? Thank you.
package testing;
import java.util.Scanner;
public class Testing {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
int boxNumber;
boxNumber = in.nextInt();
String[] boxes = new String[boxNumber];
System.out.println(boxNumber);
for(int a=0; a <= boxes.length - 1; a++){
boxes[a] = in.nextLine();
System.out.println(boxes[a]);
}
int packageNumber;
packageNumber = in2.nextInt();
String[] packages = new String[packageNumber];
System.out.println(packageNumber);
for(int n=0; n <= packageNumber - 1; n++){
packages[n] = in.nextLine();
System.out.println(packages[n]);
}
}
}
The scenario fitting the description of what occurs is when you type in a number on the first line, then the rest of the lines are strings for the boxes.
But the nextInt() method doesn't advance past the first newline character, so the first time you call nextLine(), it matches on the rest of the line until the first newline character, "" ( not null).
After the call to nextInt(), insert a call to newLine() before the for loop to bypass the first newline character.
String firstNewLine = in.nextLine();
for(int a=0; a <= boxes.length - 1; a++){
when you did hit enter after entring the first number you also have and empty line that's why nextLine() return empty string, you can use this boxNumber = in2.nextInt(); instead but I would suggest to think of another way, normally you don't need two Scanner instances

How to use the value of variable from if/else tree as value of variable for a while loop afterwards

Here is my program code as I have it written so far. It's saying I haven't initialized answer. I want to use the value of answer after the if/else tree executes to convert the number into asterisks.
import java.io.*;
import java.util.*;
public class Project5 {
public static void main(String[] args){
System.out.println("Please enter a formula of this form:operator,operand,operand(ex. add,2,2):");
// wanted to change things but was not sure how far I was allowed to go so I used commas instead of spaces
//was trying to split with a delimiter but kept getting an error [Ljava.lang.String;#55e83f9
Scanner input = new Scanner(System.in);
String formula = input.nextLine();
System.out.println(formula);
String oper = formula.substring(0,3);
System.out.println(oper);
String fnum = formula.substring(4,5);
System.out.println(fnum);
String snum = formula.substring(6,7);
System.out.println(snum);
double freal = Integer.parseInt(fnum);
System.out.println(freal);
double sreal = Integer.parseInt(snum);
double answer;
if (oper.equalsIgnoreCase("add") == true){
answer = freal+sreal;
System.out.println(answer);
}
else if(oper.equalsIgnoreCase("subtract") == true){
answer = freal-sreal;
System.out.println(answer);
}
else if(oper.equalsIgnoreCase("multiply") == true){
answer = freal*sreal;
System.out.println(answer);
}
else if(oper.equalsIgnoreCase("divide") == true){
answer = freal/sreal;
System.out.println(answer);
}
else
System.out.println("not valid.");
while(answer > 0){
System.out.print("*");
answer--;
}
}}
Because in the final else branch, you don't assign a value to answer. If that is the tree that's executed, then when you get to the while loop, it will be undefined. You can fix this by initially initializing answer to some value or by making sure every branch of the if/else tree assigns answer a value.
Edit To address your question, change
double answer;
To
double answer = 0.0;
That will fix the problem.
The wording of the error you are getting is a good start in working out what the problem is:
Project5.java:41: variable answer might not have been initialized
So you should initialize the variable answer
Edit: To be even clearer, change the line that says double answer; to double answer = 0.0; thereby initializing the answer variable. That is what the compiler is complaining about and is the only change you need to make in order for the code to compile and execute. By the way, you will have more errors to deal with after this because although you are allowing the operator to be 3 characters, you are trying to compare this with a longer word in some cases. So add works but subtract does not.
I think the only thing is that you have to initialize answer: double answer = 0.0;

Categories

Resources