I'm having a bit of a problem trying to get my code to work. I am working on a project for my computer science class, and I have to get my program to read the file and perform some math. When I tried doing this, the code was not working. I then checked with a friend who wrote the exact same code, and it did not work.
The input .txt file that the program reads looks like this:
2/3,4/5
-1/6,2/4
1/1,1/1
The code I have written looks like this:
import javax.swing.JFileChooser;
import java.util.*;
public class ProjectTest
{
public static void main(String[] args) throws Exception
{
JFileChooser chooserRational = new JFileChooser();
int returnValRational = chooserRational.showOpenDialog(null);
if(returnValRational == JFileChooser.APPROVE_OPTION)
{
System.out.println("You chose to open this file: " + chooserRational.getSelectedFile().getName());
Scanner input = new Scanner(chooserRational.getSelectedFile());
while(input.hasNext() == true)
{
String line = input.nextLine();
String[] output = line.split(",");
String[] output1 = output[0].split("/");
String[] output2 = output[1].split("/");
String a = output1[0];
String b = output1[1];
String c = output2[0];
String d = output2[1];
int int1 = Integer.parseInt(a);
int int2 = Integer.parseInt(b);
int int3 = Integer.parseInt(c);
int int4 = Integer.parseInt(d);
System.out.println(int1 + " " + int2 + " " + int3 + " " + int4);
}
input.close();
}
}
}
When I output just the Strings a, b, c, and d, the code works perfectly fine and outputs the values perfectly. When the code sees Integer.parseInt(a), however, it gives me an error that looks like this:
Exception in thread "main" java.lang.NumberFormatException: For input string: "?2"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at ProjectTest1.main(ProjectTest1.java:33)
Any help would be greatly appreciated.
Because your data file contains an UTF-8 BOM.
You have two alternatives: edit your source data file to remove the BOM, or you can add some code to deal with the BOM. For the first option use Notepad++ and remove the BOM. For the second alternative:
Scanner input = new Scanner(chooserRational.getSelectedFile());
if (input.nextByte() == 0xFE) {
input.nextByte();
input.nextByte();
} else {
input = new Scanner(chooserRational.getSelectedFile());
}
You should replace
String line = input.nextLine();
with
String line = input.next();
since you have multiples groups of data on the same line.
Edit :
I ran your code and did not get the same exception as you. I had a NumberFormatException due to the nextLine call, I now fixed it and it runs with no error. I think like the others that you have an encoding problem. Search on the internet how to display invisible characters on your preferred text editor.
Related
I am trying to use Console class to get input from user but a null object is returned when I call System.console(). Do I have to change anything before using System.console?
Console co=System.console();
System.out.println(co);
try{
String s=co.readLine();
}
Using Console to read input (usable only outside of an IDE):
System.out.print("Enter something:");
String input = System.console().readLine();
Another way (works everywhere):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String");
String s = br.readLine();
System.out.print("Enter Integer:");
try {
int i = Integer.parseInt(br.readLine());
} catch(NumberFormatException nfe) {
System.err.println("Invalid Format!");
}
}
}
System.console() returns null in an IDE.
So if you really need to use System.console(), read this solution from McDowell.
Scanner in = new Scanner(System.in);
int i = in.nextInt();
String s = in.next();
There are few ways to read input string from your console/keyboard. The following sample code shows how to read a string from the console/keyboard by using Java.
public class ConsoleReadingDemo {
public static void main(String[] args) {
// ====
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter user name : ");
String username = null;
try {
username = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("You entered : " + username);
// ===== In Java 5, Java.util,Scanner is used for this purpose.
Scanner in = new Scanner(System.in);
System.out.print("Please enter user name : ");
username = in.nextLine();
System.out.println("You entered : " + username);
// ====== Java 6
Console console = System.console();
username = console.readLine("Please enter user name : ");
System.out.println("You entered : " + username);
}
}
The last part of code used java.io.Console class. you can not get Console instance from System.console() when running the demo code through Eclipse. Because eclipse runs your application as a background process and not as a top-level process with a system console.
It will depend on your environment. If you're running a Swing UI via javaw for example, then there isn't a console to display. If you're running within an IDE, it will very much depend on the specific IDE's handling of console IO.
From the command line, it should be fine though. Sample:
import java.io.Console;
public class Test {
public static void main(String[] args) throws Exception {
Console console = System.console();
if (console == null) {
System.out.println("Unable to fetch console");
return;
}
String line = console.readLine();
console.printf("I saw this line: %s", line);
}
}
Run this just with java:
> javac Test.java
> java Test
Foo <---- entered by the user
I saw this line: Foo <---- program output
Another option is to use System.in, which you may want to wrap in a BufferedReader to read lines, or use Scanner (again wrapping System.in).
Found some good answer here regarding reading from console, here another way use 'Scanner' to read from console:
import java.util.Scanner;
String data;
Scanner scanInput = new Scanner(System.in);
data= scanInput.nextLine();
scanInput.close();
System.out.println(data);
Try this. hope this will help.
String cls0;
String cls1;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
cls0 = in.nextLine();
System.out.println("Enter a string");
cls1 = in.nextLine();
The following takes athspk's answer and makes it into one that loops continually until the user types "exit". I've also written a followup answer where I've taken this code and made it testable.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class LoopingConsoleInputExample {
public static final String EXIT_COMMAND = "exit";
public static void main(final String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter some text, or '" + EXIT_COMMAND + "' to quit");
while (true) {
System.out.print("> ");
String input = br.readLine();
System.out.println(input);
if (input.length() == EXIT_COMMAND.length() && input.toLowerCase().equals(EXIT_COMMAND)) {
System.out.println("Exiting.");
return;
}
System.out.println("...response goes here...");
}
}
}
Example output:
Enter some text, or 'exit' to quit
> one
one
...response goes here...
> two
two
...response goes here...
> three
three
...response goes here...
> exit
exit
Exiting.
I wrote the Text-IO library, which can deal with the problem of System.console() being null when running an application from within an IDE.
It introduces an abstraction layer similar to the one proposed by McDowell.
If System.console() returns null, the library switches to a Swing-based console.
In addition, Text-IO has a series of useful features:
supports reading values with various data types.
allows masking the input when reading sensitive data.
allows selecting a value from a list.
allows specifying constraints on the input values (format patterns, value ranges, length constraints etc.).
Usage example:
TextIO textIO = TextIoFactory.getTextIO();
String user = textIO.newStringInputReader()
.withDefaultValue("admin")
.read("Username");
String password = textIO.newStringInputReader()
.withMinLength(6)
.withInputMasking(true)
.read("Password");
int age = textIO.newIntInputReader()
.withMinVal(13)
.read("Age");
Month month = textIO.newEnumInputReader(Month.class)
.read("What month were you born in?");
textIO.getTextTerminal().println("User " + user + " is " + age + " years old, " +
"was born in " + month + " and has the password " + password + ".");
In this image you can see the above code running in a Swing-based console.
Use System.in
http://www.java-tips.org/java-se-tips/java.util/how-to-read-input-from-console.html
My code is not working. The text file is in the same folder as my classes. I used the pathname, which worked, but I don't think that would work if I send the file to someone else. And converting the Strings to primitive type using parse methods isn't working, either. Not sure what I'm doing wrong. Can anyone help?
Here is my code:
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
public class TestInventory {
public static void main(String[] args) {
// TODO Auto-generated method stub
Inventory movieList = new Inventory();
Scanner inputStream = null;
try{
inputStream = new Scanner(new FileInputStream("movies_db.txt"));
}
catch(FileNotFoundException e){
System.out.println("File not found or could not be opened");
System.exit(0);
}
while(inputStream.hasNextLine()){
String s = inputStream.nextLine();
StringTokenizer st = new StringTokenizer(s, " - ");
String t1 = st.nextToken();
String t2 = st.nextToken();
String t3 = st.nextToken();
String t4 = st.nextToken();
int y = Integer.parseInt(t2);
double r = Double.parseDouble(t4);
int d = Integer.parseInt(t3);
Movie m = new Movie(t1, y, r, d);
movieList.addMovie(m);
}
}
}
And this is the output I get:
run:
Exception in thread "main" java.lang.NumberFormatException: For input string: "America:"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at TestInventory.main(TestInventory.java:29)
C:\Users\customer\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
The error message occurs because you are parsing the String "America:" into parseInt().
All characters in the delim argument are the delimiters for separating tokens. source
That means that instead of splitting the text when ever there is a " - " it will split whenever there is a " " or "-".
I think you would be better of using string.split(String regex). This would allow you to parse " - " and get a String array in return.
You've fallen into one trap with the StringTokenizer class, the second parameter is read as a set of distinct characters to use as a delimiter, not as a string that must be present as a whole.
This means that instead of splitting on the exact string " - ", it will split where-ever there is a space or an -. This means that t2 probably does not contain what you think it will contain.
Assuming each line should always contain 4 tokens, you can test this be checking if st.hasMoreTokens() is true, in which case it has split the string into more parts than you intended.
I wrote this code:
import java.util.Scanner;
public static void main (String[] args){
Scanner scan = new Scanner (System.in);
String inp;
int m;
System.out.println ("Please enter some characters.");
inp = scan.nextLine();
m = inp.length();
System.out.println(" = " + m);
}
If I run that, I get something like this:
Please enter some characters.
12345
= 5
But how can I get the = 5 to be printed on the same line as the characters entered by the user, like below?
Please enter some characters.
12345 = 5
There is no function in standard Java that allows you to easily do this.
You will need to interact with the terminal using ANSI escape codes. This is not supported by all terminals.
You could also use a library that will do this for you, some examples in random order:
Charva
Lanterna
Java Curses Library
just write like this:
System.out.print(" = " + m);
println prints to a new line.
hope it works
System.out.print("Please enter some characters.");
inp = scan.nextLine();
m = inp.length();
System.out.println(" = " + m);
When you print the question, remove the ln part (System.out.print("Please enter....))
This will allow your input to be on the same line as the prompt.
Then you can print System.out.println( inp + " = " + m);
However you can't type something after the input as far as i know but you can echo it.
I have a task to compare lines in two files.. values stores in files as string. I am new to Java so please forgive if there is some silly mistake :)
file1 contains
1044510=>40000
2478436011=>10000
2478442011=>3500
2498736011=>3000
2498737011=>550
2478443011=>330
2478444011=>1,550
File two contains
1044510=>30,097
2478436011=>9,155
2478442011=>2,930
2498736011=>2,472
2498737011=>548
2478443011=>313
2478444011=>1,550
I want to take line one from first file and second file and check if value of line1 from first file is greater than second file or not. (40000>30,097) or not. Dont want to take values before "=>".
I have done a sample code but i am getting error while running.
private static void readfiles() throws IOException {
BufferedReader bfFirst = new BufferedReader(new FileReader(first_list));
BufferedReader bfSecond = new BufferedReader(new FileReader(second_list));
int index = 0;
while (true) {
String partOne = bfFirst.readLine();
String partTwo = bfSecond.readLine();
String firstValue=null;
String secondValue=null;
int firstValueInt;
int secondValueInt;
if (partOne == null || partTwo == null)
{
break;
}
else
{
System.out.println(partOne + "-----\t-----" + partTwo);
firstValue=partOne.split("=>")[1];
secondValue=partTwo.split("=>")[1];
System.out.println("first valueee"+firstValue);
System.out.println("second value"+secondValue);
firstValueInt=Integer.parseInt(firstValue);
secondValueInt=Integer.parseInt(secondValue);
if(secondValueInt>firstValueInt)
{
System.out.println("greater");
}
else
{
System.out.println("lesser");
}
}
}
}
}
This is the exception i get
Exception in thread "main" java.lang.NumberFormatException: For input string: "30,097"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at com.bq.pricefinder.flipkart.findProductDifferenceFromFiles.readfiles(findProductDifferenceFromFiles.java:45)
at com.bq.pricefinder.flipkart.findProductDifferenceFromFiles.main(findProductDifferenceFromFiles.java:18)
The problem here is that you are parsing decimal value as integer.
The exception
java.lang.NumberFormatException: For input string: "30,097"
is clear which says that decimal value 30,097 in an invalid format for an integer.
Use float instead of int, and then compare. Also, sometimes it depends on the locale what decimal symbol is used, it can be , for one country and . for another. Read also THIS.
Integer.parseInt can't work on strings containing non-digits. That's the cause of the NumberFormatException. Use it like this :
firstValueInt=Integer.parseInt(firstValue.replaceAll(",",""));
secondValueInt=Integer.parseInt(secondValue.replaceAll(",",""));
you can get integer only by adding this lines
firstValue = firstValue.replaceAll("[^0-9]", "");
secondValue = secondValue.replaceAll("[^0-9]", "");
then convert it to integer
I am having trouble with a programming assignment. I need to read data from a txt file and store it in parallel arrays. The txt file contents are formatted like this:
Line1: Stringwith466numbers
Line2: String with a few words
Line3(int): 4
Line4: Stringwith4643numbers
Line5: String with another few words
Line6(int): 9
Note: The "Line1: ", "Line2: ", etc is just for display purposes and isn't actually in the txt file.
As you can see it goes in a pattern of threes. Each entry to the txt file is three lines, two strings and one int.
I would like to read the first line into an array, the second into another, and the third into an int array. Then the fourth line would be added to the first array, the 5th line to the second array and the 6th line into the third array.
I have tried to write the code for this but can't get it working:
//Create Parallel Arrays
String[] moduleCodes = new String[3];
String[] moduleNames = new String[3];
int[] numberOfStudents = new int[3];
String fileName = "myfile.txt";
readFileContent(fileName, moduleCodes, moduleNames, numberOfStudents);
private static void readFileContent(String fileName, String[] moduleCodes, String[] moduleNames, int[] numberOfStudents) throws FileNotFoundException {
// Create File Object
File file = new File(fileName);
if (file.exists())
{
Scanner scan = new Scanner(file);
int counter = 0;
while(scan.hasNext())
{
String code = scan.next();
String moduleName = scan.next();
int totalPurchase = scan.nextInt();
moduleCodes[counter] = code;
moduleNames[counter] = moduleName;
numberOfStudents[counter] = totalPurchase;
counter++;
}
}
}
The above code doesn't work properly. When I try to print out an element of the array. it returns null for the string arrays and 0 for the int arrays suggesting that the code to read the data in isn't working.
Any suggestions or guidance much appreciated as it's getting frustrating at this point.
The fact that only null's get printed suggests that the file doesn't exist or is empty (if you print it correctly).
It's a good idea to put in some checking to make sure everything is fine:
if (!file.exists())
System.out.println("The file " + fileName + " doesn't exist!");
Or you can actually just skip the above and also take out the if (file.exists()) line in your code and let the FileNotFoundException get thrown.
Another problem is that next splits things by white-space (by default), the problem is that there is white-space on that second line.
nextLine should work:
String code = scan.nextLine();
String moduleName = scan.nextLine();
int totalPurchase = Integer.parseInt(scan.nextLine());
Or, changing the delimiter should also work: (with your code as is)
scan.useDelimiter("\\r?\\n");
You are reading line so try this:
while(scan.hasNextLine()){
String code = scan.nextLine();
String moduleName = scan.nextLine();
int totalPurchase = Integer.pasreInt(scan.nextLine().trim());
moduleCodes[counter] = code;
moduleNames[counter] = moduleName;
numberOfStudents[counter] = totalPurchase;
counter++;
}
String code = scan.nextLine();
String moduleName = scan.nextLine();
int totalPurchase = scan.nextInt();
scan.nextLine()
This will move scanner to proper position after reading int.