I am trying to build a GUI app, which would read a text file on the press of a button
and then save contents of this file to a string. My current code, I basically tried to adapt my console code for the gui, but it doesnt seem to work. Here is my button code:
private void convertButtonActionPerformed(java.awt.event.ActionEvent evt) {
Scanner user_input = new Scanner(tempTextField.getText());
String seq1 = user_input.next();
Scanner scanner = new Scanner(new File(seq1));
scanner.nextLine();
String content = scanner.useDelimiter("\\Z").next();
int N = content.length();
textarea.append("Length of the input string is: "+N);
}
textarea = JtextArea
tempTextField = JTextField
Thank you.
edit: I'm using netbeans IDE
You must handle the exception from Scanner scanner = new Scanner(new File(seq1)):
private void convertButtonActionPerformed(java.awt.event.ActionEvent evt)
{
Scanner user_input = null;
Scanner scanner = null;
try
{
user_input = new Scanner(tempTextField.getText());
String seq1 = user_input.next();
scanner = new Scanner(new File(seq1));
scanner.nextLine();
String content = scanner.useDelimiter("\\Z").next();
int N = content.length();
textarea.append("Length of the input string is: "+N);
}catch(FileNotFoundException e)
{
e.printStackTrace();
}finally
{
//always close scanner
if(user_input != null)
user_input.close();
if(scanner != null)
scanner.close();
}
}
These are known as 'Checked Exceptions'. Here, the compiler would force you to handle such code in try/catch block, i.e to Report the Exception, only then you can move forward for execution.
Related
I am having problem in taking a hole paragraph as input in java using System.in and storing it in an array. but problem is with while loop is not ending and program stuck in the loop. i have tried many methods but loop is not ending.
Scanner sc = new Scanner(System.in);
ArrayList < String > al = new ArrayList<>();
System.out.print("Please Enter Paragraph + \n");
while (!(sc.equals(null))) {
al.add(sc.next());
}
Scanner sc = new Scanner(System.in);
String para = sc.nextLine();
int x = 0;
while (para != null) {
if (sc.hasNextLine()) {
ParaArray[x] = para;
para = sc.nextLine();
x++;
} else {
para = null;
}
}
sc is a Scanner object. When you compare sc with null, you will never get true because sc could never be null. Also, your code seems to have a lot of errors. Your question is also unclear. Please provide a proper question...
-Thanks
Tejan Gandhi
Dt: 29th July (After reading your comment):
There are 2 parts of code, one which scans characters and another scans lines.. Because the first "while" loop compares sc (which is a Scanner object) it can never be null and loop can never end.. So instead of doing
sc.equals(null)
sc.hasNext()
Tell me if that works for you.
when you use "sc.hasNextline",you should put"Scanner sc= new Scanner(System.in); " before your judgment statement,just like this:
int num = 0;
while (true) {
System.out.println("Please input a number");
Scanner sc = new Scanner(System.in);
if (sc.hasNextDouble()) {
num = sc.nextDouble();
} else {
System.out.println("It is not a number,please try again!");
System.out.println("============================");
}
}
After your first loop you have already an array of paragraphs so why it is not clear why you need a second loop.
I've also put the scanner in a try () because Scanner is Closeable so it is closed at the end.
import java.util.ArrayList;
import java.util.Scanner;
public class ScanTest {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
ArrayList<String> al = new ArrayList<>();
while (true) {
System.out.println("Please Enter Paragraph + \n");
String readLine = sc.nextLine();
if (readLine.length() == 0) {
break;
}
al.add(readLine);
}
System.out.println("result:"+al);
}
}
}
I have a text file with the following line define : Hi 0x01. I'm trying to read in the word Hi and store it in its own variables and 0x01 in its own variable.The problem I'm having is that i seem to be able to read in Hi, but i cant read in0x01`.Here is my code
File comms =new File("src/Resources/com.txt");
try (Scanner scan = new Scanner(comms)) {
while (scan.hasNext()) {
String line = scan.nextLine();
Scanner sc = new Scanner(line);
sc.useDelimiter("\\s+");
try {
String comm1 = sc.next();
// System.out.println(comm1);
int value =sc.nextInt();
System.out.println(value);
sc.close();
} catch (Exception ef){
}
I honestly have no idea what you're trying to do here. You'd better scan it once:
File comms = new File("src/Resources/com.txt");
try(Scanner scan = new Scanner(comms)) {
while(scan.hasNext()) {
String line = scan.nextLine();
String[] words = line.split(" ");
System.out.println(words[0]); // "Hi"
System.out.println(words[1]); // "0x01"
}
}
catch(Exception e) {
}
Now, having these in separate strings you can do anything in the world with it like converting words[1] to int.
I am advised to use a while loop the Scanner method hasNextLine() and
in the while loop body, call the Scanner method nextLine(), and add the returned String to the ArrayList of Strings. I am new to Java so please keep that in mind. I'm not exactly sure if this is right, but this is what I have gotten so far:
Scanner input = new Scanner(new File(""));
while(input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
With this code you can:
prompt a user for a file name.
read the file line by line using the Scanner class.
add each line to an ArrayList of Strings.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerReadFile {
public static void main(String[] args) {
// Location of file to read
Scanner x = new Scanner(System.in);
System.out.println("Enter a filename: ");
String fileName = x.nextLine();
File file = new File(fileName);
ArrayList<String> lines = new ArrayList<String>();
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lines.add(line);
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Okay, so i have an issue trying to update a line or sentence in a text file.
The way my program works is this: If a user enters a question the program searches the text file for that exact question(lets say is n). The answer to the question would be on the following line(n + 1). My issue is trying to update the following line(n + 1) to some new line entered by the user.
I keep getting a Exception in thread "main" java.util.NoSuchElementException: No line found when i try to update the line in the text file. my removedata() is where i am trying to update the line of text.
Here is my code
public static void removedata(String s) throws IOException {
File f = new File("data.txt");
File f1 = new File("data2.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;
while ((line = br.readLine()) != null) {
if (line.contains(s)) {
System.out.println("Enter new Text :");
String newText = input.readLine();
line = newText;
System.out.println("Thank you, Have a good Day!");
}
pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
public static void parseFile(String s) throws IOException {
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
Scanner forget = new Scanner(System.in);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
System.out.println(scanner.nextLine());
System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
removedata(scanner.nextLine()); // NoSuchElementException
// error
} else if (yellow.equals("no")) {
System.out.println("Have a good day");
// break;
}
}
}
}
public static void getinput() throws IOException {
Scanner scanner = new Scanner(System.in);
String input = null;
/* End Initialization */
System.out.println("Welcome ");
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
parseFile(input);
}
public static void main(String args[]) throws ParseException, IOException {
/* Initialization */
getinput();
}
My text file is :
what is the textbook name?
the textbook name is Java
how is the major?
the major is difficult
how much did the shoes cost?
the shoes cost ten dollars
Can someone help me solve this issue?
Change the code in the if block in parsefile to
String temp = scanner.nextLine();
System.out.println(temp);
System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
removedata(temp); // NoSuchElementException
// error
} else if (yellow.equals("no")) {
System.out.println("Have a good day");
// break;
}
for an explanation why this works, look at Nick L.s answer.
The problem is here:
while (scanner.hasNextLine()) { //(1)
final String lineFromFile = scanner.nextLine(); //(2)
if (lineFromFile.contains(s)) { //(3)
System.out.println(scanner.nextLine()); //(4)
//....
String yellow = forget.nextLine(); //(5)
if (yellow.equals("yes")) {
removedata(scanner.nextLine()); //(6)
}
}
//....
}
First of all, you are correctly iterating the scanner lines checking whether there is a line (1). Now, you are getting the first line of the scanner on (2), but if the condition (3) succeeds, you are retrieving the next line again at (4) inside System.out.println(....). Same thing applies to (5) and (6) accordingly.
Now, imagine that you have reached the end of file at (2) and the condition at (3) succeeds. You will receive an exception of no such line, as you logically have. The same can happen at (5) and (6).
Each call of the nextLine(), will get the next line of the file opened on the stream.
I suggest that you do one readline inside the loop, then apply the received string when needed.
I'm trying to make an ArrayList that takes in multiple names that the user enters, until the word done is inserted but I'm not really sure how. How to achieve that?
ArrayList<String> list = new ArrayList<String>();
String input = null;
while (!"done".equals(input)) {
// prompt the user to enter an input
System.out.print("Enter input: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// read the input from the command-line; need to use try/catch with the
// readLine() method
try {
input = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read input!");
System.exit(1);
}
if (!"done".equals(input) && !"".equals(input))
list.add(input);
}
System.out.println("list = " + list);
I would probably do it like this -
public static void main(String[] args) {
System.out.println("Please enter names seperated by newline, or done to stop");
Scanner scanner = new Scanner(System.in); // Use a Scanner.
List<String> al = new ArrayList<String>(); // The list of names (String(s)).
String word; // The current line.
while (scanner.hasNextLine()) { // make sure there is a line.
word = scanner.nextLine(); // get the line.
if (word != null) { // make sure it isn't null.
word = word.trim(); // trim it.
if (word.equalsIgnoreCase("done")) { // check for done.
break; // End on "done".
}
al.add(word); // Add the line to the list.
} else {
break; // End on null.
}
}
System.out.println("The list contains - "); // Print the list.
for (String str : al) { // line
System.out.println(str); // by line.
}
}
String[] inputArray = new String[0];
do{
String input=getinput();//replace with custom input code
newInputArray=new String[inputArray.length+1];
for(int i=0; i<inputArray.length; i++){
newInputArray[i]=inputArray[i];
}
newInputArray[inputArray.length]=input
intputArray=newInputArray;
}while(!input.equals("done"));
untested code, take it with a grain of salt.
ArrayList<String> names = new ArrayList<String>();
String userInput;
Scanner scanner = new Scanner(System.in);
while (true) {
userInput = scanner.next();
if (userInput.equals("done")) {
break;
} else {
names.add(userInput);
}
}
scanner.close();