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
Related
I need to pull integers from a text file and sum them up. I came up with this but I keep getting an error. What am I missing? I need to use a scanner class.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class txtClass {
public static void main(String[] args) throws FileNotFoundException {
File txtFile = new File(//text file path//);
Scanner scan = new Scanner(txtFile);
int length = 0;
while(scan.hasNextLine()) {
scan.nextLine();
length++;
}
int array[] = new int [length];
array[length++] = scan.nextInt();
System.out.println(array.toString());
int h = 0;
for (int i = 0; i<array.length; i++)
{
h +=array[i];
}
scan.close();
System.out.print(h);
}
}
As suggested, a lot of the code is not really needed. But presumably the 'error' you get is array index out of bounds. Here:
int array[] = new int [length];
array[length++] = scan.nextInt();
So you allocate an array and immediately access off the end of the array. Let's assume length is 42. Therefore, the allocated array elements have indexes 0 to 41. You try and assign something to array[42]. I'm not sure what you're trying to do with that line.
The alternative guess (which we would not need to guess had you mentioned the actual error message) is that your counting lines leaves the scanner positioned at end of file. so the scan.nextInt() call in the assignment gets you an I/O error.
In any case, the core of the solution is something like
int sum = 0;
while (scan.hasNextInt())
sum += scan.nextInt();
No array is needed.
You wrote in your question
I keep getting an error
That would be NoSuchElementException which is thrown by this line of your code:
array[length++] = scan.nextInt();
This is because you have already scanned the entire file and therefore there is no next int.
Remember that in order for people to help you with errors thrown by your code, you need to post the actual exception and the stack trace as well as your code.
You don't need to save all the numbers in the file in an array in order to get the sum of all the numbers. However if you also want to save all the numbers but you don't know in advance how many there are, you can use a List.
Here is a minimal example of how to read the file – which I assume contains only numbers separated by whitespace – and calculate the total. Of-course you need to replace text file path with the actual path to the text file.
File txtFile = new File("text file path");
try (Scanner scan = new Scanner(txtFile)) {
int total = 0;
while (scan.hasNextInt()) {
total += scan.nextInt();
}
System.out.println("Total: " + total);
}
catch (FileNotFoundException xFileNotFound) {
xFileNotFound.printStackTrace();
}
Note that the above code uses try-with-resources.
I am having an issue with this unfinished program. I do not understand why this returns a "no Line found exception" when I run it. I have a while loop set up whose purpose is checking for this but I have done something wrong. I am trying to store information from a file into a 2d array for class.
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.File;
import java.util.Arrays;
public class LabProgram {
public static void main(String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
int NUM_CHARACTERS = 26; // Maximum number of letters
int MAX_WORDS = 10; // Maximum number of synonyms per starting letter
String userWord = (scnr.next()) + ".txt"; //Get word user wants to search
char userChar = scnr.next().charAt(0); //Get char user wants to search
String[][] synonyms = new String[NUM_CHARACTERS][MAX_WORDS]; // Declare 2D array for all synonyms
String[] words = new String[MAX_WORDS]; // The words of each input line
File aFile = new File(userWord);
Scanner inFile = new Scanner(aFile);
while(inFile.hasNextLine()) {
for(int i = 0; i < synonyms.length; i++) {
words = inFile.nextLine().trim().split(" ");
for(int wordCount = 0; wordCount < words.length; wordCount++) {
synonyms[i][wordCount] = words[wordCount];
}
}
}
}
}
The issue is with this for loop:
for (int i = 0; i < synonyms.length; i++) {
words = inFile.nextLine().trim().split(" ");
....
}
You're iterating from i=0 upto synonym.length-1 times, but that file does not have these much lines, so, as soon as your file is out of lines but the for loop has scope to iterate more, the inFile.nextLine() gets no line and thus throw the exception.
I don't know what you are exactly doing here or want to achieve through this code, but this is what causing you the trouble.
Hope that answers your query.
Basically your problem is that you're only checking hasNextLine() before the for loop starts, and you're actually getting the next line on every iteration of the loop. So if you run out of lines while in the middle of your for loop an exception is thrown.
I'm actually not quite sure what your code is supposed to do but at the very least you need to add a hasNextLine() check every time before you actually run nextLine() to avoid errors like this.
For example, I entered a size of 3 Students. It skips index 0 in the console also in printing.
Please refer to this image, I have a sample size of 3 students and its output.
I don't have the slightest idea of why it skips index 0? Thanks for the help!
import java.util.Arrays;
import java.util.Scanner;
class string{
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.print("Enter Student Size: ");
int studentSize = console.nextInt();
String [] arrName = new String[studentSize];
for (int i=0; i<arrName.length; i++){
System.out.print("Enter student name: ");
String nameString = console.nextLine();
arrName[i] = nameString;
}
System.out.print(Arrays.toString(arrName));
//Closing Braces for Class and Main
}
}
The problem is with the console.nextInt(), this function only reads the int value.So In your code inside the loop console.nextLine() first time skip the getting input.just puting console.nextLine()afterconsole.nextInt()
you can solve the problem.
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.print("Enter Student Size: ");
int studentSize = console.nextInt();
console.nextLine();
String [] arrName = new String[studentSize];
for (int i=0; i<arrName.length; i++){
System.out.print("Enter student name: ");
String nameString = console.nextLine();
arrName[i] = nameString;
}
System.out.print(Arrays.toString(arrName));
//Closing Braces for Class and Main
}
The reason for this skip is due to the different behavior of the console.nextInt() and console.nextLine() as:
console.nextInt() reads the integer value entered, regardless of whether you hit the enter for new-line or not.
console.nextLine() reads the whole line, but as you previously hit thee enter when you give the size of Array.
3 was accepted as the size of the Array and when you hit enter it was accepted as the first value for you array which is a blank space or I can say it is referred as "".
Following are the two resolution for this:
Either put a console.nextLine() call after each console.nextInt() to consume rest of that line including newline
Or, even better, read the input through Scanner.nextLine and convert your input to the proper format you need. you may convert to an integer using int studentSize = Integer.parseInt(console.nextLine()) method. (Surround it with try-catch)
**Edit after reviewing Tormod's answer and implementing his advice.
As the title states I'm attempting to print the total number of different words after receiving a file name from command line input. I receive the following message after attempting to compile the program:
Note: Project.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Here is my code. Any help is greatly appreciated:
import java.lang.*;
import java.util.*;
import java.io.*;
public class Project {
public static void main(String[] args) throws IOException {
File file = new File(args[0]);
Scanner s = new Scanner(file);
HashSet lib = new HashSet<>();
try (Scanner sc = new Scanner(new FileInputStream(file))) {
int count = 0;
while(sc.hasNext()) {
sc.next();
count++;
}
System.out.println("The total number of word in the file is: " + count);
}
while (s.hasNext()) {
String data = s.nextLine();
String[] pieces = data.split("\\s+");
for (int count = 0; count < pieces.length; count++)
{
if(!lib.contains(pieces[count])) {
lib.add(pieces[count]);
}
}
}
System.out.print(lib.size());
}
}
I would implement it using a HashSet Add all the words, and read out the size. If you want to make it case insensitive just manipulate all the words to uppercase or something like that. this uses some memory but...
one problem you got with the algorithm is that you do only have one "words". it only holds the words at the same line. so you only count same words at the same line.
HashSet stores strings by their hash value, and thus stores one word only one time.
construction: HashSet lib = new HashSet<>();
inside the loop: if(!lib.contains(word)){lib.add(word);}
check the word count: lib.size()
for(String s : words) {
if(s.equals(word))
count++;
}
You are comparing the words to an empty String, since it's a word it's always gonna be false.
Like Tormod said, the best would be to store the words in a HashSet, as it won't keep duplicates. Then just read out its size.
I want to be able to read a text file for its rows and columns and put the data in a matrix. this is what i got so far. i have a matrix class with one data member called element of type int and it's a 2-d array [][].
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) throws FileNotFoundException {
File fin = new File ("matrix1.txt");
Scanner scanner = new Scanner(fin);
scanner.next(); // removes the first line in the input file
int rows = scanner.nextInt();
int cols = scanner.nextInt();
while (scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}
System.out.println(rows);
System.out.println("/n");
System.out.println(cols);
}
}
The sample text file is as follows. I want to take the rows and columns so i can dynamically declare the matrix and then store its values. i get the error saying INPUTMISMATCH exception. help would be appreciated.
<matrix>
rows = 2
cols = 2
1 2
2 4
</matrix>
From the javacdocs, an InputMismatchException is thrown "if the next token does not match the Integer regular expression, or is out of range".
You're trying to scan a string "row = 2" as an integer. You can't use nextInt in this case. Try nextLine and then split on = to get the value.
Example:
String rowLine = scanner.nextLine();
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim());