0% found this document useful (0 votes)
33 views11 pages

Debug

Uploaded by

Mr. Anonymous
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
33 views11 pages

Debug

Uploaded by

Mr. Anonymous
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 11
7129723, 10:40 PM Debugging Java Code. emchstcrs® ‘ello have an placement test fo crest data system company a my college 50 they sk question on debug the java code like {wll ie you example. gt the unit digit as ‘output: finch edo > int main) {sm mum, LD; pit” Enter a number"¢S89),seanf("4, dem); LD ~ num 10; pnt im The Last Digit of «Given Number “sl Ya, nam, LD); eur | please genre his type of more vanity question fe practise Somorn Sure, I ean provide you with some Java code snippets that conan bugs for youto debug These wil help you practice and improve your programming sil, Here ae 8 few example 1. Fix the sya enor: java Diop ots | public class SyntaxEeroréxanple { public static vold main(String(] args) nt num = 4589; int (0'= aun % 20; // Use the modulus operator to get the last digit Systen.out-println("The Last Digit of a Given Number "+ num +" =" + LD); 2. Incortet variable nializton: java Copy ode | public class IncorrectInitializationtxanple ( public static void nain(String{] args) < int num = 4589; Ant (0 = 0; // Initialize Lo too wile (num'> 8) { Lo = num % 1; // Use the modulus operator to get the last digit nus /= 10; // Divice by 20 to move to the next digit y Systen.out.printin("The Last Digit of 2 Given Number 4589 +10) 3. Lopieal enor - Geting the ist digit instead of he ast digit java copy cae public class LogicatérrorExanple ( public static void main(String{] args) ( int num = 4589; nt (0 = nun; // Initialize LD to the sunber itself while (10 >= 10) ¢ LD /= 10; // Divide by 10 to get the First digit > System.out-printin("The Last Digit of a Given Number 4589 = " + 10); 4, Using Sesnner to take inp rom the wer: soue( Oeap oe] Import java.util.Scannen; public class ScannerinputExanple ( public static void main(String{] args) Scanner scanner = new Scanner(Systen. in); System.out.print("Enter 2 nunber: ")} Ant num = Seanner.nextIne()s int (0 = nun % 105 // Use the modulus operator to get Systen.out.printIn("The Last Digit of the Given Nunber "+ num + seanner.close(); +0); 5. Incotet input prompt nd variable names: sev Cae co) import java.util. Scanner; public class TnputPromptexample { public statie void nain(Stringl] args) ¢ hnpe:/cnat penal com/?madeltext-davinc-002-cender-sha wt 7129723, 10:40 PM Debugging Java Code. Scanner scanner = new Scanner(Systen. in); System.out.print ("Enter a nunber: "); Aint number = seanner.nextint(); // Use a meaningful variable name nt Iastbigit = number X 19; // Use the modulus operator to get the last digit Systen.out-printIn("The Last Digit of the Given Munber " + nunber + "= "+ lastDigit); seanner.close(); y Fee foe to debug and orrest these ode snippets og the desired outputs Happy coding and goo lic with your placement tes! ChatOPE please generate more varity questions Somer. ‘Ofcourse! Here are some more Java code snippets wit bugs for yout practice ébugeiog: 1, Swapping two numbers witout using a temporary vsisble: java Oop cae public class SwapNunbers ( public static void main(string{] args) ( int a= 55 int b = 20; 11 Tocorrect swapping without using 2 temporary variable aeatbs bra by arab) syston.out.printin("a = "a4", b=" +b); 2. Binding he factorial ofa number seve Eicopy eae] public class Factorialexanple { public static vold main(Stringl] args) ¢ int num = 53 lint factorial = @; // Incorrect initialization of factorial for (int 4 = 2) 4 <= nunj det) ( factorial *= 4} // incorrect calculation, shovld be factorial + y System.out.printin(“Factorial of * + num + "= * + factortal); 3. Checking ifa number is prime: eve oy oes | public class Peinecheck { public static vold main(steing(] args) ¢ int num = 173, boolean isprine = true; for (int 4 = 2; 4 ce mum / 2; S44) ¢ AF (oun $i == 0) { isPrine = false; break; // Missing break statenent y Af isPrine) ¢ System.out.printIn(nun +" 1s a prine nunber, yelse { Systen.out-paintIn(nun +" is not 2 prime number"); y hnpe:/cnat penal com/?madeltext-davinc-002-cender-sha at 7129723, 10:40 PM Debugging Java Code. y 4. Reversing a sting evel Bop ets] public class Stringkeverse ( public static Void nain(String{] args) { String input = “Hello, Worldl”; String reversed =" for (ant 4 = anput.2engtn() = a; 4 >= 9; 4--) ( reversed += Input{i]; // using incorrect syntax to access characters in a string y Systen.out.printin(*Reversed string: " + reversed); 5. Generating Fbonaec seis: java Eicon oes] public class Fibonacciseries { public static void aain(steingl] args) ¢ int n= 10; int firstTerm = 6; int secondiers = 45 Systen.out.prine("Fibonacci Series: * + firstTena + °, * + secondTenn); for (int 1 = 3; 1 <> ny tse) ¢ int nextTerm = firstTere + secondTerm; Systen.out.peint(", "+ nextTere); FirstTern = secondienn; Secondterm = nextTerm y Feel foe to debug and correct these code snippets toga the expected outputs. Happy coding and best of luck wit your placement test! Chat please generate more Samar Sure, hee ate Some mote Java cde snippets with bugs for you to practice debugsing: 1. Finding the maximum element in an ra: save Ocoee public class Findlaxélenent { public static voia masn(String{] args) ( ‘int{) arr = (10, 5, 20, 8, 5); Snt-rax = are(0}; for (int 42 15 1 ce anr.engths 14+) { // Tneorrect Loop coneition Af (arefi} > max) ¢ ine = arti] > y Systen.out.printin("The maxinun elerent is: " + 93x); y y 2. Chock fa suing is palindome: java Ocopj cae] public class PaLindronecheck ( public static void nain(String{] args) String input = “Level”; boolean 1sPalindrone =’ trues hnpe:/cnat penal com/?madeltext-davinc-002-cender-sha ant 7129723, 10:40 PM Debugging Java Code. for (int 4 = 0 1 < Anput.Length() / 25 f4+) Af (Anput.charat(s) |= input.charA€(input.Length() ~ i)) { // Incorrect index for the second character comparison {sPalindrone = fa1se: breaks y Af (isPalindrome) ‘ysten.out-psintln(input + * is a palindrome"); yelse ( System.out.paintln(input + As not a palindrone."); y y y 2. Calcul the sum of gts ina number seve oy cots | public class Sunofigits public static vold sain(steing(] args) { write (nun int die rus /= 10; Sun 40 digit; y System.out.println("Sum of digits: * + sun); 4. Coun the mimber af occurrences of character inating: java Diop cts] public class characteroccurrences { public static void main(string{] args) ¢ String input = "hello"; char target = Ant count = ©; for (int 1 = 0; 1 <= Anput-length(); 14) { // Incorrect Loop condition AF (Anput.charat(s) == target) countess y y systen.out.printin(“Occurrences of * 4 target + ~: "+ count); 5. Remove duplicates fom an aay java Bcopy eas] import java.util.Arrays; public class Renoveduplicates { public statie void nain(Steingl] args) ¢ int{] arr =, 2,2, 3, 4 4) 533 Ant{] Uniqueane =" new ineTare-Lengeh]: int count = 13 Uuniquearr(@] = arre]; for (int {= 45 4 ¢ arectengeh; is) AF (are[i} t= arrld = 4) ( ‘uniqueArr(eount} = arr[]; countess // Missing Increeent of count variable y luniquearr = Arrays.copyof(uniquearr, count); Systen.out.printin(-Array with duplicates removed: " + Arrays. tostring(uniqueser)); > Feo fre to debug and ores thee cade nipets og the expected outputs. Keep practicing lo enhance your coving skills! Good lack with your placement et npe:/cnat openal.com/?madeltext-davinc-002-cender-ha ant 7129723, 10:40 PM Debugging Java Code. “Chat plese more Schnorr Cetinly! Here are some moe Java code snippets with bugs for you to practice debugging 1. Check i years leap year java OCopy cots] public class Leapvearcheck { public static void aain(steingl] args) ¢ int year = 2024; boolean isteapvear = false; AF (year % 4 == 0) ( AF (year % 10 I= @ || year % 480 == ©) { // Incorrect condition for checking leap year ‘steapvear = true; > x AF (Asteapear) ¢ Systen.our-println(year +" is a leap year."); pele ( Systen.out.printIn(year +" is not a leap year"); y 2. Find the second largest element nan aay: ave Eicon cas Import java.util Arrays; public class SecondLargestelenent { public static vold aain(Stringl] args) ¢ int{] arr = (22, 5, 28, 8, 15); Arrays.sort(are); // Sorting the array in ascending order int secondLargest = arrarr-length - 2]; // Incorrect index to get the second largest Systom.out.printin("The second largest elenent is: " + secondLargest); 2. Print numbers fom 1 to 10: Sava Copy nds | public class PrintNunbers { public static void aain(steingl] args) { for (int £2 1; 1 <= 18; 1+) {-// Incorrect loop condition, should be 1 <= 18 instead of 1-- System.out-peint(i + *")s y 4, Caleta the power ofa number java Oop ade] public class Powercalculation { public static void sain(Stringl] args) ¢ int base = 2; nt exponent = 3; int result = @; for (int $= 25 4 <= exponents 64) ¢ result *= base; // Incorrect calculation, should be result * y base Systen.out.printIn(base +" raised to the power of " + exponent +" =" + result); y hnpe:/cnat penal com/?madeltext-davinc-002-cender-sha sit 7129723, 10:40 PM Debugging Java Code. 5. Implement abasic clelator: java O&opycode) Inport java.util. Seamer; public class sasiccalculator ( public static vold main(Steing{] args) { Scanner scanner = new Scanner(Systen. in); System.out -prine ("Enter first number: ")? nt num = Seanner.nextIst(); Systen.out.prins("Enter second nusber: "); nt mun2 = scanner. nextint(); systen.out.print ("enter an operator (+, -) *) /): "5 char operator = scanner.next() .enarkt(@); Ant result; switch (operator) { result = punt + num2s breaks result = umd ~ num2s breaks result = und * nun2s break; case "7" result = unt / numa breaks default: Systen.out.printIn("Invalid operator."); seanner,close() y Systen.out-printin("Result: "+ result); scanner.close(); y Foo foe to debug and cores thse code snippets to got the expected outputs. Happy coding and good luck with your placement test! Came plese more “chacrr* ‘Cerny! Here are some ation Java code snippets with bags fr you to practice debugging: 1. Implement a method to reverse an amy seve Diop cots] import java.util.Arrays; public class ReverseArray { public static void main(String{] args) int() arr = GQ, 2,3, 4, 55 reverseareay(are); System.out -printIn("Reversed Array: * + Arrays. toSteing(arr)); > public static void reversearray(int[] arr) { ant left = 8; nt right = arelength; // Incorrect initialization of the right pointer while (left < right) ( int tenp = arr(ieft]; arr(left] = are(right]; // Incorrect index for night pointer arr(night] = tenp;, Lereees right--; // Missing decrenent of right pointer hnpe:/cnat penal com/?madeltext-davinc-002-cender-sha ant 7129723, 10:40 PM Debugging Java Code. y y y 2. Implement a method o check ifa number is even or od java Bop ots | Import java.util. Scanner public class Evenaddcheck { public static void aain(steingl] args) { Scanner scanner = new Scanner(Systen. dn) systen.out-print("enter 3 unber: "); nt nun = seanner.nextine()3 AF (1sEven(nus)) ¢ Systen.out.println(nun + yeise ¢ Systen.out.println(nun + ~ is an odé number"); x Seanner.close(): As an even nunber."); y public static boolean istven(int nun) { return nun % 2 == 0} 2. Implement a method to find the factorial of «number recursively: ave Eicopy cae import java.util Scanner public class Recunsiveractorial { public static void aain(stringl] args) ¢ ‘Scanner scanner = new Scanner(Systen.dn)s systen.out-print ("enter 3 sunber: "); int nun = seanner.nextine()3 int factorial = findFactorial(sun); System.out.printIn("Factorial of ” + num + "= * « factorial); seanner.close() y public static int findFactorial(int nun) ¢ iF (num == 8) ¢ ‘return 25 pele ( return nun * findFactorial(nun - 1); // Incorrect recursive call d y 4. implement a method to prin a Pascals Tingle: java copy eas] Import java.util. Scanner; public class PascalsTriangle ( public static void nain(Steingl] args) ¢ Scanner scanner = new Scanner(Syster. tn); Systen.out-print("Enter the nunber of rows: Ant rows = Scanner nextInt(); for (int 4 = 8; 4 < rows; 164) ¢ For (int j= 0; J <= 4) jee) ( Systen.out print (calculatePascalvalue(i, 3) + “Ys 7 Incorrect method call ) Systen.out.printla(); y Seanner.close(): y public static int caleulatePascalvalue(int row, int col) { if (col == 8 || col == row) { peet hnpe:/cnat penal com/?madeltext-davinc-002-cender-sha am 7129723, 10:40 PM Debugging Java Code. return calculatePascalvalue(row - 2, col - 1) + colculatePascalvalue(row - 1, col); // Incorrect recursive call x Fee fee to debug and corres these code snippets ogo the expected outputs. Keep practicing to enhance your coding skills! Good luck with your placement est! “Chae plese generate more wih variety of questions Ceteinly! Here are some moe lava coe nippets with diverse bugs for you to practice debug: |. Implement a method t Find the GC (Greatest Common Divison) af wo mambers: evel copy eats | Import java.util. scanners public class 6co { public static void main(string{] args) Scanner scanner = new Scanner(Syster.in); Systen.out.print ("Enter first number: "); Ant nut = scanner mextInt(); Systen.out print ("Enter second number: Ant num2 = Seanner.nextEN¢(); Aint ged = Finacco(numa, sun2)s systen.out-printin("GCD of * + numt +" and" + nun +" =" + ged); seanner.close() y public static int findcco(int a, int 6) ( while (b {= 8) ( dint temp = 65 b= ab; /7 Incorrect calculation 3 = temp: y return a5 2. Implement a method occult the sm of ll ven numbers fom 1a given number evel Ocopy ote] import java.util.Scanner public class sunofevenNunbers { public static void main(Steingl] args) Scanner scanner = new Scanner (Syst Systen.out.print ("enter a unber: ")3 Ant m= scanner. nextine();, in) nt sum = FindsunofEventuabers(n); Systen.out-printin("Sum of ever sunbers fron 1 to" + n+" seanner.close(); + sun); d public static int findsunofEverNunbers (int n) ¢ int sum = 03 for (int 4 0; 1 ce ny de4) ( Af (12 == 0) ¢ ‘sun 4= 15 // Incorrect condition to check for even nunbers > x return sun; 2. plement method to check if given ring i palindrome: save Oop oae) hnpe:/cnat penal com/?madeltext-davinc-002-cender-sha ant 7129723, 10:40 PM Debugging Java Code. import java,util.Scanner public class PaLindronecheck ( public static vold main(steingl] args) { Scanner scanner = new Scanner(S)sti Systen.out.print ("Enter a string: String input ~ scanner. nextLine(); in) Af (isPalindromeCinput)) Systen.aut.println("The string is = palindrene.”); yeise ( System.out.psintln(“The string is not a palindroxe."); y Scanner.close(): y public static boolean isPalindrone(steing str) { int left = 8; int right = strlengeh() = 25 while (Left <= right) { AF (stracharAt(efe) f= stevcharat(rdgnt)) ( return false; > Letters right--; // Missing decrenent of right pointer y return trues 4, Implement a method t find he sum of clement in 32D array pablte Sete cioraokrray { publse sene wold skistetg(] ares) ¢ elitl seers = C oe weg: (7, 8, 9} D Ant sum = Anasunof20&eray(eate); System.out.printin("Sun of elements in the 20 array: " + sun); > public static int Féndsumof2Darray(int{]{] are) ( nt sum = 0; for (int 4 = 0; i < are.tength; ist) for (int j'= 0; J < arr[i]-length; i+) { // Incorrect loop variable, should be J instead of £ sun += arr(S(I}3 > x Fretuen sums 5. Implement a mtd o print the Fibonacci series up toa given umber: java Bion ots] import java.util. Scanner; public class Fibonacciseries ( public static void main(String{] args) Scanner scanner = new Scanner(Systen. in): Systen.out.print ("Enter 2 nunber: ")) Ant n= Seanner-nextIne();, Systen.out.print ("Fibonacci Series: "); for (int i= 8; 4 <= nj iss) Systen.out print (calculatetibonacci(i) + 5 M1 Incorrect wethod call x scanner.close(); y public static int calculateFibonaccs(int n) { if (nea) hnpe:/cnat penal com/?madeltext-davinc-002-cender-sha ant 7129723, 10:40 PM Debugging Java Code. return 1; yeise ¢ Fetuon calculateFsbonacei(n ~ 1) + caleulateFibonacci(n ~ 2); // Tnconsect recursive call y y Fee foe to debug and corres these code snippets ogo the expected outputs. Keep practicing and improving your cing sls! Goodluck with you placement fest! chacrn=* plese gente more womcr ‘Ofcourse! Here are some mare Java code shippets wit bugs for yout practice debugging: |. Implement a method to check i given number it pers number java Oop oes] import java.util Scanner; public class Perfectunbercheck { public static void main(string{] args) ( ‘Scanner scanner = new Scanner(Systen. in); Syston.out.print ("Enter a unber: ")} Ant num = Seanner.nextIne(s Af (1sPerfectaumber(nua)) { Ssysten.out-printin(nun + " is a perfect nunber."); y else { Systen.out.printin(nun + As not 2 perfect nusber."); y scanner.close(); y public static boolean isPerfecttumber(int nun) { nt sum = 05 for (int 4 = 45 1 < mums S42) { Af (oun ¥ 4 == 0) { y return sun =» num; // Incorrect condition to check if the nusber is perfect 2. Implement a mathod to calvulte the factorial of «number using recursion eve Bion cots] Import java.util. scanners public class RecunsiveFactorial { public static void main(String{] args) ‘Scanner scanner ~ new Scanner(Systen.in); Systen.out.print ("Enter 2 sunber: "); Ant num = seanner.nextIne()3 Ant factorial = findFactorial (nun); Systen.out.printin("Factorial of ” + num +" = * + factortal); seanner.close(); > public static int findFactorial(int nun) ( AF (um == 8) ¢ return 2; yelse { return nun * findFactorial(nus); // Incorrect recursive call y y hnpe:/cnat penal com/?madeltext-davinc-002-cender-sha sont 7129723, 10:40 PM Debugging Java Code. 2. Implement a msthod to find the average of clement in an aay java Oops) public class AverageorArray { public static void main(String{) args) { Snt{] are = (10, 26, 30, 49, 50)3 double average = Finaaverage are); System.out.printIn(-average of elements in the array: " + average); > public static double Fincaverage(int{] arr) ( nt sum = 8; for (int £ 1 areslength; i+) ¢ arr{i]s y rretuen sum / arrvlength; // Tncorrect division, should be (dovble) sum / arr-length 4. Implement a method to coun the occurrences ofeach character ina string save Bicones] Import java.util Hashiap; import java.util.Map; public class characterOccurrences { public static void main(String{] args) { String input = "hello"; MapcCharacter, Integer> charCountMap = findCharacterdccurrences input); for (Character ¢ : charCourttap.keySet()) { Systen.out-printIn(e +” occurs” + charCountMap.get(c) + " tines y y public static MapcCharacter, Integer» findcharacterdccurrences(String str) ( MapcCharacter, Integer> charCountap = new Hashtap<>();, for (int 1 = 0; 1 <= stralength(); i+) { // Incorrect Loop condition char c= strcharat(i); charcountMap.put(c, charCountMap.getOrdeFault(c, 8) + 1); y rretuen charcounthaps 5. Implement a mod ofnd the second smallest element in an ary java Ocopy ode] Import java. util.arrays; public class SecondSnallestEloment { public static void main(string{] args) ¢ Snt{) arr = (S10, 3, 20, 8s int secondSnallest’ = findSecondSmalestElenent arr); System.out.printin(-The second smallest elenent ts: "" + secondSnallest); > public static int Findsecondseallestélesent(int{] arr) { ‘Arrays. sort(arr);, return arr[]3 // Incorrect index to get the second snallest d Fea free to debug and correct these code snippets to get the expected outputs, Keep practicing to enhance your coding skills! Good lek with your placement et hnpe:/cnat penal com/?madeltext-davinc-002-cender-sha wat

You might also like