I just copied and pasted this code straight from my Uni provided lecture notes:
import java.util.*;
public class Echo {
public static void main (String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Input a line of text");
String message = console.nextLine();
System.out.println("Your input was: "
+ message);
it keeps giving me the error: Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The constructor Scanner(InputStream) is undefined
at Scanner.main(Scanner.java:4)
i think it is reffering to the (System.in); section of code, but I do not know how to fix it.
You named your file Scanner.java, but you should have named it Echo.java. Java requires that file names and public class names be the same.
The specific error: javac thought you were defining a Scanner class, which was conflicting with java.util.Scanner. Had you fixed that, it would have complained about the class/filename mismatch.
import java.util.Scanner;
import java.util.Scanner;
public class Echo {
public static void main (String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Input a line of text");
String message = console.nextLine();
System.out.println("Your input was: "
+ message);
Related
So, I am creating a program in which the user has to enter the body(message) of the email. Now when I display that instead of doing it in a proper way the compiler just displays a long line. I have tried using \n but it doesn't work.
System.out.println("Enter message");
Scanner e4 = new Scanner(System.in);
String message = e4.nextLine();
System.out.println(message);
I have a solution for you. You can keep pushing line after line onto an ArrayList until you see a particular end string. In my example it's "end", but equally it could be "</p>" or something else.
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class Scan {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter here:");
List<String> input = new ArrayList<String>();
while(true) {
String temp = in.nextLine();
if(temp.equals("end"))
break;
input.add(temp);
}
for(String s : input) {
System.out.println(s);
}
}
}
The documentation for nextLine() says that it can throw a nosuchelementexception. But when using the nextLine() to get input for the Scanner as demonstrated in the following code, the nosuchelementexception is not thrown, The only thing that happens is by pressing "Enter" two times the programs just ends. I submitted the same code for an evaluation to an online system, there also the system said that the code throws a nosuchelementexception
What sort of an input would produce a nosuchelementexception?
String input = "";
Scanner sc = new Scanner(System.in);
input += sc.nextLine() + " ";
input += sc.nextLine() + " ";
System.out.println(input);
Here’s an example where the standard input (i.e. System.in) is piped from another application:
echo 'one line only' | java Read
Or read from a file:
java Read <file_with_one_line.txt
Or using interactive user input:
java Read
I am entering one line
Ctrl+D
These examples assume that you’ve compiled the code you’ve posted (wrapped into a class Read) to Read.class in the same directory.
import java.util.Scanner;
class Read {
public static void main(String[] args) {
String input = "";
Scanner sc = new Scanner(System.in);
input += sc.nextLine() + " ";
input += sc.nextLine() + " ";
System.out.println(input);
}
}
javac read.java
I think this is possible when reading files:
I created a new txt-file without any content (test.txt) in it and ran the following code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("test.txt");
Scanner sc = new Scanner(file);
String str = sc.nextLine();
}
}
The result:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at Test.main(Test.java:9)
Edit
It can also appear with System.in because when closing one scanner it appears to also close System.in.
Consider the following code:
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);
sc.nextLine();
sc.close();
sc2.nextLine();
}
}
This throws the following exception:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at Test.main(Test.java:10)
This happens because sc (with access to System.in) was closed. This causes that System.in is not accessible anymore and therefore sc2 doesn't work properly and throws an exception.
So i am currently trying to figure out how my code can read my txt file. My objective is to prompt what ever i have for initialization, then ask me to type a number but 0 to get a message that i have written on my txt file. Then finally by finishing by typing 0 and getting what ever message i have for the finish. I have read online articles but i still have trouble. This is what i have so far:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.ArrayList;
public class FortuneFile
{
static Scanner keyboard;
static int inputLine;
static Scanner inputFile;
static boolean done;
public static void main(String[] args) throws Exception
{
initialization();
while (inputFile.hasNext())
while (!done)
{
mainLoop();
}
finish();
}
public static void initialization() throws Exception
{
Scanner inputFile = new Scanner(new File("FortuneCookie.txt"));
keyboard = new Scanner(System.in);
done = false;
System.out.println("");
System.out.println("Welcome to the Command Box FortuneCookie game!");
System.out.println("====================================================================");
System.out.println("Dare to try your luck?... You could be a Winner or a Looser!");
System.out.println("");
System.out.println("Enter \"0\" if you are scared, or if you are brave, try any number: ");
System.out.println("====================================================================");
}
public static void mainLoop() throws Exception
{
inputLine = inputFile.nextInt();
i++;
if (keyboard.equals("0"))
{
done = true;
}
else
{
{
System.out.println("");
}
System.out.print("Care to try again? ");
System.out.println("");
}
}
public static void finish()
{
System.out.println("====================================================================");
System.out.println("Thanks for playing along. I hope you are not traumatised!");
}
}
Thank you!! :)
There are some problems in your code:
First, You missed declaring i in your mainLoop() method so that it can't compile successfully.
Second, keyboard is a Scanner object which can't be compared with String object 0 by equals()
keyboard is a Scanner object. It can't be compared like String with equals("0").
When you are reading nextInt(), store the value in int variable and compare thar value is 0 or not to end the loop.
You are using keyboard.equals() which is wrong as keyboard is a Scanner object and not a String. You should use keyboard.nextLine() to get the input from the user and store this in a String. So you'll have something like,
String holder = keyboard.nextLine();
An easier way to to this would be to read in the integer using something like,
int holder = keyboard.nextInt();
and then compare this integer with 0 using ==
Check out this link for more information on Scanners in Java;
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Also in initialize() you're making a new local Scanner inputFile that you use in the method. The problem with this is that when you make calls to inputFile outside initialize() you'll run into problems as inputFile outside initialize() is not defined to operate on the file you're using. This is a scope resolution issue.
You'd just want to do, inputFile = new Scanner(new File("FortuneCookie.txt"));
Also make sure that this text file is in the same directory as your project's, otherwise you'll have to describe the complete path.
Make sure you understand your scope resolution as this can cause various problems.
I hope this was helpful!
Good luck!
Try this:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.ArrayList;
public class FortuneFile
{
static Scanner keyboard;
static int inputLine;
static Scanner inputFile;
static boolean done;
static String myMessage;
public static void main(String[] args) throws Exception
{
initialization();
//create an object that reads integers:
Scanner Cin = new Scanner(System.in);
inputLine = Cin.nextInt();
while(inputLine != 0){
System.out.println("");
System.out.print("Care to try again? ");
System.out.println("");
System.out.println("Enter another integer: ");
inputLine = Cin.nextInt();
}
System.out.println(myMessage);
finish();
}
public static void initialization() throws Exception
{
Scanner inputFile = new Scanner(new File("C:/FortuneCookie.txt"));
//keyboard = new Scanner(System.in);
//Read the first line
myMessage = inputFile.nextLine();
//System.out.println(myMessage);
done = false;
System.out.println("");
System.out.println("Welcome to the Command Box FortuneCookie game!");
System.out.println("====================================================================");
System.out.println("Dare to try your luck?... You could be a Winner or a Looser!");
System.out.println("");
System.out.println("Enter \"0\" if you are scared, or if you are brave, try any number: ");
System.out.println("====================================================================");
}
public static void finish()
{
System.out.println("====================================================================");
System.out.println("Thanks for playing along. I hope you are not traumatised!");
}
}
You can remove my main loop and put it in another procedure if you want. I am checking the input with 0. If it is zero, it is the end. If not, it will remain in the loop. I put my file in drive c. You can change your address to your file location. This is the result:
And this was the body of my text file:
I hope this solves your problem. Please let me know if you have any other question.
on one of my Java homework assignments, I am asked to request 2 file names from a user, copy all the text from the first file, and then convert it all to uppercase letters and write it to the second file.
I have my reading and writing methods copied almost exactly as it is in my book, but I can not compile because I am getting the error that the file is not found. I have even tried removing the part where the user assigns the file names and just added the directory and file location myself but I am still getting the FileNotFound Exception.
The errors appear on lines 17 and 32.
Is there something I am doing wrong or is there a problem with Netbeans?
import java.io.*;
import java.util.Scanner;
public class StockdaleUpperfile {
public static void main(String[] args) {
String readFile, writeFile, trash;
String line, fileContents, contentsConverted;
System.out.println("Enter 2 file names.");
Scanner keyboard = new Scanner(System.in);
readFile = keyboard.nextLine();
writeFile = keyboard.nextLine();
File myFile = new File(readFile);
Scanner inputFile = new Scanner(myFile); //unreported exception FileNotFoundException; must be caught or declared to be thrown;
line = inputFile.nextLine();
fileContents=line;
while(inputFile.hasNext())
{
line = inputFile.nextLine();
fileContents+=line;
}
inputFile.close();
contentsConverted = fileContents.toUpperCase();
PrintWriter outputfile = new PrintWriter(writeFile); //Isn't this supposed to create a file if it doesn't detect one?
outputfile.println(contentsConverted);
outputfile.close();
}
}
}
Change the method as
public static void main(String[] args) throws Exception
I have been trying to get 2,3,4 words of a file and this is the code so far. But I am getting some error messages. Can anybody help me please? This is the code:
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
class PrintLines{
public static void main(String[] args) throws FileNotFoundException {
Scanner me = new Scanner(System.in);
System.out.print("File Name: ");
String s = me.next();
File inFile = new File(s);
Scanner in = new Scanner(inFile);
while(in.hasNextLine()){
String[] split=in.split(" ");
System.out.println(split[2]+split[3]+split[4]);
}
in.close();
}
}
But this is the error messages I am getting:
PrintLines.java:18: cannot find symbol
symbol : method split(java.lang.String)
location: class java.util.Scanner
String[] split=in.split(" ");
^
1 error
You are calling split on the Scanner itself; you should be calling it on the nextLine which returns the next line as a String:
String[] split = in.nextLine().split(" ");
If you read the docs then Scanner doesn't have a "split" method, so what you're getting is a compiler error telling you that you're calling a non-existent method.
Try swapping
String[] split=in.split(" ");
for:
String[] split=in.nextLine().split(" ");
The connection between the two methods is hinted at if you read the JavaDoc for hasNextLine(), where the nextLine() method is the next one documented.