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
Related
So I am trying to make the program ask the user the following and get the following answer:
For example:
Type a 2nd Sentence Below:
This is a book (user inputs this)
Choose what string of characters do you want to replace:
book (user inputs this)
Choose what new string will be used in the replacement:
car (user inputs this)
The text after the replacement is: This is a car.
import java.util.*;
import java.util.Scanner;
public class StringManipulation {
public static void main(String[]args) {
/*This is where the user can type a second sentence*/
System.out.println("Type a 2nd Sentence Below:");
Scanner sd = new Scanner(System.in);
String typingtwo = sd.nextLine();
String sending;
/*Here the program will tell the user a message*/
System.out.println("This is your sentence in capital letters:");
sending = typingtwo.toUpperCase();
System.out.println(sending);
/*Here the program will tell the user another message*/
System.out.println("This is your sentence in lower letters:");
sending = typingtwo.toLowerCase();
System.out.println(sending);
System.out.print("Your Token Count:");
int FrequencyTwo = new StringTokenizer(sending, " ").countTokens();
System.out.println(FrequencyTwo);
String charactertwo = new String(typingtwo);
System.out.print("Your Character Length:");
System.out.println(charactertwo.length());
String repWords;
String newWord;
String nwords;
String twords;
System.out.println("Choose what string of characters do you want to
replace");
repWords = sd.next();
System.out.println("Choose what new string will be used in the replacement");
nwords = sc.next();
twords = typingtwo.replace(repWords,nwords);
System.out.printf("The text after the replacement is: %s \n",nwords);
}
}
I have tried everything but for some reason I keep getting the word that they chose at the end only. Pleas help!
try using Scanner.nextLine instead of Scanner.next
refer to the Java API documentation to understand the difference between the two
Here is another problem:
twords = typingtwo.replace(repWords,nwords);
System.out.printf("The text after the replacement is: %s \n",nwords);
You are printing nwords instead of twords.
Two errors i could see.
nwords = sc.next(); here it should give compilation error as scanner instance name is sd.
You are trying to print nwords at the end. it should be "twords".
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 ]
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 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
So , im having a piece of trouble here , tried with tutorials to fix it but nothing really helped me out saw something about printout string 0,1 etc but didnt work eather.
What the program does atm : Asks user for first/last name and prints it out first +last name
what i want it to do is print out the intisials of the users first and last name, any ideas how to fix this? Please help , Thanks in advance!
My code looks like this atm
package com.example.sträng.main;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
String firstName,
lastName;
//Create scanner to obtain user input
Scanner scanner1 = new Scanner( System.in );
//obtain user input
System.out.print("Enter your first name: ");
firstName = scanner1.nextLine();
System.out.print("Enter your last name: ");
lastName = scanner1.nextLine();
//output information
System.out.print("Your first name is " + firstName + " and your last name is "+ lastName);
}
}
You get the 21st character from a String using String.charAt(21).
How to get the initials, I leave as an excercise for you.
Please note, that char is a strange datatype in Java. It represents a character, but works like a number, that's why you get a strange number if you "concatenate" two chars. If you want to create a String out of chars, you have some options, such as:
char c1;
char c2;
String str = "" + c1 + c2;
or
char c1;
char c2;
String str = new String(new char[] {c1, c2});
String firstInitial = firstName.substring(0,1);
String secondInitial = lastName.substring(0,1);