I am trying to create an array using data from a file - java

This is what I have so far....
/**
* #param args
*/
public static void main(String[] args) {
final String DATA_FILE = "payroll_problem.txt";
Scanner scan = null;
try
{
scan = new Scanner(new File(DATA_FILE));
}
catch (FileNotFoundException e)
{
System.err.printf("Could not open file \"%s\".\n", DATA_FILE);
}
int [] arr = new int[scan.nextInt()];
for(int i = 0; i < arr.length; i++)
{
arr[i] = scan.nextInt();
System.out.print(arr[i]);
}
scan.close();
}
I keep getting error code
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at fvse.main(fvse.java:22)
The five ints stand for how many hours the person has worked from Monday-Friday. Here is the data file.
Mohnan Maria 8 8 8 9 8 10.01
Blue Shelly 8 10 8 8 6 10.00
Black 8 8 8 8 8 23.0
Fortuna Jorge 5 5 5 5 5 10.10
Jones Mitchel 10 5.5 10 10 10 15.05
Olafson Sven 10 10 10 10 10 10.00
Cruz Astrid 1 1 1 1 1 20.50.3
Adler Irene 10 12 8 8 8 22.50

The problem happen because you call scan.nextInt() but your input file actually contains string/characters.
Either add the integer indicating the number of lines on the top of your input file, or change your code read by line (eg: using BufferredReader.readLine())
If you choose the former, make sure you also read the first and last name using two invocation of scan.next()

You are reading your file for integers, but more than likely that file is filled with strings or characters.
Edit: Try scanning for lines or characters, or just using a FileInputStream, and then parsing the data once it's been loaded in.
Edit: Now that i've seen your data file, I would read in the file using standard file input practices (check out http://www.javapractices.com/topic/TopicAction.do?Id=42 if you need a tutorial on that). Then split the string based on spaces, and go through each string in your new string array and handle the data. The first 2 strings being names, and then integers until you get another name, or the end of the string.

Related

How to take input in java where array length is not defined?

My input is in this format:
1 2 3 4 5 6
Alice
The array length is not known.
I coded it this way:
import java.util.*;
public class Main
{
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int i=0;
while(sc.hasNext()){
arr.add(sc.nextInt());
}
String player = sc.nextLine();
}
}
But I am getting this error.
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:17)
Thanks in advance.
The reason you are seeing java.util.InputMismatchException is because you provided input "Alice" to the statement sc.nextInt(), and the scanner is telling you that it doesn't know how to convert a java.lang.String input to an int (which is the return type of nextInt()).
Here's a very simple example that reproduces the same behavior:
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
If you run those two lines and enter a non-integer, like "d", it will throw an exception:
d
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at a91.main(a91.java:6)
To fix it, you need to replace nextInt() with something that is tolerant of non-numeric input, possibly nextLine(). Here is a (very) simple example showing how that could work. Note this is just highlighting the behavior you're asking about, namely: how to address InputMismatchException. As with your original program, there is no loop termination – it will run forever (until you quit the program).
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
while (sc.hasNext()) {
String s = sc.nextLine();
System.out.println("got this: " + s);
}
1 2 3 4 5 6
got this: 2 3 4 5 6
Alice
got this: Alice
You should use hasNextInt to check for integer input. Once no more integers, then just use next() to read the player.
List<Integer> arr = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt()){
arr.add(sc.nextInt());
}
String player = sc.next();
arr.forEach(System.out::println);
System.out.println(player);
Example input's supported
10 20 30 40 50 60 70
Alice
10 20 30 40
50 60 70 Alice
10 20 30
40
50
60 70 Alice
10 20 30
40 50
60 70
Alice
output
10
20
30
40
50
60
70
Alice

how to get the final output without pressing enter?

In the below code when i enter the input as***(i just don't enter the input one by one instead i copy and paste the entire input)***
4
101
1111
00110
111111
i am supposed to get
5
15
6
63
instead i get
5
15
6
and after i press enter here
i get the 63
import java.util.Scanner;
public class VonNeumanLovesBinary {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int no = scn.nextInt();
while (no > 0)
{
int binary = scn.nextInt();
int i = 0 ;
int sum = 0;
while(binary > 0 )
{
int digit = binary % 10;
sum += Math.pow(2,i) * digit ;
binary /= 10;
i++;
}
System.out.println(sum);
no--;
}
}
}
This code is written Intellij IDE.
Please help me out . this is the problem of the ide ?
Its not the fault of the IDE. It is how it deals with copy-pasting text into the console.
The text is handed over to the Java code as you paste it, line by line. Input is only handed over once you finish the line. The previous lines are all terminated already with a newline symbol but the last line is not.
So you have to either add a newline to the end of your copy-pasta or hit enter to produce one yourself. So before you terminate the last line, the last line is never handed over to Java but is still only in the console.
For example, if you copy pasta this instead:
4
101
1111
00110
111111
(note the last, empty line)
it will work as expected, since you finished the 111111 line, i.e. it is 111111\n and not just 111111.

Why am I getting an exception when redirecting input from file, but not manual input for a Java program?

Here are the contents of my input file (called input.txt)
C:\DIRECTORY_REMOVED>type input.txt
180
3
640 480
120 300
180 180
And here is the Java program I'm running it against (a friend wrote it),
import java.io.*;
import java.util.*;
class Square
{
public static void main (String args[]) throws IOException
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String s;
s = stdin.readLine();
int L = Integer.parseInt(s);
String m;
m = stdin.readLine();
int N = Integer.parseInt(m);
int a = 1;
while (a <= N)
{
Scanner sc = new Scanner(System.in);
int W = sc.nextInt();
int H = sc.nextInt();
if ( W < L || H < L)
{
System.out.println("UPLOAD ANOTHER");
}
else if ( W >= L && H >= L && W == H)
{
System.out.println("ACCEPTED");
}
else
{
System.out.println("CROP IT");
}
a++;
}
}
}
After compiling, if I were to manually enter the input on the command line, the program runs without issues (see below),
C:\DIRECTORY_REMOVED>java Square
180
3
640 480
CROP IT
120 300
UPLOAD ANOTHER
180 180
ACCEPTED
But if I attempt to redirect the input from the earlier text file an exception gets thrown,
C:\DIRECTORY_REMOVED>java Square < input.txt
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Square.main(Square.java:18)
If the source code is re-written to use Scanner instead of BufferedReader for the initial input lines, the exception goes away. What I don't understand is WHY?
Does anyone have a good explanation of why the code runs perfectly fine if the data is entered manually from command prompt, but fails if redirected from a file?
The same behavior has been observed on Windows 7 (64-bit) and Windows 8.1 (64-bit). JDK used is also 64-bit (Java version 8).
OFF-TOPIC: The program was written in answer to a practice puzzle on HackerEarth - http://www.hackerearth.com/problem/algorithm/roy-and-profile-picture/
The standard console stream is line-buffered. That means that a system call to read some data will return once one line has been read, even if more input is available. This means that the BufferedReader you wrap around System.in just reads one line at a time to fill the internal buffer.
Then, when you wrap the Scanner around System.in, it can continue from where the BufferedReader left off.
File streams are block-buffered. A system call will fill the entire supplied buffer if the file is large enough. Since your file is small, this means that the BufferedReader will read the entire file in one go, and then supply data from its internal buffer, while the underlying stream sits at EOF.
This means that when you wrap the Scanner around System.in, all it sees is a stream already at EOF, from which it can't read anything.
Either wrap the Scanner around your stdin variable or use it from the beginning instead of the BufferedReader.

External file with multiple numbers per line Java

I need help reading an external file that has more than one number per line. Here is the external data file:
1 1
2 3
3 5
4 7
5 2
6 4
1 6
2 8
3 1
4 3
5 5
6 7
1 8
2 1
3 2
4 3
5 4
6 5
I read it in by using
public class Prog435a
{
public static void main(String[] args) throws IOException
{
Scanner kbReader = new Scanner(new File("C:\\Users\\Super Mario\\Documents\\java programs\\Prog435\\Prog435a.in"));
while(kbReader.hasNext())
{
int data = kbReader.nextInt();
System.out.println(data);
}
}
}
However, it prints out the file with each number line by line. So instead of appearing in columns, it appears in a single column. How can I get this to print out in two columns as shown above? Thanks for the help.
Loop by line. Call nextInt() two times per line.
while(kbReader.hasNextLine()) {
System.out.println(kbReader.nextInt() + " " + kbReader.nextInt());
}

Java string split function acting strange

I am noticing strange behaviour when using the split() method in Java.
I have a string as follows: 0|1|2|3|4|5|6|7|8|9|10
String currentString[] = br.readLine().split("\\|");
System.out.println("Length:"+currentString.length);
for(int i=0;i < currentString.length;i++){
System.out.println(currentString[i]);
}
This will produce the desired results:
Length: 11
0
1
2
3
4
5
6
7
8
9
10
However if I receive the string: 0|1|2|3|4|5|6|7|8||
I get the following results:
Length: 8
0
1
2
3
4
5
6
7
8
The final 2 empties are omitted. I need the empties to be kept. Not sure what i am doing wrong. I have also tried using the split in this manner as well. ...split("\\|",-1);
but that returns the entire string with a length of 1.
Any help would be greatly appreciated!
The default behavior of split is to not return empty tokens (because of a zero limit). Use the two parameter split method with a limit of -1 will give you all empty tokens in the return.
UPDATE:
Test code as follows:
public class Test {
public static void main(String[] args) {
String currentString[] = "0|1|2|3|4|5|6|7|8||".split("\\|", -1);
System.out.println("Length:"+currentString.length);
for(int i=0;i < currentString.length;i++){ System.out.println(currentString[i]); }
}
}
Output as follows:
Length:11
0
1
2
3
4
5
6
7
8
--- BLANK LINE --
--- BLANK LINE --
The "--- BLANK LINE --" is put in by me to show that the return is blank. It is blank once for the empty token after 8| and once for the empty trailing token after the last |.
Hope this clears things up.
String.split() is weird.
Its extreme weirdness, in this and other ways, are some of the reasons why we made Splitter.
It has less surprising behavior and lots of flexibility.
My Java is a little bit rusty, but shouldn't it be:
String currentString[] = "0|1|2|3|4|5|6|7|8||".split("\\|");
System.out.println("Length:"+currentString.length);
for(int i = 0; i < currentString.length; i++)
{
System.out.println(currentString[i]);
}
IMO, I think this is the default behavior of split, Anyway please try this:
String currentString[] = br.readLine().replace("||","| |").split("\|");
System.out.println("Length:"+currentString.length);
for(int i=0;i < currentString.length;i++){
System.out.println(currentString[i]);
}
This has not been tested yet, but i think this should do the trick.
You need to use indexOf() and then substring() for this to work. I don't think you can empty string by using split() only.
Please check the following code, I used your solution, it works:
public class SplitTest
{
public static void main(String[] args)
{
String text = "0|1|2|3|4|5|6|7|8||";
String pattern = "\\|";
String [] array = text.split(pattern, -1);
System.out.println("array length:" + array.length);
for(int i=0; i&lt array.length; i++)
System.out.print(array[i]+ " ");
}
}
output is:
array length:11
0 1 2 3 4 5 6 7 8

Categories

Resources