How to check if input is string with Try Catch? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
I have the following code with a try .. catch operation that checks whether or not it is a String. However , no matter the input it will not throw an exception . What I want it to do is check whether or not the input is text for example "Nick" and if its not to them throw an exception and prompt the user to try again.
public static void main(String args[]) {
int c = 1
String temp, name="" ;
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter name");
while (c == 1) {
try {
temp = myObj.nextLine();
name = temp;
c = 2;
} catch (InputMismatchException e) {
System.out.println("Name is not a string. Try again.");
}
}
}

Return type of nextline() is String. It means whatever is entered by user, it will be treated as a String(even if user enters a number, it will still be taken as a String). So there is no need in Exception handling in this case.

Any input will be a String. If what you want is to check if there are any numbers or special characters inside instead of letters then u can loop through the String and use the Character.isAlphabetic() that will return false if any character is not alphabetic.

I think this approach would work for you:
public static void main(String args[]){
String name = "";
Scanner myObj = new Scanner(System.in);
final String correctExpectedName = "Nick";
while(name.length() == 0) {
System.out.print("Enter name: ");
String tempInput = myObj.nextLine();
if (correctExpectedName.equals(tempInput)) {
name = tempInput; // here you can also use name = correctExpectedName;
} else {
System.out.println("Name is not correct. Please try again ...");
}
}
}
Please don't use exceptions to control your application logic flow. Exceptions have different purpose.

Related

How do I get the Scanner in java to read a string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How would I get my program to quit when the user enters q?
Is there something wrong with the scanner?
My code
import java.util.*;
public class Main{
public static void main(String []args){
int age;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your age, or enter 'q' to quit the program.");
age = scan.nextInt();
if(age.equals("q") || age.equals("Q")){
return 0;
}
System.out.println("Your age is " + age);
}
}
I can see mainly two problems in your code:
It lacks a loop to repeat asking for age again. There can be many ways (for, while, do-while) to write a loop but I find do-while most appropriate for such a case as it always executes the statements within the do block at least once.
age is of type, int and therefore it can not be compared with a string e.g. your code, age.equals("q") is not correct. A good way to handle such a situation is to get the input into a variable of type, String and check the value if it should allow/disallow processing it (e.g. trying to parse it into an int).
Note that when you try to parse a string which can not be parsed into an int (e.g. "a"), you get a NumberFormatException which you need to handle (e.g. show an error message, change some state etc.).
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int age;
String input;
Scanner scan = new Scanner(System.in);
boolean valid;
do {
// Start with the assumption that input will be valid
valid = true;
System.out.print("Enter your age, or enter 'q' to quit the program: ");
input = scan.nextLine();
if (!(input.equals("q") || input.equals("Q"))) {
try {
// Try to parse input into an int
age = Integer.parseInt(input);
System.out.println("Your age is " + age);
} catch (NumberFormatException e) {
System.out.println("Invalid input");
// Change the value of valid to false
valid = false;
}
}
} while (!valid || !(input.equals("q") || input.equals("Q")));
}
}
A sample run:
Enter your age, or enter 'q' to quit the program: a
Invalid input
Enter your age, or enter 'q' to quit the program: 12.5
Invalid input
Enter your age, or enter 'q' to quit the program: 14
Your age is 14
Enter your age, or enter 'q' to quit the program: 56
Your age is 56
Enter your age, or enter 'q' to quit the program: q

Is it possible to validate a scanner to check if it has a minimum (x) of the same specific values? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
What I'm trying to do is validate a scanner so that if the input string doesn't have a minimum of two vowels it returns an error, however I'm not sure how to go about this and can't seem to find an answer elsewhere.
Scanner sc = new Scanner(System.in);
System.out.print("Input alphabetical character string: ");
while (!sc.hasNext("[aeiouAEIOU]+")) {
System.out.println("Error, sequence requires a minimum of two vowels");
sc.next();
}
you could use a validate method each time they enter a value something like this.this one only checks for each vowel once though.
public static void main(String[] args) {
// TODO Auto-generated method stub
String sInput = "";
Scanner sc = new Scanner(System.in);
System.out.print("Input alphabetical character string: ");
sInput = sc.next();
if (!hasTwoVowels(sInput)) {
System.out.println("Error, sequence requires a minimum of two vowels");
sc.next();
}
sc.close();
}
public static boolean hasTwoVowels(String sInput){
int iCount = 0;
String vowel[] = new String[]{"a","e","i","o","u","A","E","I","O","U"};
for(int i =0; i < 10;i++) {
if(sInput.contains(vowel[i])) {
iCount++;
if(iCount == 2) {
return true;
}
}
}
return false;
}
}
you could also split the string and count each letter then add up the vowels
you can easily do this by doing something like this.
arr[(int)'e' - (int)'a']++ that will increment arr[4] counting 1 e
you could also use a bufferedReader to count the vowels
This is a problem where using a Scanner makes the problem harder.
The simple solution is to just read the stream one character at a time using a BufferedReader and count the characters that are vowels.
You could do it by configuring a Scanner to return "tokens" consisting of a single character and then counting the tokens that match a vowel. But that's pointless ... IMO.

Java Beginner logic error help needed [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I apologize in advance for my post. I decided to register tonight and this is my first post.
A little background about the question.
I am doing a little java project, where I need to take a name from user input, which is saved in a variable. the variable value must then display the output.
my question is. How is it done in java, using the (if) keyword, to use my code to create an if statement that voids my simple i_PlayerName method of any logic error.
to be more specific, how can I make sure that my program will only accept a string value, and if another data type is entered, an output message will be displayed " user input not accepted ".
lastly, what is this procedure called?
Thank you all :)
keep on coding the code.
public void i_PlayerName() {
String playerName;
Scanner i_playerName = new Scanner(System.in);
System.out.println("ENTER YOUR SHIP NAME");
playerName = i_playerName.nextLine();
System.out.println("Your vessel has been named " + playerName);
}
Assuming you meant alphabets when you said only strings are allowed, this should do it.
public static void main(String[] Args) {
String playerName = "";
System.out.print("Enter ship name: ");
Scanner scanner = new Scanner(System.in);
String i_playerName = scanner.next();
System.out.println();
char[] chars = i_playerName.toCharArray();
boolean isChar = true;
for (char c : chars) {
if (!Character.isLetter(c)) {
isChar = false;
}
}
if(isChar == true) {
System.out.println("Your vessel has been named: " + i_playerName);
}
else {
System.out.println("User input is not accepted.");
}
}
when the scanner is reading if you assign it to a String type it will take the input as a String regardless if the user inputs numbers or Strings. If you want to handle the scenario when user inputs value other than String you can do it with regular expression and if the input is not a match then output the error. Use below method to check if input is a String.
public boolean isStringValue(String s){
String pattern= "[a-zA-Z]*";
return s.matches(pattern);
}
//use method above:
String input = scan.next();
if(isStringValue(input)){
//your code
} else {
//output some error
}

How does one go about doing so [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Write a method called multiConcat that takes a String and an integer as parameters. Return a String made up of the string parameter concatenated with itself count time, where count is the integer. for example, if the parameters values are “ hi” and 4, the return value is “hihihihi” Return the original string if the integer parameter is less than 2.
What i have so Far
import java.util.Scanner;
public class Methods_4_16 {
public static String multiConcat(int Print, String Text){
String Msg;
for(int i = 0; i < Print; i ++ ){
}
return(Msg);
}
public static void main(String[] args) {
Scanner Input = new Scanner(System.in);
int Prints;
String Texts;
System.out.print("Enter Text:");
Texts = Input.nextLine();
System.out.print("Enter amount you wanted printed:");
Prints = Input.nextInt();
System.out.print(multiConcat(Prints,Texts));
}
}
Just a few hints:
concating strings can be done this way: appendTo += stuffToConcat
repeating an operation n times can be done with a for-loop of this kind:
for(int i = 0 ; i < n ; i++){
//do the stuff you want to repeat here
}
Should be pretty simple to build the solution from these two parts. And just in case you get a NullPointerException: remember to initialize Msg.
Try this:
public static String multiConcat(int print, String text){
StringBuilder msg = new StringBuilder();
for(int i = 0; i < print; i ++ ) {
msg.append(text);
}
return msg.toString();
}
I have used StringBuilder instead of a String. To know the difference, give this a read: String and StringBuilder.
Also, I would guess you are new to Java programming. Give this link a read. It is about Java naming conventions.
Hope this helps!

Reading Strings [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm having trouble with an assignment. What's happening is that a file is being read that reads numbers and validates if they're correct values. One of these values contains a letter and I'm trying to get my program to detect that and save the total value that should not be there. Here's the code. I'm reading the data as Strings and then converting the strings into doubles to be compared. I want to validate if the strings being read in are all numbers and then save that value for a later use. Does that make sense? for example the numbers have to be between 0 and 99999 and one value is 573S1, which wouldn't work because it contains an S. I want to save that value 573S1 to be printed as an error from the file at a later point in the code.
public static void validateData() throws IOException{
File myfile = new File("gradeInput.txt");
Scanner inputFile = new Scanner(myfile);
for (int i=0; i<33; i++){
String studentId = inputFile.next();
String toBeDouble = studentId;
Double fromString = new Double(toBeDouble);
if (fromString<0||fromString>99999){
System.out.println();
}
Any help would be greatly appreciated. Thanks a lot!
Edit: Here's what I get if I try to run the program.
Exception in thread "main" java.lang.NumberFormatException: For input string: "573S1"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Double.valueOf(Double.java:475)
at java.lang.Double.<init>(Double.java:567)
at Paniagua_Grading.validateData(Paniagua_Grading.java:23)
at Paniagua_Grading.main(Paniagua_Grading.java:6)
Because you are using Scanner on a file, Scanner can actually tell you this information with hasNextDouble.
while(inputFile.hasNext()) {
if(inputFile.hasNextDouble()) {
// the next token is a double
// so read it as a double
double d = inputFile.nextDouble();
} else {
// the next token is not a double
// so read it as a String
String s = inputFile.next();
}
}
This kind of convenience is the main reason to use Scanner in the first place.
You could try something like the method below, which will check if a string contains only digits -
private static boolean onlyDigits(String in) {
if (in == null) {
return false;
}
for (char c : in.toCharArray()) {
if (Character.isDigit(c)) {
continue;
}
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(onlyDigits("123"));
System.out.println(onlyDigits("123A"));
}
The output is
true
false

Categories