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...
}
Related
I'm pretty new to Java coming from Python so please pardon my retardedness. I'm trying to make a simple if statement and it won't work :(. It ignores the if statement and goes straight else.
I've tried to use .contains and .equalsIgnoreCase in the if statement.
package me.johnminton;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String species_animal;
System.out.println("Please enter your species: ");
species_animal = user_input.next();
if (species_animal.contains("Erectus")) {
System.out.println("random input statement");
}
else
{
System.out.println("okay");
}
}
}
I'm hoping for it output "random input statement" if I input Erectus in the first input. But instead, it goes straight to the else and outputs "okay".
The next() method just fetches a single word from the scanner, although you can change that behaviour by specifying a delimiter for the scanner.
In your case, if you type Eructussian or something similar, you'll get the result you want, but if you type Home Erectus, you won't.
I suspect you meant to use nextLine() instead of next(), which fetches an entire line of text.
The problem is that your scanner isn’t finishing without getting a return key. Try ‘user_input.nextLine()’ instead of ‘user_input.next()’
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;].*
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 am trying to make a Java code that enables the user to input any number and the Java makes a triangle out of that number using *
My code is not compiling, but I think I've finally almost got it down. The only problem is, that it is not recognizing scanf.
Here is my code:
import java.util.Scanner;
class triangle
{
public static void main(String[] args)
{
char print='*';
int row,col;
int noOfRows;
System.out.printf("Enter number of rows to be printed\n");
scanf("%d",noOfRows);
{
for(col=1;col<=row;col++)
{ // this brace is useless, since there is only one statement in this for loop
System.out.printf("%c",print);
} // same for this one
System.out.printf("\n");
}
}
}
How can I fix this?
scanf() and printf() are supported by C and C++ in java:
1. BufferedReader or Scanner for reading from console(System.in).
2. print() or println() for printing to console.(System.out).
You need to declare a new object of the scanner.
Also, to print, is System.out.println("");
You should use Scanner class like this: Scanner scanner = new Scanner(System.in); and do something like this:
System.out.println("Enter number of rows");
noOfRows = scanner.nextInt();
My friend, you use scanf in "C"of "C++" in java we use System.in
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.