Fill an int array with a txt java - java

Hi i want to fill an array with values from a txt file, but I got the error java.util.NoSuchElementException: No line found when running the program, this is my code.
private static void leeArchivo()
{
Scanner s = new Scanner(System.in);
//Size of the array
int size = Integer.parseInt(s.nextLine());
datos = new int[size];
while (s.hasNextLine()) {
for (int i = 0; i < size; i++) {
//fill array with values
datos[i] = Integer.parseInt(s.nextLine());
}
}
}
The txt would look like this, first line is the size of the array:
4
75
62
32
55

Having both a while loop and a for loop appears to be the cause of your trouble. If you are sure that your input is correct, ie. the number of lines matches the first number, then you can do something like this:
private static void leeArchivo()
{
Scanner s = new Scanner(System.in);
//Size of the array
int size = Integer.parseInt(s.nextLine());
datos = new int[size];
for (int i = 0; i < size; i++) {
//fill array with values
datos[i] = Integer.parseInt(s.nextLine());
}
}
In the code above, there is no test for hasNextLine() as it's not required because we know there is a next line. If you want to play it safe, use something like this:
private static void leeArchivo()
{
Scanner s = new Scanner(System.in);
//Size of the array
int size = Integer.parseInt(s.nextLine());
datos = new int[size];
int i = 0;
while ((i < size) && s.hasNextLine()) {
//fill array with values
datos[i] = Integer.parseInt(s.nextLine());
i++;
}
}

Related

Why does my method that I am trying to call to inside main not work?

minGap(array); is not being recognized. I don't know what I have done wrong, but I am sure it is a super simple fix. Trying to figure out if it is something to do with the data type being used or if it has something to do with the arrangement of the line " " added. Any hints?
package Lab8;
import java.util.*;
import java.util.Scanner;
public class Question_One {
public static void main(String args[]) {
int length;
Scanner input = new Scanner(System.in); //scanner to input any size array user wants
System.out.println("Please enter the numbers for the array.");
length = input.nextInt();
String[] array = new String[length];
for(int i = 0;i <length;i++) { //counter logic
System.out.println("How many integers are in the array?"+(i+1));
array[i] = input.nextLine();
}
System.out.println("Enter the numbers for the array (individually):");
for(int i = 0;i <length;i++) { //counter logic
System.out.print(array [i]);
array[i] = input.nextLine();
}
input.close();
minGap(array);
}
private static int minGap(int a[], int gapMin) {
int []gap = new int[a.length];
//a
for (int i=0;i<a.length-2;i++) {
if (gapMin>gap[i]) {
gapMin=gap[1];
}
}
return gapMin;
}
}
I believe you wanted a method to find the minimum gap. As such, you should not be passing that into the method. Your logic is also a bit off, you want to take the minimum value after gapMin>gap[i] (not a hardcoded gap[1]). So you could do,
private static int minGap(int a[]) {
int gapMin = Integer.MAX_VALUE;
int[] gap = new int[a.length];
for (int i = 0; i < a.length; i++) {
if (gapMin > gap[i]) {
gapMin = gap[i];
}
}
return gapMin;
}
or (if you're using Java 8+)
private static int minGap(int a[]) {
return Arrays.stream(a).min().getAsInt();
}
Then you need to actually save that value or print it. That is, change
minGap(array);
to (just print it)
System.out.println(minGap(array));
And you need an array of int (not a String[]).
int[] array = new int[length];
for(int i = 0; i < length; i++) {
System.out.printf("Please enter integer %d for the array%n", i + 1);
array[i] = input.nextInt();
}

Filling a 2d character array from a file in java

I'm a beginner in java and I am trying to fill a 2d character array from an input file. To do this I constructed a method which takes in a 2d character array as a parameter variable, then reads the file and stores it as a character array. So far I have done everything except fill the array, as when I run the code the program throws a NoSuchElement exception. If anyone could help me with this I would greatly appreciate it.
public static char [][] MakeWordArray (char [][] givenArray)
{
try
{
File wordFile= new File ("words.txt");
Scanner in= new Scanner (wordFile);
int rows =0;
int col=0;
while (in.hasNextLine())
{
rows = rows + 1;
col = col + 1;
in.next();
}
char [][] words = new char [rows][col];
File wordFile2= new File ("words.txt");
Scanner in2= new Scanner(wordFile2);
for ( int i = 0; i < rows; i++)
{
for (int j = 0; j < col; j++)
{
String wordly = in2.nextLine();
words [i][j] = wordly.charAt(i);
}
}
return words;
}
catch (FileNotFoundException e)
{
System.out.println("File Does Not Exist");
}
return null;
}
I think your counting methods have some problems.
If you want to count how many lines your .txt have:
int counter = 0;
while (in.hasNextLine())
{
counter++;
in.nextLine();
}
If you want to count how many char your .txt have:
int counterWithoutSpace = 0, counterWithSpace = 0;
while (in.hasNextLine())
{
String line = in.nextLine();
Scanner inLine = new Scanner(line);
while (inLine.hasNext())
{
String nextWord = inLine.next();
counterWithoutSpace += nextWord.length();
counterWithSpace += nextWord.length() + 1;
}
counterWithSpace--;
}
If you want to count how many char you have on each line, I recommend ArrayList. Because the size of your array is dynamic.
Note that you can also you can use the char counter logic above with List too.See as follows:
List<Integer> arr = new ArrayList<Integer>();
while (in.hasNextLine())
{
arr.add(in.nextLine().length());
}
And if you realy needs the static array, you can use:
Integer[] intArr = arr.toArray(new Integer[0]);
You can transform its entire function as below to get a list of every Character of the .txt:
List<Character> arr = new ArrayList<Character>();
while (in.hasNextLine())
{
String line = in.nextLine();
for (char c : line.toCharArray())
{
arr.add(c);
}
}
Try using a do while loop instead of the while
do
{
rows=rows+1;
col=lol+1;
in.next();
}
while(in.hasNext());
There are multiple questions here.
1) Why did you provide a char[][] parameter when you are not even using it?
2) Why are you using two files when all you need to do is read from a file and convert it in 2d Array?
3) The method name should follow camel casing convention.
From what i understood from your question, This is a code i've tried.
NOTE- because the requirement is of an Array and not dynamic datatypes like List ArrayList etc., the data entered into char array might be lost
Saying that here is what works.
public class StackOverflow{
public static char [][] makeWordArray ()
{
try{
File f = new File("C:\\docs\\mytextfile.txt");
Scanner scan = new Scanner(f);
int row = 0, col = 0;
String readData = "";
while(scan.hasNextLine()){
readData += scan.nextLine();
row++;
}
double range = (readData.length()/row);
col = (int)Math.ceil(range);
char[][] arr = new char[row][col];
int count = 0;
for (int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
arr[i][j] = readData.charAt(count++);
System.out.println("Pos: ["+ i +"][" + j + "]" + arr[i][j]);
}
}
return arr;
}
catch(FileNotFoundException fe){
System.err.println(fe.getMessage());
return null;
}
}
public static void main(String[] arg){
char[][] myarr = StackOverflow.makeWordArray();
//print your array
}
}

2d array size based on input

I have a code where in, an array is to be defined, in which the size is based on user input. How do I do that?
My code is as follows:
public static void main(String args[]) throws Exception {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of layers in the network:");
int Nb_Layers = in.nextInt();
int[] Hidden_layer_len = new int[Nb_Layers];
for (int i = 0; i < Nb_Layers-1; i++)
{
System.out.println("Enter the length of layer" +(i+1)+":");
Hidden_layer_len[i] = in.nextInt();
if(i == 0)
{
double [][] E = new double[Hidden_layer_len[i]][1];//This is the array I need based on the size mentioned.
}
}
System.out.println(E);
}
I want this to be a 2D array. Any suggestions would be appreciated. thank you!
You can define the array outside the for loop and assign inside. E.g.
double[][] E = null;
for (int i = 0; i < Nb_Layers - 1; i++) {
System.out.println("Enter the length of layer" + (i + 1) + ":");
Hidden_layer_len[i] = in.nextInt();
if (i == 0) {
E = new double[Hidden_layer_len[i]][1];
}
}
This way it will be available when you print it at the end.
By the way you probably want to print it like this
System.out.println(Arrays.deepToString(E));

How do you populate an array with String input from a file?

Assume that i have 4 grades in testgrades.txt I don't know why this wont work.
public static void main(String[] args) throws FileNotFoundException {
File file1= new File("testgrades.txt");
int cnt = 4;
int[] grades = new int[cnt];
String line1;
for (int i=0; i<cnt; i++) {
Scanner inputFile2 = new Scanner(file1);
line1 = inputFile2.nextLine();
int grades2 = Integer.parseInt(line1);
grades[i] = grades2;
}
System.out.print(grades);
First of all, you should note that arrays in java hold fixed-size elements of the same type.
You can initialize them in one of two ways (not very sure if there are other ways).
//First method
int[] anArray = new int[10];
// Second method
int[] anArray = {1,2,3,4,5,6,7,8,9,10};
In either case, the array is of size 10 elements. Since you are fetching the data from the text file, I'll suggest you count number of lines into a variable and use that value to initialize the array. Then you can use a loop to fill the values this way:
// Assuming you have cnt as your total count of grades.
int[] grades = new int[cnt];
String line1;
for (int 1=0; i<cnt; i++) {
line1 = inputFile2.nextLine();
int grades2 = Integer.parseInt(line1);
grades[i] = grades2;
}
This is coming off my head so let me know if you face any problem.
You can do like this
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
File file= new File("testgrades.txt");
Scanner scan = new Scanner(file);
int arr[] = new int[100];
int i = 0;
do{
String line1 = scan.nextLine();
int grades2 = Integer.parseInt(line1);
arr[i++] = grades2;
}while(scan.hasNextLine());
for(int j = 0; j < i; j++){
System.out.println(arr[j]);
}
}

How to convert a char array to an int array?

Say I am using this code to convert a String (containing numbers) to an array of characters, which I want to convert to an array of numbers (int).
(Then I want to do this for another string of numbers, and add the two int arrays to give another int array of their addition.)
What should I do?
import java.util.Scanner;
public class stringHundredDigitArray {
/**
* #param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number: ");
String num1 = in.nextLine();
char[] num1CharArray = num1.toCharArray();
//for (int i = 0; i < num1CharArray.length; i++){
//System.out.print(" "+num1CharArray[i]);
//}
int[] num1intarray = new int[num1CharArray.length];
for (int i = 0; i < num1CharArray.length; i++){
num1intarray[i] = num1CharArray[i];
}
for (int i = 0; i < num1intarray.length; i++){ //this code prints presumably the ascii values of the number characters, not the numbers themselves. This is the problem.
System.out.print(" "+num1intarray[i]);
}
}
}
I really have to split the string, to preferably an array of additionable data types.
try Character.getNumericValue(char); this:
for (int i = 0; i < num1CharArray.length; i++){
num1intarray[i] = Character.getNumericValue(num1CharArray[i]);
}
Try This :
int[] num1intarray = new int[num1CharArray.length];
for (int i = 0; i < num1CharArray.length; i++)
{
num1intarray[i]=Integer.parseInt(""+num1CharArray[i]);
System.out.print(num1intarray[i]);
}
Short and simple solution!
int[] result = new int[charArray.length];
Arrays.setAll(result, i -> Character.getNumericValue(charArray[i]));

Categories

Resources