I want to be able to find the variable name of an object that has already been checked for if it has been called. And then store this variable name inside either an array or other form of storage for later reference. Here is the code in it's unfinished state.
import java.util.*;
public class errorHelpImproved
{
//Needs Scanner to detect what's in the line
public static Scanner sc = new Scanner(System.in);
//Create a section that reads line by line and finds commands that aren't imported
public static void import1(File file)
{
/*logic note:
read line by line
IF a line contains the keyword Scanner
-Set a flag to check for the keyphrase import java.util.Scanner; OR import java.util.*;
-If neither keyphrase found before the first instance of a keyword public class
+Then Scanner has been called without the package being imported
-If either keyphrase found, stop searching and add this Scanner variable to an array of Scanner variables
*/
File fileStart = new File(file);
do
{
String line = file.nextLine();
if(line.contains(" Scanner "))
{
boolean flagTest=false;
String line2;
do
{
line2 = fileStart.nextLine;
if(line2.contains("import java.util.*;") || line2.contains("import java.util.Scanner;"))
{
flagTest=true;
break;
}
}while(!line2.contains("public class"))
if(flagTest == false)
{
System.out.println("Scanner class has been called without being imported.");
}
else if(flagTest == true)
{
//This is where it would find the word after scanner and store it
}
}
}while(file.hasNext());
}
//Main method gets name of file and passes it to the first check and then from there all other codes will use it
public static void main(Strings [] args)
{
System.out.println("");
}
}
Cause I've thought about this for almost a week and I have no idea how I would go about this.
Scanning .java files for declarations and reading the variable name is more complex than this. You can do it like this, but java code has no requirement for linebreaks. A java application is fine to be written in one line.
The same is true for adding linebreaks. You can add a linebreak wherever a whitespace is allowed in the code.
Scanner sVar;
Scanner
sVar2;
Are both legal java code. Your approach will also match text literals and comments:
/* This is a line with the Scanner variable */
String value = "I am fooling the Scanner code with this line and the comment above";
Reading your comments above: The java compiler does what your teacher asked you for. You can run the java compiler using the javax.tools package. See more information here http://docs.oracle.com/javase/8/docs/api/javax/tools/ToolProvider.html#getSystemJavaCompiler()
Having said that, you must accept restrictions to your approach: The code must be "well formatted" to match your search criteria, otherwise you will have false positives or bad matches.
consider that each line containing " Scanner " is in fact a variable definition or declaration.
The word after Scanner is not a comment and we suppose it to be the variable name.
There is only one Scanner defined per line. (No Scanner sA, sB; or Scanner sA; Scanner sB;)
Furthermore, you store the list of matches in a List for later processing (write to file).
Then the missing code could look like this:
else if(flagTest == true)
{
//This is where it would find the word after scanner and store it
int pos = line.indexOf("Scanner") + "Scanner ".length();
String varStart = line.substring(pos);
pos = varStart.indexOf(";");
String varName = varStart.substring(0, pos).trim();
variableNames.add(varName);
}
This will be less restrictive, if you run it with a regular expression matcher on the line, that has a match-group for the variable name. But I think this is maybe more confusing for your coding level.
A regular expression with a matching group should look like this: .*Scanner\s+([a-zA-Z_$][a-zA-Z_0-9$]*)[\s;].*
Related
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.
I'd like to just see an example with some explanation.
What string functions do I use to compare the objects and does it compare each character or the actual word without any additional letters to it?
Thanks
I tried doing something very similar to this question for a project awhile ago. There are numerous ways to do this in Java, but I used the Scanner class and the File class.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //Just a normal scanner
System.out.println("Please enter in the pathname to the file you want to view.");
String pathname = input.nextLine(); //Pathname to text file
File book = new File(pathname); //Creating a new file using the pathname
if(book.canRead() == false) //If Java cant read the file, this will pop up
{
System.out.println("Your file cannot be read");
}
else if(book.canRead() == true) //If Java can read the file, then this asks for the word to search for
{
System.out.println("Please enter in the word you wish to search for.");
wordToSearchFor = input.nextLine();
wordCounter(book); //Calls the method
}
System.out.println(wordToSearchFor.toLowerCase() + " appeared " + numOfOccurrences + " times in " + pathname);
}
This is the main method where you use the File class to create a file based off of a pathname that you give it EX - C:\Users\alex\Downloads\mobydick.txt
I then check to see if you can read the file, and if you can, then I call a method to analyze the book itself
import java.io.*;
import java.util.Scanner;
public class TextReader
{
private static int numOfOccurrences; //Counter to keep track of the number of occurances
private static String wordToSearchFor; //String field so both methods can access it
/*
* This method takes in the file of the book so the scanner can look at it
* and then does all of the calculating to see if the desired word appears,
* and how many times it does appear if it does appear
*/
public static void wordCounter(File bookInput)
{
try
{
Scanner bookAnalyzer = new Scanner(bookInput); //Scanner for the book
while(bookAnalyzer.hasNext()) //While the scanner has something to look at next
{
String wordInLine = bookAnalyzer.next(); //Create a string for the next word
wordInLine = wordInLine.toLowerCase(); //Make it lowercase
String wordToSearchForLowerCase = wordToSearchFor.toLowerCase();
String wordToSearchForLowerCasePeriod = wordToSearchForLowerCase + ".";
if(wordInLine.indexOf(wordToSearchForLowerCase) != -1 && wordInLine.length() == wordToSearchFor.length())
{
numOfOccurrences++;
}
else if(wordInLine.indexOf(wordToSearchForLowerCasePeriod) != -1 && wordInLine.length() == wordToSearchForLowerCasePeriod.length())
{
numOfOccurrences++;
}
}
}
catch(FileNotFoundException e) //Self explanitory
{
System.out.println("The error is FileNotFoundException - " + e);
System.out.println("This should be impossible to get to because error checking is done before this step.");
}
}
Scanners in Java can be take a File object to analyze, which is the fist thing I do in this method. I then use a while loop and ask the Scanner if there is a word that follows the current word. As long as there is a word, this will continue to run. I then create a String of the current word that the scanner is on to use as a reference to compare against. I then use a method that comes with the String class to make everything lowercase because uppercase and lowercase letters matter.
The first if statement in this method checks if the current word that the scanner has matches what you are searching for using the indexOf method from the String class, which takes some string and looks to see if it exists in another string. The if statement comparison also makes sure that the desired word length is the same as the word length in the book in case you are looking up "the" and it doesnt mark "then" as a word since it contains "the". The second if statement does the same thing, just with your desired word with a period at the end. If you wanted to go the extra mile, you could also check for exclamation points, question marks, commas, and so forth, but I decided to just check for periods.
Every time one of these if statements is correct, I increment a variable by one, and after the scanner runs out of words to search for, I print out the total number of times that certain word appears in a text file.
I want to read words from a text file which looks like:
"A","ABILITY","ABLE","ABOUT","ABOVE","ABSENCE","ABSOLUTELY","ACADEMIC","ACCEPT","ACCESS","ACCIDENT","ACCOMPANY", ...
I read the words using split("\",\"") so I have them in a matrix. Unfortunately I cannot skip reading the first quotation mark, which starts my .txt file, so as a result in my console I have:
"A
ABILITY
ABLE
ABOUT
ABOVE
Do you know how can I skip the first quotation mark? I was trying both
Scanner in = new Scanner(file).useDelimiter("\"");
and parts[0].replace("\"", "");, but it doesn't work.
package list_1;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class exercise {
public static void main(String[] args) throws FileNotFoundException{
File file = new File("slowa.txt");
Scanner in = new Scanner(file).useDelimiter("\""); //delimiter doesn't work!
String sentence = in.nextLine();
String[] parts = sentence.split("\",\"");
parts[0].replace("\"", ""); //it doesn't work!
for (int i=0; i<10 ; i++){
System.out.println(parts[i]);
}
}
}
Strings are immutable which means that you can't change their state. Because of that replace doesn't change string on which it was invoked, but creates new one with replaced data which you need to store somewhere (probably in reference which stored original string). So instead of
parts[0].replace("\"", "");
you need to use
parts[0] = parts[0].replace("\"", "");
Anyway setting delimiter and using nextLine doesn't make much sense because this method is looking for line separators (like \n \r \r\n), not your delimiters. If you want to make scanner use delimiter use its next() method.
You can also use different delimiter which will represent " or ",". You can create one with following regex "(,")?.
So your code could look like
Scanner in = new Scanner(file).useDelimiter("\"(,\")?");
while(in.hasNext()){
System.out.println(in.next());
}
You can use this regular expression. It works for me:
Scanner in = new Scanner(file).useDelimiter("\"(,\")?");
while(in.hasNext()){
System.out.println(in.next());
}
I have this code in Eclipse:
package test;
import java.util.Scanner;
class test{
public static void main(String args[]){
Scanner Input = new Scanner(System.in);
if (Input.equals("payday2")){
System.out.println(Input);
}
}
}
Now when I try to start the code/aplication, it terminates itself.
Any ideas why that happens?
You instantiate the Scanner as a variable named Input but never try to read.
Your condition
if (Input.equals("payday2")){
will only check if the Scanner object is equals to the string "payday2" which will always be false, hence the program terminate.
If you want to read, you need to do Input.nextLine().
I dont know about eclipse, but Netbeans would give a warning "equals on incompatible type" with this line.
Also, you should not name your variable with a capital letter as by convention, only class name should start with a capital.
So your fixed program would be
Scanner input = new Scanner(System.in);
String value = input.nextLine();
if ("payday2".equals(value)) {
System.out.println(value);
}
Notice that I kept the string in a variable to display it as displaying input would call toString of the Scanner object which is probably not what you expected.
Notice that I also compared the string in reverse order which is a good practice to avoid NPE even if not really needed here.
You never read input from the Scanner instance so the application doesnt block
String text = input.nextLine();
if ("payday2".equals(text)) {
...
I think you mean to do:
String in = Input.nextLine();
if(in.equals("payday2"))
{
System.out.println(in);
}
Note: in Java 7 you can do the following:
String in = Input.nextLine();
switch(in)
{
case "payday2":
System.out.println(in)
break;
case "payday the heist":
//...
break;
}
Which makes it much easier to manage different input cases.
I've looked around SO but I can't find anything that is helping. Basically I am writing a piece of code to grab a list of numbers as input. However I want the numbers input with a comma as Delimiter.
Here is my code-snippet.
import java.util.Scanner;
public class TreeUtils {
Scanner inputTreeOne = new Scanner(System.in);
Scanner inputTreeTwo = new Scanner(System.in);
//Changing default whitespace delimiter of Scanners to comma.
inputTreeOne.useDelimiter(",");
}
The problem I'm having is a syntax error with my useDelimiter() method. The error is as follows(from eclipse):
Multiple markers at this line
- Syntax error on token "","", delete this token
- Syntax error on token(s), misplaced
construct(s)
Thanks.
P.S I'm newly registered here, so I'm not sure if this is the right way of putting a question. I hope it's fine.
the code fragments itself are okay but you misplaced them. you didn't define a method inside your class.
try again like this:
public static void main(String[] args) {
Scanner inputTreeOne = new Scanner(System.in);
inputTreeOne.useDelimiter(",");
while (inputTreeOne.hasNext()) {
System.out.println(inputTreeOne.next());
}
}
You haven't included enough code to be sure (update - you have now), but I expect that you put those declarations at the top level of a class; i.e. not within a method.
Like this for example:
import java.util.Scanner;
public class Test {
Scanner inputTreeOne = new Scanner(System.in);
Scanner inputTreeTwo = new Scanner(System.in);
inputTreeOne.useDelimiter(",");
....
}
The first two declarations are syntactically OK.
The line where you call useDelimiter is NOT OK. That is a statement not a declaration, and you cannot put statements at the top level of a class.
Why? Because the Java grammar doesn't allow it!
You most likely need to do the setup of your scanner in a constructor ...
For example:
import java.util.Scanner;
public class Test {
Scanner inputTreeOne = new Scanner(System.in);
Scanner inputTreeTwo = new Scanner(System.in);
public Test() {
inputTreeOne.useDelimiter(",");
}
....
}
Or maybe it would be more appropriate to put all three lines inside a method.
I should also note that it is probably incorrect to create two separacte scanners for the same input stream. You are likely to get into all sorts of trouble with look-ahead characters being buffered by the "wrong" scanner.
Use a single scanner, and (if you need to) set and reset the delimiter between nextXxxx calls, etcetera.
Your code is fine, but it seems you misplaced it within your class.
Check where you put your code, it should be placed within a constructor, method or - very unlikely in your case - static initialization block.
private void foobar() {
// Do some cool stuff...
Scanner inputTreeOne = new Scanner(System.in);
Scanner inputTreeTwo = new Scanner(System.in);
//Changing default whitespace delimiter of Scanners to comma.
inputTreeOne.useDelimiter(",");
// Do some other stuff...
}