How to individually read strings from a line - java

I want to be able to distinguish the user's input using spaces, where each string they input in one line is used for something different.
Specifically, each word they input is used in a method where I add an item to a list. The user will type 'add' followed by the item's type and age.
I have just messed around trying to figure something out but I am just lost.
if (input.equals("add")) {
scan.next(); ??
}
After the user types 'add', they then input a type and age for a vehicle that they want to add to a list. For example, 'car 7' may be typed so a new item in a list can be made, and 'car' will be its type and '7' will be its age.
To note: age is an int.

If the user enters:
car 7
all you need to do to read that line is:
String words[] = scan.nextLine().split(" ");
Now you have an array that contains the words of that line. For eg: words[0] would contain car, words[1] would contain 7, etc.

You can also read them one at a time as well as change the delimiter. Here are several examples.
String text = "The quick brown fox jumped over the lazy dog";
Scanner scan = new Scanner(text);
while (scan.hasNext()) {
System.out.print(scan.next() + " ");
}
System.out.println();
And this one changes the delimiter between words. You can specify a regular expression pattern or a simple String.
text = "The:quick,+-brown::::fox:.:jumped++over,,,,the,+,+lazy---dog";
scan = new Scanner(text);
// regular expression delimiter. Any combo of one or more of the chars.
scan.useDelimiter("[:,.;+-]+");
while (scan.hasNext()) {
System.out.print(scan.next() + " ");
}
System.out.println();

Related

My Java program for removing special characters and white space from user input of name fails when I test it with spaces

I'm a student and am working on an assignment that has us trying a few techniques we haven't covered. Removing special characters and spaces from user input, I figured out how to remove the special characters but when I insert a space in my name when I try my program, my name is returned to me missing whatever letters were after the space. Like, "Pat ricia" becomes "Pat". I had to go with a different technique for removing special characters because "replaceAll" didn't work for me there, and it isn't working for me with removing white space. Can I have another set of eyes to tell me what I'm missing?
package edu.gmc.Course_Project;
import java.util.Scanner;
public class Input_Name {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//asking for user input
System.out.print("enter your name: ");
String name = scan.next();
//Java won't do all this at once (2 step process) so I'm converting the whole name to lower case first
name=name.toLowerCase();
//now to get the first character
char first=name.charAt(0);
//and changing it to upper case
first=Character.toUpperCase(first);
String newName="";
newName+=first;
//I'm not really sure about this part, but it has to do with the length...without it, my name was returned to me as "P"
for(int i=1;i<name.length();i++)
{
//this part ignores anything other than A-Z or a-z...I had a different method earlier but I couldn't get it to work properly
char ch=name.charAt(i);
if(ch>='a' && ch<='z')
{
newName+=ch;
}
}
//removing white spaces
newName = newName.replaceAll("\\s+", "");
//the program is complete, now what does it do?
System.out.println("your name is "+newName);
}
}
The reason why your program was not working was because you was using String name = scan.next(); at the very start of your program, this command will store the next string inputted, and because there is a space it is simply storing the first string before the space, instead you need to use String name = scan.nextLine(); as it will store the entire line including white space and additional strings,

Read integers and string from a list using a scanner

I am reading a string from stdin that's formatted as a list. I am using the information from the string to create objects.
An example input string would be formatted as follows:
1 apple, 3 bananas, 2 pears
I want to read that line a create objects as I go, but my biggest issue is properly reading the line to get the number of items, followed by them item itself while also skipping whitespace and commas.
I have tried the following:
Scanner input = new Scanner(System.in);
input.useDelimeter(",|\\s");
while(input.hasNext()){
int numItems = input.nextInt();
String item = input.next();
// create object and add to object array
}
Which works for the first iteration (1 apple) but fails on the second with a type mismatch. Can anyone suggest a fix or alternate solution?
Thanks!
,|\\s declares two separate delimiters. Those delimiters can be matched in text "apple, 3" twice:
comma after apple
space before 3
apple, 3
^^
12
so we split that text at two separate (middle) places, which means we split it into 3 tokens:
"apple",
"",
"3".
When in next iteration (after calling input.next() which consumes apple) you are calling input.nextInt() Scanner tries to parse second token as int, but since it finds empty string it is throwing exception.
One of solutions would be treating [space] or ,[space] as single delimiter. You can achieve it by making comma optional:
input.useDelimiter(",?\\s");
Demo:
Scanner input = new Scanner("1 apple, 3 bananas, 2 pears");
input.useDelimiter(",?\\s");
while(input.hasNext()){
int numItems = input.nextInt();
System.out.println(numItems);
String item = input.next();
System.out.println(item);
System.out.println("----");
}
Output:
1
apple
----
3
bananas
----
2
pears
----
You can spilt the input String using delimiter "," and get following output after using trim() method.
1 apple
3 bananas
2 pears
Here is the code:
String [] array1 = input.nextLine().split(",");
for(int i=0; i<array1.length; i++){
System.out.println(array1[i].trim());
}
Edit: You can further split the Strings inside for loop using delimiter space, to get the desired output.

Using a Scanner with a String Splitter

I am trying to use a string splitter to display user input e.g. 1,2 coordinates to display on a console. I don't get any errors when I run my code. However, my attempt to use the splitter does not seem to work.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a row and column number at which to shoot (e.g., 2,3): ");
String[] coordinates = scanner.nextLine().split(",");
if (coordinates.length != 2) {
System.out.println("Please enter coordinates in the correct format.");
System.out.println("\nPlayer 1 Please take your turn:");
continue;
}
System.out.println("\nEnter Mine location:");
System.out.println("\nPlease Enter x position for your Mine:");
System.in.read(byt);
str = new String(byt);
row = Integer.parseInt(str.trim());
System.out.println("\nPlease Enter y position for your Mine:");
System.in.read(byt);
str = new String(byt);
col = Integer.parseInt(str.trim());
Your use of System.in.read(...) is dangerous code and is not doing what you think it's doing:
System.in.read(byt); // *****
str = new String(byt);
row = Integer.parseInt(str.trim());
Instead use a Scanner, something that you already have, and either call getNextInt() on the Scanner, or get the line and parse it.
Also, you never use the Strings held in the coordinates array -- why get the Strings if you are ignoring them?
You ask about:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a row and column number at which to shoot (e.g., 2,3): ");
str = scanner.nextInt().split(",");
but then see that the compiler won't allow this since you're trying to call a method on the int primitive that scanner.nextInt() returns.
My recommendation to use Scanner#nextInt() was as a replacement for you misuse of System.in.read(...). If instead you want the user to enter two numbers on one line, separated by a comma, then you're best bet is to use String.split(","), although, I think it might be better to use String.split("\\s*,\\s*") to get rid of any white space such as spaces hanging about. This way the split should work for 1,1 as well as 1, 2 and 1 , 2, and then you can parse the items held in the array via Integer.parseInt(...).

Ignore space, blanks

Does anybody know how i could make scanner ignore space? I wanna type a first and second name, but scanner wont let me, i want to save the full name
String name;
System.out.print("Enter name: ");
name = scan.next(); //Ex: John Smith
System.out.println(name);
Edit:
New problem.. While using nextLine in my extended program, nextLine just ignores the whole question and moves on without a chance to scan the name.
Scanner#next() splits lines around whitespace. Scanner.nextLine() does not, therefore leaving spaces in.
name = scan.nextLine(); //Ex: John Smith
Well, first your System.out.print(); call is flawed. Everything inside must be inside quotations
System.out.print("Enter name: ");
scan.next() gets the next character in the stream, whereas scan.nextLine() gets the next line (terminated by an EOL character), which may be more helpful to you.
After that, you can create an array of words, like
String[] broken = name.split(" ");
which will place into broken all of the words that you've typed in delimited by spaces.
Then you can go something like
for(int i = 0; i < broken.size; i++)
{
System.out.print(broken[i] + " ");
}
System.out.println();
Scanner.next delimits using whitespaces, to read a full line you can use:
name = scan.nextLine();
use scanner.nextLine() which reads full line, instead of scan.next();
Example:
name = scan.nextLine();
Read oracle documentation for Scanner class for available methods.
sounds like you want to read the entire line (minus the line ending). if someone enters, "helen r. smith", you can read the line in with:
name = scan.nextLine();
YOU CAN DO LIKE THIS
import java.util.*;
class scanner2
{
public static void main(String args[])
{
Scanner in= new Scanner(System.in);
System.out.println("enter the name");
String name= in.nextLine();//for name with spaces with more than one word or for one word.
System.out.println("enter single word");
String rl= in.next();//single word name
System.out.println("name is "+name+" rl is "+rl);
}
}
Execute it you will get your answer.

Algorithm to output the initials of a name

I have just started the java programming and at the moment I am doing the basic things. I came across a problem that I can't solve and didn't found any answers around so I thought you might give me a hand. I want to write a program to prompt the user to enter their full name (first name, second name and surname) and output their initials.
Assuming that the user always types three names and does not include any unnecessary spaces. So the input data will always look like this : Name Middlename Surname
Some of my code that I have done and stuck in there as I get number of the letter that is in the code instead of letter itself.
import java.util.*;
public class Initials
{
public static void main (String[] args)
{
//create Scanner to read in data
Scanner myKeyboard = new Scanner(System.in);
//prompt user for input – use print to leave cursor on line
System.out.print("Please enter Your full Name , Middle name And Surname: ");
String name = myKeyboard.nextLine();
String initials1 = name.substring(0, 1);
int initials2 = name.
//output Initials
System.out.println ("Initials Are " + initials1 + initials2 + initials3);
}
}
Users will enter a string like
"first middle last"
so therefore you need to get each word from the string.
Loot at split.
After you get each word of the user-entered data, you need to use a loop to get the first letter of each part of the name.
First, the nextLine Function will return the full name. First, you need to .split() the string name on a space, perhaps. This requires a correctly formatted string from the user, but I wouldn't worry about that yet.
Once you split the string, it returns an array of strings. If the user put them in correectly, you can do a for loop on the array.
StringBuilder builder = new StringBuilder(3);
for(int i = 0; i < splitStringArray.length; i++)
{
builder.append(splitStringArray[i].substring(0,1));
}
System.out.println("Initials Are " + builder.toString());
Use the String split() method. This allows you to split a String using a certain regex (for example, spliting a String by the space character). The returned value is an array holding each of the split values. See the documentation for the method.
Scanner myKeyboard = new Scanner(System.in);
System.out.print("Please enter Your full Name , Middle name And Surname: ");
String name = myKeyboard.nextLine();
String[] nameParts = name.split(" ");
char firstInitial = nameParts[0].charAt(0);
char middleInitial = nameParts[1].charAt(0);
char lastInitial = nameParts[2].charAt(0);
System.out.println ("Initials Are " + firstInitial + middleInitial + lastInitial);
Note that the above assumes the user has entered the right number of names. You'll need to do some catching or checking if you need to safeguard against the users doing "weird" things.

Categories