+ 2

can any one tell how to remove this error??

import java.util.*; import java.lang.*; class sample { public static void main(String args[]) { int x,y,z; Scanner sc=new Scanner(System.in); System.out.print("\n\tenter 1st value:"); boolean b=sc.hasNextInt(); if(b==true) { x=sc.nextInt(); System.out.print("\n\tX:"+x); } else { do { System.out.print("\n\tinvalid value:"); System.out.print("\n\tenter 1st value:"); x=sc.nextInt(); }while(b=false); } Scanner sc=new Scanner(System.in); System.out.print("\n\tenter 2nd value:"); boolean b=sc.hasNextInt(); if(b==true) { y=sc.nextInt(); System.out.print("\n\tY:"+y); } else { do { System.out.print("\n\tinvalid value:"); System.out.print("\n\tenter 1st value:"); x=sc.nextInt(); }while(b=false); } z=x+y; System.out.print("\n\tRESULT:"+z); } }

16th Dec 2017, 4:15 PM
Keerthana Vema
Keerthana Vema - avatar
5 Answers
+ 4
change: while (b=false); to: while (b == false); OR while (!b); Remember = is not a comparison operator. *Keep in mind this will become an infinite loop since b is never set back to true* You also created 2 local variables with the same name after your first loop. Remove the 2nd Scanner: 'Scanner sc = new Scanner (System.in);' and Change the name of the 2nd boolean variable 'b' OR do not create a new boolean variable. change: boolean b = sc.hasNextInt(); to: b = sc.hasNextInt(); or boolean hasNext = sc.hasNextInt(); // and modify everytime b was accessed to use this name instead
16th Dec 2017, 4:46 PM
Rrestoring faith
Rrestoring faith - avatar
+ 4
Ah, that would be because if the 2nd if statement: if (b == true) is false, then y is never given a value when it is accessed with z = x + y; (2nd last piece of code). I'm not sure what you were trying to do but to fix the error you can set y by default to be equal to 0. change: int x, y, z; to: int x, y = 0, z;
17th Dec 2017, 4:13 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
Maybe tell the output (error message)?
16th Dec 2017, 4:43 PM
Lucien
Lucien - avatar
+ 1
@Rrestoring faith tq for d answer.....but I'm also getting error like "variable y might not have been initialised"
17th Dec 2017, 8:13 AM
Keerthana Vema
Keerthana Vema - avatar
+ 1
@Restoring faith....tqq it worked well šŸ˜€šŸ˜€
17th Dec 2017, 4:26 PM
Keerthana Vema
Keerthana Vema - avatar