Skip to content

Instantly share code, notes, and snippets.

@alvadorn
Last active August 14, 2020 23:11
Show Gist options
  • Select an option

  • Save alvadorn/1aaf5256739746a6b4fe6828d4d7de72 to your computer and use it in GitHub Desktop.

Select an option

Save alvadorn/1aaf5256739746a6b4fe6828d4d7de72 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
public class TryCatchExample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("\nDigite o palpite");
int userTry = TryCatchExample.tryDigit(scan);
}
public static int tryDigit(Scanner scan) {
try {
return scan.nextInt();
} catch(Exception e){
System.out.println("ERRO: "+e.getMessage()+"\nPor favor, digite um número válido: ");
System.out.println("\nDigite novamente o palpite");
scan.nextLine(); // clean buffer here
return TryCatchExample.tryDigit(scan);
}
}
}
import java.util.Scanner;
public class TryCatchExampleDoWhile {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("\nDigite o palpite");
boolean repeatScan = false;
int userTry;
do {
try {
userTry = scan.nextInt();
repeatScan = false;
} catch(Exception e){
System.out.println("ERRO: "+e.getMessage()+"\nPor favor, digite um número válido: ");
System.out.println("\nDigite novamente o palpite");
scan.nextLine(); // clean buffer here
repeatScan = true;
}
} while(repeatScan);
}
}
@Fernandoez
Copy link

Só queria dizer que eu amo esse cara!
Igor é o melhor!!!
Obrigado pela ajuda!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment