Initializing an int variable before if statement - java

When compiling i get an Error stating that my variable has not been initialized.
Code :
int number;
if (dotted==true)
{
if (input >= 1 && input <= 21)
{
number = 1;
System.out.print("True");
}
if (input >= 22 && input <= 40)
{
number = 2;
System.out.print("False");
}
if (input >= 41 && input <= 63)
{
number = 3;
System.out.print("False");
}
if (input >= 64 && input <= 82)
{
number = 4;
System.out.print("True");
}
}
else
{
if (input >= 2 && input <= 22)
{
number = 1;
System.out.print("True");
}
if (input >= 23 && input <= 41)
{
number = 2;
System.out.print("False");
}
if (input >= 42 && input <= 64)
{
number = 3;
System.out.print("False");
}
if (input >= 65 && input <= 83)
{
number = 4;
System.out.print("True");
}
}
System.out.print(number); // number is not initialized?
Why is number not initialized?
I put int number = 0;
But then when i print, no matter the value of input it stays at 0?
Love how people downvote this. A student new to java with a question gets downvoted. Nice site

You need to put int number = 0 because you can't be sure whether the IF statement is executed or not. That's a precaution for your code.
Also, if you think about it, if it keeps being 0, it means you're actually not entering into the IF statement.
Try to put that and check if the dotted variable is actually TRUE or not.
Check also your variable input, because it is the one that changes your number variable.

Why is number not initialized?
Simply, because if none of the if statements are executed then the number variable will never get initialised. Hence the variable will not have a value and that's why you get the following error:
When compiling i get an Error stating that my variable has not been
initialized.
Also, remember local variables must be initialized before the method exits.
with that in mind, you must at least give the variable below a default value:
int number = 0;
I put int number = 0; But then when I print, no matter the value of
input it stays at 0?
if that's the case then it means you're never entering into the if statement. So, you might have to consider your if statement expressions again.

Related

How to define 00-90 when I have charAt each of it

What I need to do is write a program that makes the first character (which is charAt(0) )and the second character (which is charAt(1) ) to become a value that not exceeding 90 which is (0 ~ 90) , but I also have to define them as an independent digit , because my program will make it to invalid if it is other than a digit.
So for an example it will become invalid if I type in 91
and it will valid if I type in number between 0~90
but I have no idea how to do this...
if(Character.isDigit(loop1.charAt(0))&&
Character.isDigit(loop1.charAt(1)))
I have tried this ,but not working
if(Character.isDigit(loop1.charAt(0)) &&
Character.isDigit(loop1.charAt(1)) &&
((loop1 >= 0)&&(loop1 <= 90)))
also this one but this is not working( I have no idea what I'm doing)
if(Character.isDigit(loop1.charAt(0)) &&
(((int)loop1.charAt(0)) >= 0) && <=9
Character.isDigit(loop1.charAt(1)) &&
((int)loop1.charAt(1)) <= 9)
Please help me... thanks a million !
Assuming I understand your question, parse loop1 and test the values using a simple if check, like
int t = Integer.parseInt(loop1);
if (t < 0 || t > 90) {
System.out.println("Value outside accepted range.");
} else {
System.out.println("Value valid.");
}
If I am getting this right you want to convert the first two characters of a string into a number and check is that number bigger than 90. Also you want the digits to be stored in different variables(?). If so this code should do it:
int digit1 = loop1.charAt(0) - '0';
int digit2 = loop1.charAt(1) - '0';
int number = digit1 * 10 + digit2;
if ( number <= 90 && number >= 0 )
System.out.println("Input is good");
else
System.out.println("Input is bad");

reading from a file wont read the first value Java

So i Have this code going on, I need it to open a file, and scan the two integers in the file, then I need it to store the two numbers. The numbers are restricted to between 1 and 10 for the first number and between 1 and 39 for the second number. I have a valueCounter to make sure that the correct number gets stored in the correct variable. For some reason, the code always returns
"Your Initial Fib is out of range, eneter # between 1-10"
Which would be appropriate if the first number was greater than 10 or less than 1, but regardless of what i change the first number to, the code returns the same line. The only time it wont return that line is when i change the 2nd number to to be between 1 and 10. So I can conclude that the code is skipping the first number, but i cant figure out why. Any being of higher intelligence that can help?
private static File inFile = null;
private static PrintWriter outFile = null;
private static int startValue;
private static int lengthValue;
public static void main(String[] args) throws IOException
{
inFile = new File( inFileName);
Scanner in = new Scanner (inFile);
outFile = new PrintWriter (outFileName);
int valueCounter = 1;
while (in.hasNextInt())
{
int value = in.nextInt();
if ( value <= 39 && value >= 1 && valueCounter == 2)
{
lengthValue = value;
valueCounter ++;
}
if ( value > 39 || value < 1 && valueCounter == 2)
{
System.out.println("You are asking for too many Fib, eneter # between 1-39");
in.close();
System.exit(1);
}
if ( value <= 10 && value >= 1 && valueCounter == 1)
{
startValue = value;
valueCounter ++;
}
if ( value > 10 || value < 1 && valueCounter == 1)
{
System.out.println("Your Initial Fib is out of range, eneter # between 1-10");
in.close();
System.exit(1);
}
}
}
It is because of operator precedence, the && is evaluated before the ||. This makes the following expression
if ( value > 10 || value < 1 && valueCounter == 1)
evaluated to true the second round, because first value < 1 && valuecounter == 1 is evaluated, which is false. Next, value > 10 is evaluated, which is true. Or-ing both results in true, and the body executes. Use parentheses to control the order of evaluation.
if ( value > 10 || value < 1 && valueCounter == 1)
Seems to be always true and since its a normal outer "if" at the end of code, its always being called. overthink your "if" and its appearance

Supposed variable cannot be resolved as variable?

I'm doing a basic Java tutorial and below is the question.
Write a method that prints the numbers from 1 to 100. But for multiples of three print ÒFizzÓ instead of the number,and for the multiples of five print ÒBuzzÓ. For numbers which are multiples of both three and five print ÒFizzBuzzÓ."
My code is below
public static void fizzBuzz(){
for(int i = 0; i < 101; i= i +1 )
System.out.println(i);
if (i%3 == 0){
System.out.println("ÒFizzÓ");
}else if (i % 5 == 0){
System.out.println("ÒBuzzÓ");
}else if (i % 15 == 0){
System.out.println("ÒFizzBuzzÓ");
}
}
Eclipse tells me that "i" cannot be resolved as a variable. This is confusing to me as I thought I already defined "i" as an integer in my for loop? Thanks for taking the time to solve this newbie question :)
Add braces or your loop body ends after the first statement. Also, for your approach you need to test 15 first because it's a multiple of 3 and 5
for(int i = 0; i < 101; i++) { // <-- i++ is short for i = i + 1
System.out.println(i);
if (i % 15 == 0) {
System.out.println("ÒFizzBuzzÓ");
} else if (i % 5 == 0) {
System.out.println("ÒBuzzÓ");
} else if (i % 3 == 0) {
System.out.println("ÒFizzÓ");
}
}
I know a funny story about Apple who lost a few million dollars because a developer updated a code with an if block but... the if statement had only one instruction and no curly brackets and he did not see it. Thus, the code he was willing to add when the condition was met were actually ALWAYS executed.
In your case, you won't lose money but you surely did the same mistake :
for(int i = 0; i < 101; i= i +1 ) {
System.out.println(i);
if (i % 15 == 0){
System.out.println("ÒFizzBuzzÓ");
} else if (i%3 == 0){
System.out.println("ÒFizzÓ");
} else if (i % 5 == 0){
System.out.println("ÒBuzzÓ");
}
}
When Java says something cannot be resolved as a variable, it is usually been used outside the scope it was declared or it was not declared at all.In your case, your braceless for-loop is causing the problem.

Why I am getting an error to initialize letter and how do I fix it?

public static char determineGrade(float grade)
{
char letter;
if(grade>=90 && grade<=100)
{
letter='A';
}
else if(grade>=80 && grade<=89)
{
letter='B';
}
else if(grade>=70 && grade<=79)
{
letter='C';
}
else if(grade>=60 && grade<=79)
{
letter='D';
}
else if(grade<=59)
{
letter='F';
}
return letter;
}
The program keeps telling me to initialize letter but I do not understand why I need to. Thank you.
Why I am getting an error to initialize letter and how do I fix it?
The problem is that it is possible to reach the return statement without a value having been assigned to letter. (This happens when grade is greater than 100.0. While that might not make sense in the context of your application, the Java compiler cannot know that.)
People have suggested returning a "default" value. I think that is wrong, unless the API spec defines a default value. (And, IMO, it is bad API design to do that.)
I think that a better approach is to throw an exception (for example IllegalArgumentException) if the argument provided makes no sense.
public static char determineGrade(float grade) {
if (grade >= 90 && grade <= 100) {
return 'A';
} else if (grade >= 80 && grade <= 89) {
return 'B';
} else if (grade >= 70 && grade <= 79) {
return 'C';
} else if (grade >= 60 && grade <= 79) {
return 'D';
} else if (grade >= 0 && grade <= 59) {
return 'F';
} else {
throw new IllegalArgumentException("grade is out of range: " + grade);
}
}
The other design issue here is whether it is appropriate to use floating point numbers to represent grades. There is a risk that the computation that calculates the grades gives values that are a tiny bit "off" due to rounding error; i.e. 89.999998 instead of 90.0. If you are going to use a floating point type here, you need to use threshold comparisons rather than simple >= and <= against an integer value.
The problem is :
else if(grade<=59)
{
letter='F';
}
Should be
else
{
letter='F';
}
Because you have a series of if condition, so the compiler cannot know that whether a condition will be true in run time. So either you need to declare a default value for letter or the last else should not have any condition.
For grade over 100, there should be some check to handle this.
if grade over 100 is not acceptable, an exception should be thrown at the beginning of the method (as rule of thumb):
if(grade > 100){
throw new IllegalArgumentException("Invalid input"):
}
char letter simply declares a variable of type char. Initialising means assigning it an initial value, before the variable is acted upon elsewhere in the program.
In your case, if grade is not in any of the ranges that you explicitly check for, letter needs a default value that your method can return. Since this is a local variable in your method, compiler will not assign the standard default value for char, as mentioned in this excerpt from the documentation:
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
That is why you need to explicitly initialise it.
Try this,
public static char determineGrade(float grade) {
char letter = 0;
if (grade >= 90 && grade <= 100) {
letter = 'A';
} else if (grade >= 80 && grade <= 89) {
letter = 'B';
} else if (grade >= 70 && grade <= 79) {
letter = 'C';
} else if (grade >= 60 && grade <= 79) {
letter = 'D';
} else if (grade <= 59) {
letter = 'F';
}
return letter;
}
there is a situation where all if statements are not executing (when number >100 ). Then letter variable doesn't have a value.To prevent that the letter variable should be initialized with a default value.
Because the char is only given values in if statements the method does not know if it will ever be given a value (it assumes there is a chance that none of if statements will have a true condition) and therefore you are requested to give an initial value.
Another way around it would be by turning the last else if statement to just an else because it covers all if the remaining possibilities anyway.

In java, How would I check input validation for an array used to input grades (can't be negative, can't be over 100)

So far I've tried to create a while loop that only kicks out if the entered array value is a "correct" one (between 0 and 100). Wich means that the loop should repeat if the value entered is a negative number or something random like a char.
My code so far only works if all grades entered are incorrect. If I enter a 0, 100, and -2 it still goes through, even though -2 should cause the loop to repeat. What do I need to modify to only allow values that are between 0 and 100 to be entered into the array?
Code so far:
//Input validation for grades
int g = 0;
while(g >= 0)
{
System.out.print("Please Enter the Students' Grades: ");
for (int c = 0; c < studentGrades.length; c++)
{
studentGrades[c] = input2.nextInt();
if (studentGrades[c] >= 0 && studentGrades[c] <= 100)
{
g = -1;
}
}
}
In this code snippet:
studentGrades[c] >= 0 && studentGrades[c] <= 100
... you are saying that if the entered grade is greater than or equal to 0 and it is less than or equal to 100, set g to -1 (and exit the loop).
So essentially, every time a valid grade is entered, your loop will exit. You've done the opposite of what you wanted. Try adding a ! before your condition to negate it.
This should do
outer:
while(g >= 0) {
System.out.print("Please Enter the Students' Grades: ");
for (int c = 0; c < studentGrades.length; c++) {
studentGrades[c] = input2.nextInt();
System.out.println(" input is "+studentGrades[c]);
if (studentGrades[c] <= 0 || studentGrades[c] >= 100) {
break outer;
}
}
}
Put a check before you add the next into the array. If it's out of bounds, ask for another value.
You need to flip the logic around, currently your g flag starts as "invalid" (meaning that if g doesn't change, the loop continues), and when you find a valid grade you mark g as valid.
Instead, at the top of the while loop set g to -1, and then set it back to 0 if any of the grades provided are invalid, for example:
int g = 0;
while(g >= 0) {
g = -1;
System.out.print("Please Enter the Students' Grades: ");
for (int c = 0; c < studentGrades.length; c++) {
studentGrades[c] = input2.nextInt();
if (studentGrades[c] < 0 || studentGrades[c] > 100) {
g = 0;
}
}
}
I think this what you are trying to achieve (also you can enhnace it)
int[] values = new int[5]; //modify this according to your size
int index = 0;
do {
int value;
do {
System.out.println("Enter value " + (index + 1) + ": ");
value = input.nextInt();
} while (value < 0 || value > 100); //make sure each value is valid
values[index++] = value; //add value to the array
} while(index < values.length); //make sure you get all the values
If for loop is not required then I think it looks better that way.
Move your while loop inside the for loop, because I guess you want to validate your input grade for each index: -
And your condition should be g < 0. Also, you have used reverse condition in your if. You were setting g = -1 for correct input. You need to change your condition in if.
for (int c = 0; c < studentGrades.length; c++) {
g = -1; // Set to invalid to get your while run first time.
while(g < 0) {
System.out.print("Please Enter the Students' Grades: ");
studentGrades[c] = input2.nextInt();
// Check invalid grade -> negative or more than 100
if (studentGrades[c] < 0 || studentGrades[c] > 100) {
g = -1;
} else {
// Break while if correct grade has been entered. Continue with next index
break;
}
}
}
This code looks like it will loop until it gets studentGrades.length values, no matter what, and if the while loop repeats, it will repeat forever because g is not reinitialized.
I assume this must be a homework problem, so I'll leave the actual coding to fix the bug to you as an exercise.

Categories

Resources