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();
Related
For example the name Donald trump (12 character) brings up the error string index out of range 7 (where the space is found) even though the name Donald trump is longer.
package test;
import javax.swing.JOptionPane;
public class Usernamesubstring {
public static void main(String[] args) {
String fullname = JOptionPane.showInputDialog("What is your full name");
int breakbetween = fullname.lastIndexOf(" ");
String firstnamess = fullname.substring(breakbetween - 3, breakbetween);
int length = fullname.length();
String lastnamess = fullname.substring(length - 3, length);
String firstnamec = firstnamess.substring(0, 0);
String lastnamec = lastnamess.substring(breakbetween + 1, breakbetween + 1 );
firstnamec = firstnamec.toUpperCase();
lastnamec = lastnamec.toUpperCase();
String firstname = firstnamess.substring(1,3);
String lastname = firstnamess.substring(1,3);
firstname = firstnamec + firstname;
lastname = lastnamec + lastname;
System.out.println(firstname + lastname);
}
}
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.substring(String.java:1963)
at test.Usernamesubstring.main(Usernamesubstring.java:14)
You've made it more complicated than it needs to be. A simple solution can be made using String.split (which divides a string into an array of smaller strings based on a delimiter, e.g. "Donald Trump".split(" ") == {"Donald", "Trump"})
Full Code
class Usernamesubstring // change that since it no longer uses substrings
{
public static void main (String[] args)
{
String fullName = "Donald Trump";
String[] parts = fullName.split(" ");
String firstName = parts[0]; // first item before the space
String lastName = parts[parts.length - 1]; // last item in the array
System.out.println(firstName + " " + lastName);
}
}
sometimes independent of your indexes
String fullName = "Donald Trump";
String[] result = fullName.split (" ");
in result you will find now
result [0] ==> Donald
result [1] ==> Trump
isn't that a little easier for your project?
Your error shoul be in the line String lastnamec = lastnamess.substring(breakbetween + 1, breakbetween + 1 ); as lastnamess is a string of lenght 3 from fullname.substring(length - 3, length); and breakbetween is greater then 3 for "Donald Trump", where space is character 6.
You should simpify your code a bit, it makes it easier to read and find the problems.
tl;dr: The exception occurs when you try to access a String at an index which exceeds it's length or is just not contained in the string (negative values).
Regarding your approach: It's usually not a good idea to prompt a name in full because people tend to input weird stuff or mix up the order. Better prompt for first and last name separately.
Assuming someone input his name with Firstname Lastname you wouldn't have to make such a substring mess, Java has some nice features:
String name = "Mario Peach Bowser";
name = name.trim();
String[] parts = name.split(" ");
String lastname = parts[parts.length-1];
String firstname = name.replace(lastname, "").trim();
System.out.println("Hello "+firstname+", your last name is: "+lastname);
In this case I am using the trim() function to remove whitespaces at the start and end and just split the string when a white space occurs. Since people can have some middle names and stuff, I just replace the last name out of the raw input string, call trim() on it again and you have everything extracted.
If you really want a substring approach, the following would work:
String lastname = name.substring(name.lastIndexOf(" ")).trim();
String firstname = name.substring(0,name.lastIndexOf(" ")).trim();
You usually don't store the index variables. But each variant would need some sort of error check, you can either use try{} and catch() or check the String before parsing.
Only these lines are required.
String[] nameArr = fullname.split(" ");
String lastN = nameArr[nameArr.length - 1];
int lastIndexOf = fullname.lastIndexOf(lastN);
String firstN = fullname.substring(0, lastIndexOf);
System.out.println(firstN + " " + lastN);
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'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();
}
I have one question regarding about retrieving Barcode data.
Below screen shot is the my java application.
For example, the barcode data have "12345-6789".
I put cursor on "Mo No." and scan barcode, System will read barcode and display on "Mo No." filled as "12345-6789"
But what I want is "12345" in Mo No. and "6789" in Container No. Once I scanned barcode.
How should I implement the code.
Please advice.Thanks.
you can just ignore whatever after dash -
for example:
String barcode="12345-6789";
System.out.println(barcode.substring(0,barcode.indexOf("-"))); //this will only print whatever before first occurance of '-'
OUTPUT:
12345
Use String#split
String toSplit = "12345-6789";
String a;
String b;
//check if string contains your split-char with [string#contains][2])
if(toSplit.contains("-")
{
//split takes RegularExpression!
String[] parts = toSplit.split("-");
a = parts[0]; // =12345
b = parts[1]; // =6789
}
else
{
throw new IllegalArgumentException(toSplit + " does not contain -");
}
I am getting the names as String. How can I display in the following format: If it's single word, I need to display the first character alone. If it's two words, I need to display the first two characters of the word.
John : J
Peter: P
Mathew Rails : MR
Sergy Bein : SB
I cannot use an enum as I am not sure that the list would return the same values all the time. Though they said, it's never going to change.
String name = myString.split('');
topTitle = name[0].subString(0,1);
subTitle = name[1].subString(0,1);
String finalName = topTitle + finalName;
The above code fine, but its not working. I am not getting any exception either.
There are few mistakes in your attempted code.
String#split takes a String as regex.
Return value of String#split is an array of String.
so it should be:
String[] name = myString.split(" ");
or
String[] name = myString.split("\\s+);
You also need to check for # of elements in array first like this to avoid exception:
String topTitle, subTitle;
if (name.length == 2) {
topTitle = name[0].subString(0,1);
subTitle = name[1].subString(0,1);
}
else
topTitle = name.subString(0,1);
The String.split method split a string into an array of strings, based on your regular expression.
This should work:
String[] names = myString.split("\\s+");
String topTitle = names[0].subString(0,1);
String subTitle = names[1].subString(0,1);
String finalName = topTitle + finalName;
First: "name" should be an array.
String[] names = myString.split(" ");
Second: You should use an if function and the length variable to determine the length of a variable.
String initial = "";
if(names.length > 1){
initial = names[0].subString(0,1) + names[1].subString(0,1);
}else{
initial = names[0].subString(0,1);
}
Alternatively you could use a for loop
String initial = "";
for(int i = 0; i < names.length; i++){
initial += names[i].subString(0,1);
}
You were close..
String[] name = myString.split(" ");
String finalName = name[0].charAt(0)+""+(name.length==1?"":name[1].charAt(0));
(name.length==1?"":name[1].charAt(0)) is a ternary operator which would return empty string if length of name array is 1 else it would return 1st character
This will work for you
public static void getString(String str) throws IOException {
String[] strr=str.split(" ");
StringBuilder sb=new StringBuilder();
for(int i=0;i<strr.length;i++){
sb.append(strr[i].charAt(0));
}
System.out.println(sb);
}