Int to String
Para transformar um int em um string existem três formas:
String s = String.valueOf(n);
String s = Integer.toString(n);
String s = "" + n;
String to Int
Para transformar uma string em um int:
int n = Integer.parseInt(s);
================
Java Int to String
Neste exercÃcio, caso conseguisse transformar um int em um String, o console devolve "Good job". Em caso contrário, devolve "Wrong answer".
import java.util.*;
import java.security.*;
public class Solution {
public static void main(String[] args) {
DoNotTerminate.forbidExit();
try {
Scanner in = new Scanner(System.in);
int n = in .nextInt();
in.close();
//String s=???; Complete this line below
String s = Integer.toString(n);
if (n == Integer.parseInt(s)) {
System.out.println("Good job");
} else {
System.out.println("Wrong answer.");
}
} catch (DoNotTerminate.ExitTrappedException e) {
System.out.println("Unsuccessful Termination!!");
}
}
}
//The following class will prevent you from terminating the code using exit(0)!
class DoNotTerminate {
public static class ExitTrappedException extends SecurityException {
private static final long serialVersionUID = 1;
}
public static void forbidExit() {
final SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPermission(Permission permission) {
if (permission.getName().contains("exitVM")) {
throw new ExitTrappedException();
}
}
};
System.setSecurityManager(securityManager);
}
}
============
Essa publicação faz parte de uma série de exercÃcios resolvidos em Java no HackerRank. Acesse a série completa:
- HackerRank #6 | Scanner e End-of-file
- HackerRank #7 | Int to String / String to Int
- HackerRank #8 | Date and Time
- HackerRank #9 | Static Initializer Block
- HackerRank #10 | Currency Formatter
- HackerRank #11 | DataTypes
- HackerRank #12 | Strings Introduction
- HackerRank #13 | Substring Comparisons
- HackerRank #14 | Abstract Class
- HackerRank #18 | BigInteger
- HackerRank #19 | Loops II
- HackerRank #20 | String Reverse
- HackerRank #23 | Instanceof keyword
- HackerRank #26 | Generics
- HackerRank #27 | 1D Array
- HackerRank #28 | Anagrams
- HackerRank #33 | Arraylist
- HackerRank #34 | Exception Handling Try / Catch
- HackerRank #36 | Exception Handling
- HackerRank #37 | List
- HackerRank #38 | SubArray
- HackerRank #39 | HashSet
- HackerRank #40 | Java Dequeue
Top comments (0)