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]);
}
}
Related
I am trying to use user inputted N lines of N characters to do some operations with. But first I need to know N and another int being inputted. When I define N and the other integer K and then write 5 lines (in this case) of 5 characters each the program runs well. But when I use the represented String a (which I then would split into 2 ints, N and K, not shown here to not complicate things), an error occurs. Even if I now input 6 lines, being the 5 last of 5 characters each, the program gives an error of no line found for the multi function. I don't understand what's the problem, and if I remove the string a and just define N and K the program runs well. What's more surprising, the program runs if I use an interactive console instead of text input and write the terms one by one.
static String [][] vetor (int N) {
Scanner scan = new Scanner(System.in);
String[][] multi = new String [N][N];
for (int i = 0 ; i<N ; i++){
String forest = scan.nextLine();
String[] chars = forest.split("");
for (int k=0; k<N; k++){
multi[i][k]= chars [k];
}
}
return multi;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String a = scan.nextLine();
int N = 5;
int K = 5;
String [][] multi = vetor(N);
I've tried many things, but I can't make sense of this. I didn't find any similar questions, but feel free to redirect me to an explanation.
Edit: This is a similar program one can run (with a possible input down (K<= N)) :
import java.util.Scanner;
import java.util.Arrays;
public class Main {
static int[] numerificar() {
Scanner myObj = new Scanner(System.in);
String Input = myObj.nextLine();
String[] Inputs = Input.split(" ", 0);
int size = Inputs.length;
int [] a = new int [size];
for(int i=0; i<size; i++) {
a[i] = Integer.parseInt(Inputs[i]);}
return a;
}
static String [][] vetor (int N) {
Scanner scan = new Scanner(System.in);
String[][] multi = new String [N][N];
for (int i = 0 ; i<N ; i++){
String forest = scan.nextLine();
String[] chars = forest.split("");
for (int k=0; k<N; k++){
multi[i][k]= chars [k];
}
}
return multi;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int[] a = numerificar();
int N = a[0];
int K = a[1];
int cadeira = 0;
String [][] multi = vetor(N);
for (int i = 0 ; i<N ; i++){
if (cadeira == 1) {
break;
}
for (int k=0; k<N-K+1; k++){
if (cadeira == 1) {
break;
}else if( multi[i][k].equals(".")){
for (int j=0; j<K; j++){
if(multi[i][k+j].equals( "#")){
k+=j;
break;
} else if (j == K-1) {
cadeira = 1;
}
}
}
}
}
System.out.println(cadeira);
}
}
5 3
.#.##
#####
##...
###..
#####
The output should be 1 in this case.
The problem is you are creating more than one Scanner that reads from System.in. When data is readily available, a Scanner object can read more data than you ask from it. The first Scanner, in the numerificar() method, reads more than the first line, and those lines are not available to the second Scanner, in the vetor() method.
Solution: use just one Scanner object in the whole program.
public class Main {
static Scanner globalScanner = new Scanner(System.in);
static int[] numerificar() {
String Input = globalScanner.nextLine();
String[] Inputs = Input.split(" ", 0);
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
}
}
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++;
}
}
I am trying to read in two lines of input from stdin, and copy the items of the first line into one array, and the items of the second line into another array. The items in each line have spaces between them, which I use to differentiate between the items. An example of the input would be:
1 2 3
4 5
At the moment 12345 is stored in one array but I want the result to be this:
arr1 = [1, 2, 3];
arr2 = [4, 5];
How would I do this?
import java.util.*;
public class Tester {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter lines:");
while(input.hasNext()) {
String s = input.nextLine();
String[] strArray = s.split(" ");
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
System.out.print(intArray[i]);
}
}
}
You should extract the parsing of a single line to a separate method:
private static int[] parseInts(String s) {
String[] strArray = s.split(" ");
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
}
return intArray;
}
After that, the code in main looks simpler:
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter lines:");
int[] line1Numbers = parseInts(input.nextLine());
int[] line2Numbers = parseInts(input.nextLine());
// For the remaining lines:
while(input.hasNext()) {
String line = input.nextLine();
int[] numbers = parseInts(line);
for(int i = 0; i < strArray.length; i++) {
System.out.print(intArray[i]);
}
}
}
My code is just printing out the last number from the list I create in a different program.
I need help storing the data into an array so I can sort it after.
edit: I need to take data from a file which is 'numbers.txt' and store it into an array.
public static void main(String[] args) throws Exception {
int numberArray = 0;
int[] list = new int[16];
File numbers = new File("numbers.txt");
try (Scanner getText = new Scanner(numbers)) {
while (getText.hasNext()) {
numberArray = getText.nextInt();
list[0] = numberArray;
}
getText.close();
}
System.out.println(numberArray);
int sum = 0;
for (int i = 0; i < list.length; i++) {
sum = sum + list[i];
}
System.out.println(list);
}
}
Correction in the code.
1.) Inside while loop, list[0] = numberArray;, will keep adding elements on the same index 0, so lat value will override. SO something like list[i] = numberArray; will work, and increement i inside while loop. Take care of ArrayIndexOutOfBound Exception here.
public static void main(String[] args) throws Exception {
int numberArray = 0;
int[] list = new int[16];
File numbers = new File("numbers.txt");
int i =0;
// Check for arrayIndexOutofBound Exception. SInce size is defined as 16
try (Scanner getText = new Scanner(numbers)) {
while (getText.hasNext()) {
numberArray = getText.nextInt();
list[i] = numberArray;
i++;
}
getText.close();
}
System.out.println(numberArray);
int sum = 0;
for (int i = 0; i < list.length; i++) {
sum = sum + list[i];
}
System.out.println(list);
}
}