Extract letters from file - java

I have a question on how to extract letters from File. This is an example line from the file I read.
ui Parker 8
I read 3 tokens and am supposed to extract 2 letters from the first token but not sure how to do it. The code references 5 attributes which are part of an object that was declared earlier and 3 tokens in the file. The first letter determines if the student is undergraduate or graduate and the second letter determines if the student is instate or out of state.
while(fileScan.hasNext())
{
classStatus = fileScan.next();
if(classStatus.charAt(0) == 'u' || classStatus.charAt(0) == 'U')
{
classStatus= "underGrad";
}
else
{
classStatus= "Grad";
}
studentName = fileScan.next();
resident = fileScan.next();
numberOfCredits = fileScan.nextInt();
double tuitionBill = fileScan.nextDouble();
StudentNode aNode = new StudentNode(classStatus,studentName,resident);

So an important part left out is you are using java.lang.Scanner (the type of fileScan) yeah?
Well, because your file is most likely well organized:
token [space] token [space] token
you can read each line in as a String and then effectively do a split on spaces on each line read in. With Scanner we can accomplish this split through regular expressions, more specifically by using the useDelimiter() method. A good reference is this other SO question for using useDelimiter().
Anyway, to continue, you use fileScan.next() to get each token as a String. Then you use the substring method or charAt method like above to pick out the necessary characters.

Related

How do you go through ArrayList and find what is in the ArrayList using Scanner?

I am making an ArrayList of cars and I am having trouble how to iterate through the ArrayList and print what I ask using a scanner.
Example: I am looking for an Audi in the list, I want it to look through the ArrayList and if it is in the ArrayList print "We have a %s."
This is what I have so far:
public class Main {
public static void main(String[] args) {
ArrayList<String> car = new ArrayList<>();
car.add("Audi");
car.add("Chevrolet");
car.add("Dodge");
car.add("Ford");
car.add("Honda");
car.add("Toyota");
car.add("Volkswagen");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
for(String name: car)
{
if(name == sc){
System.out.printf("We have a %s.", sc);
}
}
}
}
I think that real problem here1 is that you don't have a clear understanding of what a Scanner does.
A Scanner reads characters from a stream (for example System.in) and turns them into various kinds of values; e.g. integers, floating point numbers, strings and so on. The basic model is:
call hasNextXXX to test if there is a XXX to read.
call nextXXX to read a XXX.
So you are trying to get a name of a car manufacturer from the Scanner. Assuming that car manufacturer names don't have spaces in them, what you are reading is a white-space delimited token. The method for reading a token is Scanner::next. It returns the token as a String with any leading or trailing whitespace removed.
Aside: String::nextLine would also work, except that it returns the complete line with all white space entered by the user before or after the name2. If the user enters (for example) Ford with a space after it, then that won't match the value in your car list. To deal with that, you would need to do something like this:
String str = sc.nextLine().trim(); // 'trim' removes leading and
// trailing whitespace; e.g. SP,
// TAB, CR and NL characters.
Once you have the name as a String, you should String::equals to compare it against other strings. Comparing strings using == is incorrect in nearly all circumstances; see How do I compare strings in Java?
For a deeper understanding of Scanner, I recommend that you take the time to read the javadocs.
Your code doesn't do the above. Instead, it reads a line (i.e. str = sc.nextLine()) and doesn't use it. Then it uses == to test if the Scanner is equal to each String in your list. That fails, because a Scanner is not a String.
Aside: in Java, == for a reference type (i.e. for objects) means "is this the same object".
1 - The other possibility is that you didn't read the code that you had written carefully enough.
2 - ... apart from the line separator sequence; i.e. CR, NL or CR + NL. This is removed automatically by nextLine: refer to the javadocs for more details.

Can Scanner.next() return null or empty string?

I'm learning Java coming from other programming languages (Js, C and others..)
I'm wondering if under any circumstances the Scanner.next() method could return (without throwing) an invalid string or less than one character (ie. null or empty string ""). I'm used to double-check user input for any possible unexpected/invalid value, but I wanted to know if testing for null and myString.length() < 1 is always unnecessary or could be useful/needed.
I'm asking in particular when reading from the commandline and System.in, not from other Streams of Files. Can I safely get the first character with myString.charAt(0) from the returned value when reading normally from the terminal input (ie. no pipes and no files, straight from terminal and keyboard)?
I searched the Java SE 9 API Docs and couldn't find mentions about possibly unexpected return values. In case anything goes wrong with input it should just throw an Exception, right?
Example (part of main method without imports):
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a selection (from A to E): ");
String res = keyboard.next();
if (res == null || res.length() < 1) {
// Unnecessary if?
}
Scanner#next can never return null and if the user enters an empty string or a string containing whitespaces only then the method will block and wait for input to scan.
Therefore the if condition is redundant and is not needed at all.
Scanner.next can never return null by looking at its source code. From Scanner.next code
while(true){
...
if (token != null) {
matchValid = true;
skipped = false;
return token;
}
...
}
It can throw NoSuchElementException if no more tokens are available or IllegalStateException if the scanner is closed according to the docs. So your checks are redundant.
Given the following input:
a b c
d e
f
g
The breakdown below shows how a certain sequence of calls to a Scanner object, , will read the above input:
A call to scan.next(); returns the next token, a.
A call to scan.next(); returns the next token, b.
A call to scan.nextLine(); returns the next token, c. It's important to note that the scanner returns a space and a letter, because it's reading from the end of the last token until the beginning of the next line.
A call to scan.nextLine(); returns the contents of the next line, d e.
A call to scan.next(); returns the next token, f.
A call to scan.nextLine(); returns everything after f until the beginning of the next line; because there are no characters there, it returns an empty String.
A call to scan.nextLine(); returns g.

Get input from user in one line without space in java

I am a beiggner in java programming and i have a problem i want to get input from user in one line such as in c++
in c++ if i want to make a calculator i make 2 variable for example a band third is op and make user input them by
cin>>a>>op>>b;
if (op=='+')
{
cout<<a+b<<endl;
}
and so on how to make that in Java ?
i make a try in java but i get Error
and one more question how to make user input a char i try char a=in.next(); but get error so i make it string
code java
Scanner in=new Scanner(System.in);
int a=in.nextInt();
String op=in.nextLine();
int b=in.nextInt();
if (op=="+")
{
System.out.println(a+b);
}
else if (op=="-")
{
System.out.println(a-b);
}
.........
First of all, in Java you compare String with a.equals(b), in you example it would be op.equals("+"). And also, after reading a line it have the line break character (\n), so you should remove it to avoid problems. Remove it using String op = in.nextLine().replace("\n", "");.
And answering the how to read a character part, you can use char op = reader.next().charAt(0)

I want to know how to find a special character in a string

I am programming in Java in Eclipse, I want to ask users to enter their specific ID, Which starts with an uppercase G and has 8 digit numbers. like G34466567. if the user enters an invalid ID it will be an error. how can i separate a valid ID from others?
You can use regex. This pattern checks if the first character is a capital G and there are 8 digits following:
([G]{1})([0-9]{8})$
As you see there are two expressions which are separated by the (). The first says "only one character and this one has to be a capital G". And the second one says, there have to be 8 digits following and the digits can be from 0 to 9.
Every condition contains two "parts". The first with the [] defines which chars are allowed. The pattern inside the {} show how many times. The $ says that the max length is 9 and that there can't be more chars.
So you can read a condition like that:
([which chars are allowed]{How many chars are allowed})
^------------------------\/---------------------------^
One condition
And in Java you use it like that:
String test= "G12345678";
boolean isValid = Pattern.matches("([G]{1})([0-9]{8})$", test);
As you see that matches method takes two parameters. The first parameter is a regex and the second parameter is the string to check. If the string matches the pattern, it returns true.
Create an ArrayList. Ask the user to input the ID, check if it is already there in the list, ignore, otherwise add that ID to the list.
EDIT: For ensuring that the rest 8 characters of the String ID are digits, you can use the regex "\\d+". \d is for digits and + is for one or more digits.
Scanner sc = new Scanner(System.in);
ArrayList<String> IDS = new ArrayList();
char more = 'y';
String ID;
String regex = "\\d+";
while (more == 'y') {
System.out.println("Pleaes enter you ID.");
ID = sc.next();
if (IDS.contains(ID)) {
System.out.println("This ID is already added.");
} else if (ID.length() == 9 && ID.charAt(0) == 'G' && ID.substring(1).matches(regex)) {
IDS.add(ID);
System.out.println("Added");
} else {
System.out.println("Invalid ID");
}
System.out.println("Do you want to add more? y/n");
more = sc.next().charAt(0);
}
Assuming that you save the id as a string, you can check the first letter and then check if the rest is a number.
Ex.
String example = "G12345678";
String firstLetter = example.substring(0, 1); //this will give you the first letter
String number = example.substring(1, 9); //this will give you the number
To check that number is a number you could do the following instead of checking every character:
try {
foo = Integer.parseInt(number);
} catch (NumberFormatException e) {
//Will Throw exception!
//do something! anything to handle the exception.
// this is not a number
}

How to read a string with spaces in Java

I am trying to read a user input string which must contain spaces. Right now I'm using:
check = in.nextLine();
position = name.names.indexOf(check);
if (position != -1) {
name.names.get(position);
} else {
System.out.println("Name does not exist");
}
this just returns various errors.
your question isn't very clear - specfically you like like you are checking that what the person has typed matches a known list, not that it does or doesn't have spaces in it, but taking you at your word:
Read the whole line in, then check using
a) Regex
b) indexof() - if your check is very simple
Possibly also want to do a length check on the input line as well (i.e all lines should be < 255 chars or something) , just to be paranoid
If you are doing more like what you code sample looks like then you do something like
ArrayList<String> KnownListOfNames = .....
if(!KnownListOfNames.Contains(UserEnteredString)){
System.out.println("Name not found");
}
Typically you would also do some basic input validation first - google for "SQL injection" if you want to know more.

Categories

Resources