(1) Locate the error in the following statement and show how to fix it: try i =
ID: 3635488 • Letter: #
Question
(1) Locate the error in the following statement and show how to fix it:
try
i = Integer.parseInt (str) ;
catch (NumberFormatException e)
System.out.println ("Input was not an integer") ;
(2) Write a class method named intToString that converts an int value to string form. For example,
inToString (123) should return "123" and intToString (-123) should return "-123". Use a "do" loop
that removes digits one by one from the parameter and adds them to a string that is later returned by
the method.
(3) There is an error in the following statement, please identify the error and show how to fix it:
do
i /= 2
while (i > 10) ;
// please provide explanation for your answers
Explanation / Answer
1)ans:
import java.util.Scanner;
public class mytest{
public static void main(String[] args) {
Scanner sn=new Scanner(System.in);
String str;
System.out.println("Entered your input");
try
{
str=sn.nextLine();
int i = Integer.parseInt (str) ;
System.out.println("Entered Integer value="+i);
}
catch (NumberFormatException e){
System.out.println ("Input was not an integer") ;
}
}
}
2.
import java.util.Scanner;
public class testing{
public static void main(String[] args)
{ Scanner sn=new Scanner(System.in);
String str,str1=" ";
System.out.println("Entered your input");
str=sn.nextLine();
int i = Integer.parseInt (str) ;
do{ int i1=i%10;
i=i/10;
str1 = str1+ Integer.toString(i1);
}while(i!=0);
System.out.println("Entered Integer value="+str1);
}
}
3.ANS:
public class testing {
public static void main(String[] args) {
int i=100;// WE NEED TO INITIALIZE THE LOOP FIRST
do{
i /= 2;
System.out.println ("i="+i);
}while (i > 10) ;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.