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
Related
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.
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.
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
}
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!
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 kind of new to this stuff, but what i want to do is just print out 00s from an int array that i created. I used a stringBuilder() to get rid of the commas and stuff. Now when I print out the numbers, they must have a space after every third 0 (a total of 11 0s). How do I do that? I only get a space after every 0 :-(.
here is what I got so far.
public class AccountNumber {
private int[] digits = new int [11];
// Methods Returns a string representation
public String toString() {
StringBuilder builder = new StringBuilder();
for (int value :digits) {
builder.append(value + " ");
}
String text = builder.toString();
return text;
//return Arrays.toString(digits);
}
public AccountNumber ( boolean random ){
}
}
The output I want is 000 000 000 00
I have another (main) class which creates the object for me. That's where the printing should happen.
public class Test1 {
public static void main (String [] args) {
//Random rand = new Random(false);
AccountNumber acc = new AccountNumber(false);
System.out.println(acc.toString());
//AccountNumber.AccountNumber();
}
}
Thank you
You are trying to pretty print 11-digit account number on your Account class. You want to insert space after each 3 digits. If my assumptions are correct, you just need a counter to see which digit you're on and test if that digit can be divided by three:
int index= 0;
for (int value :digits) {
builder.append(value);
if (index %3 == 0) {
builder.append(" ");
}
++index;
}
This could be written in more clear way by using classic for loop, but I don't know which type your digits field is.