Check if string taken with Scanner.next() contains number - java

I wanted to take a String using Scanner.next() and see if it contains a number or not. I used regex to check if a string contains anything but a number. The regex works correctly if the string is hard coded, but not when taken from keyboard. I expected input of 5 to be detected as a number, but it is not. Please tell me why. My code:
import java.util.Scanner;
public class Error {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int num = 0;
String input = "";
boolean isStringNumber = true;
System.out.println("\nPlease enter a number only...");
input = inp.nextLine();
isStringNumber = input.contains("[^0-9]+");
if (isStringNumber == false) {
System.out.println("\nYou entered a non number " + input);
}
}
}

contains uses a String literal as its argument. Use matches instead
isStringNumber = input.matches("[0-9]+");
or simply
isStringNumber = input.matches("\\d+");
BTW: Scanner has a nextInt method for accepting integer values

instead isStringNumber = input.contains("[^0-9]+");
try isStringNumber = input.matches("[0-9]+");

Related

How can I use something like (input == '\n') to determine when to stop accepting user input?

I have to convert an infix operation to a postfix one, however the infix operation must be inputted as one character per line. So instead of inputting something like this: 3-2, you would need to input something like this:
3
-
2
I had an idea of using =='\n' to determine whether the inputted character is a next line function so that would determine the end of the equation, but it doesn't work. I tried replacing it with a different character such as =='e', and that works perfectly. What can I do to fix this?
String string = "";
Scanner input = new Scanner(System.in);
boolean flag = true;
while (flag==true)
{
char charIn = input.next().charAt(0);
string = string + charIn;
if (charIn=='e') //inputting 'e' gives me my desired result
{
flag = false;
}
}
//code that passes string to InfixToPostfix method and prints out the answer. this part works fine
You did not specify that this was a school assignment or that you had certain restrictions, so this answer is admittedly a shot in the dark.
I would recommend using a StringBuilder within a loop and reading nextLine() instead of simply next(). This allows you to determine if the entry was empty (ie: the enter key was pressed without entering a character).
Also, we should allow the user to enter more than one character anyway (what happens when they try to enter 22 as a number). Abandoning the char type allows for this.
public static void main(String[] args) {
StringBuilder string = new StringBuilder();
Scanner input = new Scanner(System.in);
boolean flag = true;
while (flag) {
// Capture all characters entered, including numbers with multiple digits
String in = input.nextLine();
// If no characters were entered, then the [ENTER] key was pressed
if (in.isEmpty()) {
// User is done adding characters; exit the loop
flag = false;
} else {
// Otherwise, get the text entered and add it to our final string
string.append(in);
}
}
System.out.println("Final String: " + string);
}
Does this meet your needs?
This should do what you want. Reading just the first character has its limitations.
String string = "";
Scanner input = new Scanner(System.in);
boolean flag = true;
while (flag==true)
{
String nextLine = input.nextLine();
char charIn;
if(nextLine.length() > 0) {
charIn = nextLine.charAt(0); //This is bad idea as you can only operate on single digit numbers
System.out.println("charIn = " + charIn);;
string = string + charIn;
}
else
flag = false;
}

StringOutOfBoundsException 1 Java

This is what the error says:
java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.substring(String.java:1963)
at FracCalc.produceAnswer(FracCalc.java:34)
at FracCalc.main(FracCalc.java:16)
And Here is my existing code:
import java.util.*;
public class FracCalc {
public static void main(String[] args)
{
// TODO: Read the input from the user and call produceAnswer with an equation
Scanner input = new Scanner(System.in);
System.out.println("Do you want to calculate something? If no, type in 'quit'. If yes, simply type in 'yes'. ");
String Continue = input.next();
if(Continue.equals("quit")){
System.out.println("Have a nice day! ");
}else if(Continue.equals("yes")){
System.out.println("Please input a fraction, there must be exactly one space between the operator and the operand. ");
String readInput = input.nextLine();
System.out.println(produceAnswer(readInput));
}
}
// ** IMPORTANT ** DO NOT DELETE THIS FUNCTION. This function will be used to test your code
// This function takes a String 'input' and produces the result
//
// input is a fraction string that needs to be evaluated. For your program, this will be the user input.
// e.g. input ==> "1/2 + 3/4"
//
// The function should return the result of the fraction after it has been calculated
// e.g. return ==> "1_1/4"
public static String produceAnswer(String input)
{
// TODO: Implement this function to produce the solution to the input
int space = input.indexOf(" ");
int nextspace = space + 2;
String operand = input.substring(0, space + 1);
String operator = input.substring(space + 1, nextspace);
String operand2 = input.substring(nextspace + 1, input.length());
return operand2;
}
// TODO: Fill in the space below with any helper methods that you think you will need
}
I'm trying to segregate fraction operators by determining the indexes of spaces and then going from there. Unfortunately i keep getting this error. Can someone please help! Thank You!
You have to use input.nextLine() since you want to read the entire line and not just characters. Try this in your main method:
Scanner input = new Scanner(System.in);
System.out.println("Do you want to calculate something? If no, type in 'quit'. If yes, simply type in 'yes'. ");
String Continue = input.nextLine();
if (Continue.equals("quit")) {
System.out.println("Have a nice day! ");
} else if (Continue.equals("yes")) {
System.out.println(
"Please input a fraction, there must be exactly one space between the operator and the operand. ");
String readInput = input.nextLine();
System.out.println(produceAnswer(readInput));
}

Splitting strings with scanner

I am trying to split a string into two others with the Scanner in Java. It doesn't seem to be working. I can only find examples through Google where Scanner is used to read console input. I worked out the way I'm doing things from the manual for the Scanner and I'm not sure what I've got wrong.
String elem = "hello.there";
Scanner s = new Scanner(elem);
s.useDelimiter(".");
String first = s.next();
String second = s.next();
First and second are showing up blank, I'm not sure why.
You need to scape the period (.):
s.useDelimiter("\\.");
and then use next() which returns the next complete token, since hasNext() returns a boolean representinf if the scanner has another token in its input:
String first = s.next();
String second = s.next();
import java.util.Scanner;
public class TokenizeUsingScanner {
/**
* This java sample code shows how to split
* String value into tokens using
* Scanner. This program tokenize
* the input string base on the delimiter
* set by calling the useDelimiter method
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String input = "hello.there";
Scanner s = new Scanner(input);
s.useDelimiter("\\.");
while(s.hasNext()){
System.out.println(s.next());
}
}
}
String first = s.hasNext(); returns boolean so you can't asssign it to a string.
You need
String first = s.next();

Correctly scanning a blank input with the Scanner object

I'm working on creating a basic guitar inventory and I'm doing testing with scanner, I was trying to scan a blank entry and when there is a blank entry it should print "ANY" and it does, i'm using scan.useDelimiter("\z"); and now when I enter a correct entry like "fender" it should print "FENDER" but it just prints "ANY" as if the entry was incorrect.. someone know what I can do to solve that problem? Here is an sscce:
import java.util.Scanner;
public class SSCCE {
public static void main(String[] args)
{
System.out.println("Enter a builder name: ");
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\z"); // count a blank entry (end of input)
String entry_1 = scan.next();
if (entry_1.equalsIgnoreCase("FENDER")
|| entry_1.equalsIgnoreCase("MARTIN")
|| entry_1.equalsIgnoreCase("GIBSON")
|| entry_1.equalsIgnoreCase("COLLINGS")
|| entry_1.equalsIgnoreCase("OLSON")
|| entry_1.equalsIgnoreCase("RYAN")
|| entry_1.equalsIgnoreCase("PRS"))
{
entry_1 = entry_1.toUpperCase();
System.out.println(entry_1);
}
else
{
entry_1 = "ANY";
System.out.println(entry_1);
}
}
}
By default, the scanner removes the delimiter from the tokens it return. When the delimiter was a line break (the default), when you do fender, entry_1 was assigned "fender". After you changed the delimiter, the line break caused by the enter is no longer removed, so you get "fender\n" in entry_1, causing your if condition to fail.
To fix, just do String entry_1 = scan.next().trim(); instead which removes the trailing linebreak.
You can try printing the scanned value to see why it is not going into the if statement.
import java.util.Scanner;
public class SSCCE {
public static void main(String[] args)
{
System.out.println("Enter a builder name: ");
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\z"); // count a blank entry (end of input)
String entry_1 = scan.next();
System.out.println("Input = [" + entry_1 + "]");
// rest of the code...
}
I think this is due to your use of \\z. Look at this regex tutorial for a more detailed story. For solving your problem, suffice it to say that changing it to \\Z should do the trick. The following code is working for me:
public static final Set<String> names = Sets.newHashSet("martin", "gibson", ...);
public static void main(String[] args) {
System.out.println("Enter a builder name: ");
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\Z"); // count a blank entry (end of input)
String entry = scan.next();
entry = "any" if (!names.contains(entry.toLowerCase());
System.out.println(entry.toUpperCase());
}
Note: I assumed you are scanning one name at a time. If not, then just use line break.

String replace function not replacing characters correctly - Java

I am trying to replace a specific character '8' with a '2' in a string. I think I have everything set up correctly and when I look online for examples, this looks like it should. When I print the string though, it is just as I entered it. To run it, test it with "80802" or some similar input. Thanks!
import java.util.Scanner;
class PhoneNumber {
public static void main(String[] args) {
String number = null;
Scanner scan = new Scanner(System.in);
// Prompt the user for a telephone number
System.out.print("Enter your telephone number: ");
// Input the user's name
number = scan.nextLine();
// Replace the relevant letters with numbers
number.replace('8', '2');
System.out.println("Your number is: " + number );
}
}
A common mistake... You want:
number = number.replace('8', '2');
String.replace() doesn't change the String, because Strings are immutable (they can not be changed). Instead, such methods return a new String with the calculated value.
number.replace() returns a new string. It does not change `number'.
number.replace('8','2'); returns the correct string it does not modify number. To get your desired functionality you must type
number = number.replace('8','2');
public static void main(String[] args) {
String number = null;
Scanner scan = new Scanner(System.in);
// Prompt the user for a telephone number
System.out.print("Enter your telephone number: ");
// Input the user's name
number = scan.nextLine();
// Replace the relevant letters with numbers
number = number.replace('8', '2');
System.out.println("Your number is: " + number );
}
Hope this helps.

Categories