I am very new at this so I apologize if this may seem very basic. Anyway I am trying to read input from a file and put that data into an array so that I can graph it later. the problem I am having is putting the labels of the data into an array.
Here is what I have currently:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class P6 {
static String titlePie = "Pie Chart";
static int numElements;
static String[] labels;
static double[] dataPieElements;
public static void main(String[] args){
P6 p6 = new P6();
p6.readFile(args[0]);
System.out.println(numElements);
System.out.println(Arrays.toString(dataPieElements));
System.out.println(Arrays.toString(labels));
}
private void readFile(String inputFile) {
try {
Scanner in = new Scanner(new File(inputFile));
while (in.hasNext()){
numElements=in.nextInt();
if (in.hasNextDouble()){
for (int i = 0; i<numElements; i++){
dataPieElements[i]=in.nextDouble();
}
}
else if (in.hasNext()){
for (int i = 0; i<numElements; i++){
labels[i]=in.next();
}
}
}
in.close();
}
catch (FileNotFoundException e){
System.out.println("File not found");
}
}
}
The input file looks like this:
6
Nokia
Apple
Google
Samsung
Apple
Other
14.2
26.2
13.1
18.9
11.3
16.3
The error I'm getting is:
Exception in thread "main" java.lang.NullPointerException
So my thinking is that because the doubles are after the strings the pointer reaches the end of the file and never gets the strings, but if I change the order of the if statements and get the strings before the doubles it turns the doubles into strings. So what is the best way to get each data type into its respective array?
Thank you so much for any suggestions you might have!
You declared your arrays labels and dataPieElements, but you didn't initialize those arrays, so they're still null.
Initialize them when you know how many are needed. After
numElements=in.nextInt();
then...
labels = new String[numElements];
dataPieElements = new double[numElements];
Related
I can't seem to find the issue in my code and was wondering if you wonderful people on here would be willing to help me out. My professor is requiring us to create a 2-D array from information pulled from a file she provided us. Using the Scanner and File class we should be able to accomplish this, however, I have hit a speed bump. My scanner is not recognizing the integer after the delimiter I have set for it. Here is the file she provides us with.
5x7
o,2,3
7,1,3
7,1,1
X,4,2
This info is separated by newlines where there are spaces in the blockquote.
Here is my code:
import java.io.*;
import java.util.*;
public class Battlefield {
// Use the FILL_CHAR for a space that contains no creature.
// Use these chars for creatures so that your code will pass
// the tests used for evaluating your program.
public final char FILL_CHAR = '-';
public final char OGRE = 'o';
public final char CENTAUR = '7';
public final char DRAGON = 'X';
private char[][] field;
public Battlefield(String fn) {
try {
// You write code here.
// Read a file and initialize the field.
// The name of the file is passed in from the driver.
// Keep all the file reading stuff in the try/catch block
// to make file exceptions easier to deal with.
File battlefield = new File(fn);
Scanner scan = new Scanner(battlefield);
scan.useDelimiter("x");
int row = scan.nextInt();
System.out.println(row);
System.out.println(scan.next());
System.out.println(scan.hasNextInt());
int column = scan.nextInt();
char[][] field = new char[row][column];
/**
Scanner scan2 = new Scanner(battlefield);
scan2.useDelimiter(",");
/**
field[scan2.nextInt()][scan2.nextInt()] = OGRE;
field[scan2.nextInt()][scan2.nextInt()] = CENTAUR;
field[scan2.nextInt()][scan2.nextInt()] = CENTAUR;
field[scan2.nextInt()][scan2.nextInt()] = DRAGON;
**/
} catch (IOException ex) {
System.err.println(ex.getStackTrace());
}
}
And my main method/driver class:
public class BattlefieldDrv {
public static void main(String[] args)
{
Battlefield battlefieldOne = new Battlefield("1field.dat");
System.out.println(battlefieldOne.toString());
}
}
Here is my stack trace:
> 5
7
o,2,3
7,1,3
7,1,1
X,4,2
false
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Unknown Source)
at java.base/java.util.Scanner.next(Unknown Source)
at java.base/java.util.Scanner.nextInt(Unknown Source)
at java.base/java.util.Scanner.nextInt(Unknown Source)
at Battlefield.<init>(Battlefield.java:38)
at BattlefieldDrv.main(BattlefieldDrv.java:15)
Thank you for any help or insight you have!
So let's step through this code.
scan.useDelimiter("x");
int row = scan.nextInt();
5 is read into row.
System.out.println(row);
5 is printed.
System.out.println(scan.next());
The rest of the file is read and printed, because that's what comes after the x.
System.out.println(scan.hasNextInt());
There's nothing left to read, so the NoSuchElementException is thrown here.
You need to make the scanner also accept newlines as delimiter; you can do that by using
scan.useDelimiter("(x|\\s)");
(The \\s is the pattern for "any whitespace").
As a side note, it's good practice to use the try-with-resources-construct:
try (Scanner scan = new Scanner(Paths.get("1field.dat"))) {
scan.useDelimiter(...);
...
} catch (IOException e) {
This will result in your file resource being closed automatically.
I am a beginner in programming. I am currently learning how to convert texts from notepad into array line by line. An instance of the text in notepad,
I am a high school student
I love banana and chicken
I have 2 dogs and 3 cats
and so on..
In this case, the array[1] will be string 'I love banana and chicken'.
The lines in the notepad can be updated and I want the array to be dynamic/flexible. I have tried to use scanner to identify each of the lines and tried to transfer them to array. Please refer to my code:
import java.util.*;
import java.io.*;
import java.util.Scanner;
class Test
{
public static void main(String[] args)
throws Exception
{
File file = new File("notepad.txt");
Scanner scanner = new Scanner(file);
String line;
int i = 0;
int j = 0;
while (scanner.hasNextLine()) {
i++;
}
String[] stringArray = new String[i];
while (scanner.hasNextLine()) {
line = scanner.nextLine();
stringArray[j] = line;
j++;
}
System.out.println(stringArray[2]);
scanner.close();
}
}
I am not sure why there is runtime-error and I tried another approach but still did not produce the result that I want.
The first loop would be infinite because you check if the scanner has a next line, but never advance its position. Although using a Scanner is fine, it seems like a lot of work, and you could just let Java's nio package do the heavy lifting for you:
String[] lines = Files.lines(Paths.get("notepad.txt")).toArray(String[]::new);
You can simply do it by creating an ArrayList and then converting it to the String Array.
Here is a sample code to get you started:
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new File("notepad.txt"));
List<String> outputList = new ArrayList<>();
String input = null;
while (in.hasNextLine() && null != (input = in.nextLine())) {
outputList.add(input);
}
String[] outputArray = new String[outputList.size()];
outputArray = outputList.toArray(outputArray);
in.close();
}
Since you want array to be dynamic/flexible, I would suggest to use List in such case. One way of doing this -
List<String> fileLines = Files.readAllLines(Paths.get("notepad.txt"));
I am trying to create a 2D ArrayList and add values to it. For some reason I keep getting a NoSuchElementException.
Here is the problem I am trying to solve: https://www.hackerrank.com/challenges/java-arraylist
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner input = new Scanner(System.in);
int TestCases = input.nextInt();
ArrayList<ArrayList<Integer>> listOfLists = new ArrayList<ArrayList<Integer>>();
List<ArrayList<Integer>> Sdarraylist = new ArrayList<ArrayList<Integer>>();
//ArrayList<ArrayList<String>> 2darraylist = new ArrayList<>();
//ArrayList<String> 1darraylist=new ArrayList<>();
for(int i=0;i<TestCases;i++){
ArrayList<Integer> Fdarraylist=new ArrayList<Integer>();
//size of Arraylist
int NumbersOnCurrentLine = input.nextInt();
for(int j=0;i<NumbersOnCurrentLine;j++){
//add numbers on the current line to the list
Fdarraylist.add(input.nextInt());
}
Sdarraylist.add(Fdarraylist);
}
// data.add(new ArrayList<String>());
//data.get(0).add("String");
}
}
That exception occurs when you try to read from an input, but no input is available. One workaround would be to use use the hasNextInt() method to make sure there is readable input available.
ex)
if (input.hasNextInt()) {
Fdarraylist.add(input.nextInt());
}
This could be the result of the input saying there are three numbers on the current line, when in reality there are only two.
1
3 1 4 <= would cause exception.
I do not know how to take the integer and ignore the strings from the file using scanner. This is what I have so far. I need to know how to read the file token by token. Yes, this is a homework problem. Thank you so much.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ClientMergeAndSort{
public static void main(String[] args){
int length = 13;
try{
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.nextLine());
input = new Scanner(file);
while (!input.hasNextInt()) {
input.next();
}
int[] arraylist = new int[length];
for(int i =0; i < length; i++){
length++;
arraylist[i] = input.nextInt();
System.out.print(arraylist[i] + " ");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Take a look at the API for what you're doing.
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()
Specifically, Scanner.hasNextInt().
"Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input."
So, your code:
while (!input.hasNextInt()) {
input.next();
}
That's going to look and see if input hasNextInt().
So if the next token - one character - is an int, it's false, and skips that loop.
If the next token isn't an int, it goes into the loop... and iterates to the next character.
That's going to either:
- find the first number in the input, and stop.
- go to the end of the input, not find any numbers, and probably hits an IllegalStateException when you try to keep going.
Write down in words what you want to do here.
Use the API docs to figure out how the hell to tell the computer that. :) Get one bit at a time right; this has several different parts, and the first one doesn't work yet.
Example: just get it to read a file, and display each line first. That lets you do debugging; it lets you build one thing at a time, and once you know that thing works, you build one more part on it.
Read the file first. Then display it as you read it, so you know it works.
Then worry about if it has numbers or not.
A easy way to do this is read all the data from file in a way that you prefer (line by line for example) and if you need to take tokens, you can use split function (String.split see Java doc) or StringTokenizer for each line of String that you are reading using a loop, in order to create tokens with a specific delimiter (a space for example) so now you have the tokens and you can do something that you need with them, hope you can resolve, if you have question you can ask.
Have a nice programming.
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) throws IOException {
String newStr=new String(readAllBytes(get("data.txt")));
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(newStr);
while (m.find()) {
System.out.println("- "+m.group());
}
}
}
This code fill read the file and then using the regular expression you can get only Integer values.
Note: This code works in Java 8
I Think This will work for you requirement.
Before reading the data from the file initially,try to write some content to the file by using scanner and filewriter then try to execute the below code snippet.
File file = new File(your filepath);
List<Integer> list = new ArrayList<Integer>();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String str =null;
while(true) {
str = bufferedReader.readLine();
if(str!=null) {
System.out.println(str);
char[] chars = str.toCharArray();
String finalInt = "";
for(int i=0;i<chars.length;i++) {
if(Character.isDigit(chars[i])) {
finalInt=finalInt+chars[i];
}
}
list.add(Integer.parseInt(finalInt));
System.out.println(list.size());
System.out.println(list);
} else {
break;
}
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
The final println statement will display all the integer in your file line by line.
Thanks
Here are my directions:
This program will use two arrays - these are called parallel arrays. You will NOT be using an array of objects.
You will have a minimum of 6 methods in this application (including main())
inputData() - input from the data file into two arrays - the data file is below, call it "population.txt"
remember to check for the existence of the file before associating the Scanner object to it
displayCountries() - display all of the countries - just the countries
Can you please tell me why this will not run? I need to have the value of the population and the country name together so I can write it in a table later. So I am thinking that I need to read the first value into countryName and the first value into populationNum instead of reading them all in at the same time. The text that I am reading in is below the code. I do not know how to do that though. I am also wondering if I need the [25] when I instantiate. It gives me this error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Population.inputData(Population.java:32)
at Population.main(Population.java:13)
This is my code:
import java.io.*;
import java.util.Scanner;
import java.io.IOException;
import java.text.DecimalFormat;
public class Population{
public static void main(String [] args)throws IOException{
//Arrays
String [] countryNames = new String [25];
int [] populationNum = new int [25];
//Input data from file into the array
inputData(countryNames, populationNum);
//Displays and calculations
displayCountries(countryNames);
} //end main()
//this class gets the input for arrays from the file
public static void inputData(String [] countryNames, int [] populationNum) throws IOException{
File infile = new File("population.txt.");
int index = 0;
Scanner scan = new Scanner(infile);
while(scan.hasNext())
for(int i = 0; i < countryNames.length; i++)
countryNames[i] = scan.nextLine();
for(int i = 0; i < populationNum.length; i++)
populationNum[i] = scan.nextInt();
} //end inputData()
//this class displays the countries
public static void displayCountries(String [] countryNames) {
for(int i = 0; i < countryNames.length; i++)
System.out.println(countryNames[i]);
} //end displayCountries()
}//end class
Ghana
24333000
Brazil
193364000
Australia
23480970
Nigeria
170123000
Papua New Guinea
6888000
Mexico
108396211
Egypt
79221000
Iran
75078000
Myanmar
50496000
Belgium
10827519
Tuvalu
10000
russia
141927297
You need to read into both arrays in the same loop, like this:
int i = 0;
while(scan.hasNext()) {
countryNames[i] = scan.nextLine();
if (scan.hasNext()) populationNum[i] = scan.nextInt();
if (scan.hasNext()) scan.nextLine(); // Go to the next line
i++;
}
The two for loops inside the while are incorrect (not to mention that the second for loop is not even part of the while, because you omitted curly braces).
Demo.
You need { after while(scan.hasNext()) and closing } after two for loops. What is happening is while loop scans all data then the for loops try to do scan.next when the scanner is already at end of file. Hope this helps