I've made the code so it asks the user various questions, and if the input.trim().isEmpty() a message will be given to the user and will ask the user to input again. So if the user just writes blank spaces, message given. If the user gives a few blank spaces and some characters, it will accept.
Problem right now is that I want to capitalize the first letter of the Word, but it doesn't really work. Say if the user's input start with a letter then that will be capitalized. But if there's whitespace it wont capitalize at all.
So if input is:
katka
Output is:
katka
Another example:
katka
Output is:
Katka
Code is:
String askWork = input.nextLine();
String workplace = askWork.trim().substring(0,1).toUpperCase()
+ askWork.substring(1);
while (askWork.trim().isEmpty()){
String askWork = input.nextLine();
String workplace = askWork.trim().substring(0,1).toUpperCase()
+ askWork.substring(1);
}
I've tried different approaches but no success.
The problem is because of whitespace as all the indices you refer while converting to uppercase are not accurate.
So first trim() the String so you can clear all leading and trailing whitespace and then capitalize it.
better check empty string and all whitespace to avoid exception.
String askWork = input.nextLine().trim();
String capitalized = askWork.substring(0, 1).toUpperCase() + askWork.substring(1)
The trim() method on String will clear all leading and trailing whitespace. The trimmed String must become your new String so that all indices you refer to after that are accurate. You will no longer need the replaceAll("\\s",""). You also need logic to test for empty input. You use the isEmpty() method on String for that. I've written a toy main() that keeps asking for a word and then capitalizes and prints it once it gets one. It will test for blank input, input with no characters, etc.
public static void main(String[] args) throws Exception {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String askWork = "";
while (askWork.isEmpty()) {
System.out.println("Enter a word:");
askWork = input.readLine().trim();
}
String workPlace = askWork.substring(0,1).toUpperCase() + askWork.substring(1);
System.out.println(workPlace);
}
Try trimming your input to remove the whitespace, before attempting to capitalize it.
String askWork = input.nextLine().trim();
String capitalized = askWork.substring(0, 1).toUpperCase() + askWork.substring(1)
However, if the input is only whitespace, this will result in an IndexOutOfBoundsException because after trim() is called askWork is set to the empty string ("") and you then try to access the first character of the empty (length 0) string.
String askWork = input.nextLine().trim();
if(askWork.isEmpty()) {
// Display error
JOptionPane.showMessageDialog(null, "Bad!");
else {
String capitalized = askWork.substring(0, 1).toUpperCase() + askWork.substring(1)
JOptionPane.showMessageDialog(null, "It worked! -- " + capitalized);
}
You will need to trim the input before you start manipulating its contents:
String askWork = input.nextLine().trim();
String workplace = askWork.substring(0,1).toUpperCase() + askWork.substring(1);
Another solution without substrings:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String askWork = input.nextLine().trim();
while (askWork.isEmpty())
askWork = input.nextLine().trim();
char[] workChars = askWork.toCharArray();
workChars[0] = workChars[0].toUpperCase();
String workplace = String.valueOf(workChars);
// Work with workplace
input.close();
}
Related
I am working through a piece of self study, Essentially I am to ask the User for a string input such as "John, Doe" IF the string doesnt have a comma, I am to display an error, and prompt the user until the string does indeed have a comma (Fixed.). Once this is achieved I need to parse the string from the comma, and any combination of comma that can occur (i.e. John, doe or John , doe or John ,doe) then using the Scanner class I need to grab John doe, and split them up to be separately printed later.
So far I know how to use the scanner class to grab certain amounts of string up to a whitespace, however what I want is to grab the "," but I haven't found a way to do this yet, I figured using the .next(pattern) of the scanner class would be what I need, as the way it was written should do exactly that. however im getting an exception InputMismatchException doing so.
Here is the code im working with:
while (!userInput.contains(",")) {
System.out.print("Enter a string seperated by a comma: ");
userInput = scnr.nextLine();
if (!userInput.contains(",")) {
System.out.println("Error, no comma present");
}
else {
String string1;
String string2;
Scanner inSS = new Scanner(userInput);
String commaHold;
commaHold = inSS. //FIXME this is where the problem is
string1 = inSS.next();
string2 = inSS.next();
System.out.println(string1 + " " + string2);
}
}
This can be achieved simply by splitting and checking that the result is an array of two Strings
String input = scnr.nextLine();
String [] names = input.split (",");
while (names.length != 2) {
System.out.println ("Enter with one comma");
input = scnr.nextLine();
names = input.split (",");
}
// now you can use names[0] and names[1]
edit
As you can see the code for inputting the data is duplicated and so could be refactored
I'm writing out a piece of a code that where I am trying to split up the user's input into 3 different arrays, by using the spaces in-between the values the user has entered. However, everytime i run the code i get the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Substring.main(Substring.java:18)
Java Result: 1
I have tried to use a different delimiter when entering the text and it has worked fine, e.g. using a / split the exact same input normally, and did what i wanted it to do thus far.
Any help would be appreciated!
Here's my code if needed
import java.util.Scanner;
public class Substring{
public static void main(String[]args){
Scanner user_input = new Scanner(System.in);
String fullname = ""; //declaring a variable so the user can enter their full name
String[] NameSplit = new String[2];
String FirstName;
String MiddleName;
String LastName;
System.out.println("Enter your full name (First Middle Last): ");
fullname = user_input.next(); //saving the user's name in the string fullname
NameSplit = fullname.split(" ");//We are splitting up the value of fullname every time there is a space between words
FirstName = NameSplit[0]; //Putting the values that are in the array into seperate string values, so they are easier to handle
MiddleName = NameSplit[1];
LastName = NameSplit[2];
System.out.println(fullname); //outputting the user's orginal input
System.out.println(LastName+ ", "+ FirstName +" "+ MiddleName);//outputting the last name first, then the first name, then the middle name
new StringBuilder(FirstName).reverse().toString();
System.out.println(FirstName);
}
}
Split is a regular expression, you can look for one or more spaces (" +") instead of just one space (" ").
String[] array = s.split(" +");
Or you can use Strint Tokenizer
String message = "MY name is ";
String delim = " \n\r\t,.;"; //insert here all delimitators
StringTokenizer st = new StringTokenizer(message,delim);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
You have made mistakes at following places:
fullname = user_input.next();
It should be nextLine() instead of just next() since you want to read the complete line from the Scanner.
String[] NameSplit = new String[2];
There is no need for this step as you are doing NameSplit = user_input.split(...) later but it should be new String[3] instead of new String[2] since you are storing three entries i.e. First Name, Middle Name and the Last Name.
Here is the correct program:
class Substring {
public static void main (String[] args) throws java.lang.Exception {
Scanner user_input = new Scanner(System.in);
String[] NameSplit = new String[3];
String FirstName;
String MiddleName;
String LastName;
System.out.println("Enter your full name (First Middle Last): ");
String fullname = user_input.nextLine();
NameSplit = fullname.split(" ");
FirstName = NameSplit[0];
MiddleName = NameSplit[1];
LastName = NameSplit[2];
System.out.println(fullname);
System.out.println(LastName+ ", "+ FirstName +" "+ MiddleName);
new StringBuilder(FirstName).reverse().toString();
System.out.println(FirstName);
}
}
Output:
Enter your full name (First Middle Last): John Mayer Smith
Smith, John Mayer
John
java.util.Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
hence even though you entered 'Elvis John Presley' only 'Elvis' is stored in the fullName variable.
You can use BufferedReader to read full line:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
fullname = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
or you can change the default behavior of scanner by using:
user_input.useDelimiter("\n"); method.
The exception clearly tells that you are exceeding the array's length. The index 2 in LastName = NameSplit[2] is out of array's bounds. To get rid of the error you must:
1- Change String[] NameSplit = new String[2] to String[] NameSplit = new String[3] because the array length should be 3.
Read more here: [ How do I declare and initialize an array in Java? ]
Up to here the error is gone but the solution is not correct yet since NameSplit[1] and NameSplit[2] are null, because user_input.next(); reads only the first word (*basically until a whitespace (or '\n' if only one word) is detected). So:
2- Change user_input.next(); to user_input.nextLine(); because the nextLine() reads the entire line (*basically until a '\n' is detected)
Read more here: [ http://www.cs.utexas.edu/users/ndale/Scanner.html ]
hello guys I need help with reading from file with space delimiter. The problem is for example i got a text file the format as follows: id name
example:
1 my name
how can I get the string together (my name) as the code I have tried would only get me (my). I can't change the delimiter from the text file
while(myScanner.hasNextLine())
{
String readLine = myScanner.nextLine();
String readData[] = readLine.split(" ");
String index = readData[0];
String name = readData[1];
}
myScanner.close();
If it's always just going to be id space name with nothing coming after it, then you can do this:
String readLine = myScanner.nextLine();
int split = readLine.indexOf(" ");
String index = readLine.substring(0, split);
String name = readLine.substring(split + 1);
This will only work if those are the only two fields though. If you add more fields after that there's no (general) way to determine where item two ends and item three begins.
Another way is to use next, nextInt, etc, to read out exactly what you want:
String index = myScanner.next(); //Or int index = myScanner.nextInt();
String name = myScanner.nextLine().substring(1); //drop the leading space
That's a bit more flexible of an approach, which might be better suited to your needs.
Use following code.
while(myScanner.hasNextLine())
{
String readLine = myScanner.nextLine();
if(null != readLine && readLine.length()>0) {
String index = readLine.substring(0, id.indexOf(" "));
String name = readLine.substring(id.indexOf(" ") + 1);
}
}
myScanner.close();
I am trying to make the user input a string, which can both contain spaces or not. So in that, I'm using NextLine();
However, i'm trying to search a text file with that string, therefore i'm using next() to store each string it goes through with the scanner, I tried using NextLine() but it would take the whole line, I just need the words before a comma.
so far here's my code
System.out.print("Cool, now give me your Airport Name: ");
String AirportName = kb.nextLine();
AirportName = AirportName + ",";
while (myFile.hasNextLine()) {
ATA = myFile.next();
city = myFile.next();
country = myFile.next();
myFile.nextLine();
// System.out.println(city);
if (city.equalsIgnoreCase(AirportName)) {
result++;
System.out.println("The IATA code for "+AirportName.substring(0, AirportName.length()-1) + " is: " +ATA.substring(0, ATA.length()-1));
break;
}
}
The code works when the user inputs a word with no spaces, but when they input two words, the condition isn't met.
the text file just includes a number of Airports, their IATA, city, and country. Here's a sample:
ADL, Adelaide, Australia
IXE, Mangalore, India
BOM, Mumbai, India
PPP, Proserpine Queensland, Australia
By default, next() searches for first whitespace as a delimiter. You can change this behaviour like this:
Scanner s = new Scanner(input);
s.useDelimiter("\\s*,\\s*");
By this, s.next() will match commas as delimiters for your input (preceeded or followed by zero or more whitespaces)
Check out the String#split method.
Here's an example:
String test = "ADL, Adelaide, Australia\n"
+ "IXE, Mangalore, India\n"
+ "BOM, Mumbai, India\n"
+ "PPP, Proserpine Queensland, Australia\n";
Scanner scan = new Scanner(test);
String strings[] = null;
while(scan.hasNextLine()) {
// ",\\s" matches one comma followed by one white space ", "
strings = scan.nextLine().split(",\\s");
for(String tmp: strings) {
System.out.println(tmp);
}
}
Output:
ADL
Adelaide
Australia
IXE
Mangalore
India
BOM
Mumbai
India
PPP
Proserpine Queensland
Australia
What would be a concise regular regular expression to remove everything from a string that is not an alphabet
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int T=0;
try{
T= Integer.parseInt(br.readLine());
while(T>0)
String input=br.readLine();
**String res= input.replaceAll("^[a-zA-Z]"," " );**
System.out.println(res);
Also tried
input.replaceAll("[^a-zA-Z]]"," " )
Neither of them is replacing anything from the input string.The input string remains just as it was
Edit:
input.replaceAll("[^a-zA-Z]"," " ) //works well
input.replaceAll("^[a-zA-Z]"," " ) //replaces first char of string
You need:
input = input.replaceAll("[^a-zA-Z]"," " );
^^^^^^^ ^ ^
You need to make the input reference point to the String object returned by the replaceAll method to get the changed string as Strings are immutable.
The range A-z is not something you want. You need A-Z.
Also you have an extra ] in your pattern.
See it
input.replaceAll("[^a-zA-z]","") is a new string in String constant pool and you don't set your string with this new content. Use this please:
input = input.replaceAll("[^a-zA-z]","");