How to input the second line - java

The file that is begin read from is
11 -5 -4 -3 -2 -1 6 7 8 9 10 11
8 -33 -22 -11 44 55 66 77 88
11 and 8, the first integer, begin the size of said array. The resulted output, suppose to be an array, is suppose to be two different array base on their first integer size.
I can read and implement the first line of integer using the following code
public class sortList{
public static void main(String args[]){
try{
Scanner s = new Scanner(new File("data"));
int[] array = new int[s.nextInt()];
for (int i = 0; i < array.length; i++){
if (i == 0){
continue;
}
array[i] = s.nextInt();
System.out.println(array[i]);
}
}
catch(IOException e){
e.printStackTrace();
}
}
}
Now how do I read the second line of integer, cause i searched everywhere here. No avail

You're literally halfway there. You've got one loop to go over the first line. After the first loop has completed, you've effectively exhausted the entire line of text.
What you can do is then advance the scanner to the next line by use of the Scanner#nextLine() method.
Then, you create another array to store your second line of text similar to the way you created the first. You don't need to duplicate your Scanner.
In actuality, you could write it as a separate, concise method, and only call it when you're ready to populate your arrays. Outside of the method (after you call it, that is), you'd advance your scanner to the next line.
public int[] readLine(Scanner fileReader) {
int[] array = new int[fileReader.nextInt()];
for (int i = 0; i < array.length; i++){
array[i] = fileReader.nextInt();
}
return array;
}

public class sortList{
public static void main(String args[]){
try{
Scanner s = new Scanner(new File("data.txt"));
int[] array = new int[s.nextInt()];
for (int i = 0; i < array.length; i++){
array[i] = s.nextInt();
System.out.println(array[i]);
}
s.nextLine();
int[] array1 = new int[s.nextInt()];
for (int i = 0; i < array1.length; i++){
array1[i] = s.nextInt();
System.out.println(array1[i]);
}
}
catch(IOException e){
e.printStackTrace();
}
}

First, remove these three lines:
if (i == 0) {
continue;
}
Then, put a while (s.hasNextInt()) { … } (or so, I didn't look up the documentstion) around the int[] array and the } of the for loop.
To see whether it all works, you should then add System.out.println("one record: " + Arrays.toString(array)); as the last line of the while loop.

Related

Reading a string splitting it and assigning values to 2D array in JAVA

I am trying to split a string with " "(space) and assigning each value on row to each respective array.
The input file contains:
4
2 2
1 3
4 7
3 4
The first line of the file has a single integer value N which is number of jobs.
The next N lines will represent a job, each with 2 values.
How do I start reading from second line from a Input file?
I want to split from Second line and assign it to 2D array. So if (2,2) is there on second line, then 2 should be assigned to array[0][0] and the other 2 to array[0][1]. For next line 1 should be assigned to array[1][0] and 3 should be assigned to array[1][1].
int num = scan.nextInt(); // taking number of jobs from first line
int[][] array = new int[num][num];
while (scan.hasNext()) //It reads till file has next line
{
String str = scan.nextLine();
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
array[i][j] = scan.nextInt();
}
}
}
Had done till here, couldn't figure out further.
int[][] array = new int[num][num];
Wrong dimensions of the array, for N = 4 you create array of 4 * 4, not 4 * 2.
Since the number of columns is fixed in your case, you should create array as new int[num][2] and update reading of the data accordingly.
String str = scan.nextLine();
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
array[i][j] = scan.nextInt();
}
}
Reading a line just to skip it may be redundant if you use Scanner to read the integer numbers using nextInt. So actually you do NOT need to read the data line by line, then split each line into String parts, and convert each part into a number because Scanner class takes care of it.
Also, the innermost loop tries to read N numbers per array row, while it's better to refer actual length of the array in the row.
Thus, it should be ok just to read the data according to the task using Scanner only:
int num = scan.nextInt(); // taking number of jobs from the first line
// preparing array of N rows and 2 columns
int[][] array = new int[num][2];
for (int i = 0; i < num; i++) {
for (int j = 0; j < array[i].length; j++) { // reading 2 ints per row
array[i][j] = scan.nextInt();
}
}
You can make it a lot easier by just ignoring the first line and letting Java do the hard work:
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
import java.util.Arrays;
public class FileToArray {
public static void main(String[] args) {
try {
try (Stream<String> stream = Files.lines(Path.of("arr.txt"))) {
String[][] nums = stream.skip(1).map(s -> s.split(" ")).toArray(String[][]::new);
System.out.println(Arrays.deepToString(nums));
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}

Array rotation TLE (Time Limit Exceeded)

I am really confused why my java code is not working it is giving TLE on Code Monks on Hacker Earth.
Here is the link to the 1
Link to Question
the first question MONK AND ROTATION
import java.util.Scanner;
class TestClass {
static int[] ar=new int[100001];
public static void main(String args[] ){
Scanner in=new Scanner(System.in);
byte t=in.nextByte();
while(t-->0){
int n=in.nextInt();
int k=in.nextInt()%n;
for(int i=0;i<n-k;i++)
ar[i]=in.nextInt();
for(int i=0;i<k;i++)
System.out.print(in.nextInt()+" ");
for(int i=0;i<n-k;i++)
System.out.print(ar[i]+" ");
System.out.println();
}
}
}
I don't know why is it giving TLE I think there is some infinite loop going.
the question at the site is-
Monk and Rotation
Monk loves to perform different operations on arrays, and so being the principal of HackerEarth School, he assigned a task to his new student Mishki. Mishki will be provided with an integer array A of size N and an integer K , where she needs to rotate the array in the right direction by K steps and then print the resultant array. As she is new to the school, please help her to complete the task.
Input:
The first line will consists of one integer T denoting the number of test cases.
For each test case:
The first line consists of two integers N and K, N being the number of elements in the array and K denotes the number of steps of rotation.
The next line consists of N space separated integers , denoting the elements of the array A.
Output:
Print the required array.
Constraints:
1<=T<=20
1<=N<=10^5
0<=K<=10^6
0<=A[i]<=10^6
Sample Input
1
5 2
1 2 3 4 5
Sample Output
4 5 1 2 3
Explanation
Here T is 1, which means one test case.
denoting the number of elements in the array and , denoting the number of steps of rotations.
The initial array is:
In first rotation, 5 will come in the first position and all other elements will move to one position ahead from their current position. Now, the resultant array will be
In second rotation, 4 will come in the first position and all other elements will move to one position ahead from their current position. Now, the resultant array will be
Time Limit: 1.0 sec(s) for each input file
Memory Limit: 256 MB
Source Limit: 1024 KB
I'm not sure about the correctness of your solution, but try to use StreamTokenizer or BufferedReader instead of Scanner. Scanner is too slow and may result in TLE when you need to read a lot of data.
Reduce the number of reads and writes from/to System.in and System.out.
Look at the following solution
Scanner scanner = new Scanner(System.in);
int noOfTestCases = scanner.nextInt();
for (int i = 0; i < noOfTestCases; i++) {
int arraySize = scanner.nextInt();
int noOfRotations = scanner.nextInt();
noOfRotations = noOfRotations % arraySize;
scanner.nextLine();
String inputString = scanner.nextLine();
String[] inputStringArray = inputString.split(" ");
StringBuffer sb = new StringBuffer();
for (int j = 0; j < arraySize; j++) {
sb.append(inputStringArray[(arraySize + j - noOfRotations) % arraySize] + " ");
}
System.out.print(sb);
System.out.println("");
}
import java.util.*;
public class temp {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
int k = sc.nextInt();
int p = 0;
int ar[] = new int[n];
for(int i=0;i<n;i++){
ar[i] = sc.nextInt();
}
k %= n;
for(int i=0;i<n;i++){
p = ar[(i+(n-k))%n];
System.out.print(p+" ");
}
System.out.println();
}
}
}
Though I have not used a big sized array in the starting, this code is working fine for all test cases.
Try this one.
Think from a different perspective. Instead of splitting the string and converting it into an array and applying the iterative logic, we can apply a different logic.
The trick is you just need to find the position of the input string where we have to split only once.
By that I mean,
input=>
6 2       //4 is the length of numbers and 2 is the index of rotation
1 2 3 4 5 6     //array (take input as a string using buffered reader)
Here, we just need to split the array string at the 2nd last space i.e. 4th space. So the output can be achieved by just splitting the string once-
5 6 1 2 3 4
first split- 5 6 + space + second split- 1 2 3 4
This logic worked for me and all the test cases passed.
Also don't forget to cover the corner case scenario when array input string is just one number.
Code Snippet-
int count=0;
for(int k=0; k<arr.length(); k++) {
if(arr.charAt(k)==' ')
count++;
if(count==size-rot) {
System.out.println(arr.substring(k+1,arr.length())
+ " " + arr.substring(0,k));
break;
}
}
Problem is in the System.out.print() call that is inside the for-loop. Thats a fairly heavy call and if called too many times and creates an overhead. This solution works:
//import for Scanner and other utility classes
import java.util.*;
class TestClass {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String input = s.nextLine();
int noOfTests = Integer.parseInt(input);
for (int t = 0; t < noOfTests; t++) {
input = s.nextLine();
String[] str = input.split(" ");
int sizeOfArray = Integer.parseInt(str[0]);
int noOfRotations = Integer.parseInt(str[1]);
String strIntegerArray = s.nextLine();
String[] array = strIntegerArray.split(" ");
printRightRotatedArray(array, noOfRotations, strIntegerArray.length());
}
}
static void printRightRotatedArray(String[] array, int noOfRotations, int lengthOfStr) {
int len = array.length;
int noOfAcutalRotations = noOfRotations % len;
int startingIndex = len - noOfAcutalRotations;
StringBuilder sb = new StringBuilder(lengthOfStr+1);
for (int i = 0; i < len; i++) {
sb.append(array[(startingIndex + i) % len]);
sb.append(" ");
}
System.out.println(sb);
}
}
putting all into string buffer and print at the end worked for me.
class TestClass {
public static void main(String args[] ) throws Exception {
//BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();// output
for(int i=0;i<t;i++){
String [] nk=br.readLine().split(" ");
int n= Integer.parseInt(nk[0]);
int k=Integer.parseInt(nk[1]);
String [] a=br.readLine().split(" ");
int split=n-(k%n);
for (int j = split; j < a.length; j++) {
sb.append(a[j]);
sb.append(' ');
}
for (int j = 0 ; j < split; j++) {
sb.append(a[j]);
sb.append(' ');
}
sb.append("\n");
}
System.out.println(sb);
}
}

Storing the input in 3 dimentional arrays

I want to store the input for different test cases that want to test with my java program .
below the sample input :
1
4 5
2 5 6 8
3 8 5 1 7
Here:
1st line- No of test cases.
2nd line-length of arrays M and N.
3rd line- elements of M array.
4th line: elements of N array .
My problem , how to store all these elements at run time and given them as input my java class .
As #Vamsi krishna suggested, the separate lines for the input are not really relevant. So you can enter the values as arguments to the java command line and read them in your main method:
public static void main(String[] args) {
int i = 0;
int numberOfTests = Integer.parseInt(args[i++]);
int mSize = Integer.parseInt(args[i++]);
int nSize = Integer.parseInt(args[i++]);
int[] mValues = new int[mSize];
for(n = 0; n < mSize; n++) {
mValues[n] = Integer.parseInt(args[i++]);
}
int[] nValues = new int[nSize];
for(n = 0; n < mSize; n++) {
nValues[n] = Integer.parseInt(args[i++]);
}
}
Then call your application with:
java MyApp.class 1 4 5 2 5 6 8 3 8 5 1 7
Note: you did not indicate how the number of test cases should be used. If this means multiple groups of m,n arrays can be specified as input an extra iteration is needed and the m,n arrays must be stored somewhere, for example in another array.
If this simple approach is not good enough (it might be too error prone because of the lack of formatting on the input) you could put the input in a file and read it using java.util.Scanner:
public static void main(String[] args) {
File file = new File(args[0]);
Scanner sc = new Scanner(file);
try {
while (sc.hasNextInt()) {
int i = sc.nextInt();
// see logic above but use sc.nextInt() to get the next int value
}
}
finally {
sc.close();
}
}
Call this with:
java MyApp.class C:\input.txt
And put the input in the file C:\input.txt.
/*
* Sharing the code here with . Yes,there will be multiple test cases in
* the input Suggest any better way if you find
*/
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testcases = Integer.parseInt(br.readLine());
String readinput = "";
int count = 0;
int[][][] array = new int[testcases][3][];
for (int i = 0; i <= array.length; i++) {
readinput = "";
count = 0;
for (int j = 0; j < array[i].length; j++) {
readinput = br.readLine();
count = readinput.split(" ").length;
String[] data = new String[count];
data = readinput.split(" ");
System.out.println(Arrays.toString(data));
for (int k = 0; k < count; k++) {
array[i][j][k] = Integer.parseInt(data[k]);
}
}
}

reading a text file line by line and putting the lines into lists in Java

If I had the following text file:
5 -5 -4 -3 -2 -1
6 -33 -22 -11 44 55 66
(the first # in line is the length of the list)
How do I read the file line by line and then read the integers in each of the lines to create 2 lists?
Desired output of program:
list1 = [-5,-4,-3,-2,-1]
list2 = [-33,-22,-11,44,55,66]
The following is the what I was able to do to get one line done but i dont know how to modify it to continue reading the lines.
import java.util.*;
import java.io.*;
import java.io.IOException;
public class Lists
{
public static void main(String[] args) throws IOException // this tells the compiler that your are going o use files
{
if( 0 < args.length)// checks to see if there is an command line arguement
{
File input = new File(args[0]); //read the input file
Scanner scan= new Scanner(input);//start Scanner
int num = scan.nextInt();// reads the first line of the file
int[] list1= new int[num];//this takes that first line in the file and makes it the length of the array
for(int i = 0; i < list1.length; i++) // this loop populates the array scores
{
list1[i] = scan.nextInt();//takes the next lines of the file and puts them into the array
}
`
I have made list1 to be a 2d array which will be having each of the line as its rows. I am storing the no. of elements of each of the rows of list1 to another array listSizes[] instead of num used in your code. After reading all the lines if you need it in 2 arrays you can move it easily from list1.
Code
int listSizes[] = new int[2];
int[][] list1= new int[2][10];
for(int j = 0; scan.hasNextLine(); j++) {
listSizes[j] = scan.nextInt();
for(int i = 0; i < listSizes[j]; i++)
{
list1[j][i] = scan.nextInt();
}
}
for(int j = 0; j < 2; j++) {
for(int i = 0; i < listSizes[j]; i++)
{
System.out.print(list1[j][i] + " ");
}
System.out.println();
}
Output
-5 -4 -3 -2 -1
-33 -22 -11 44 55 66

No Such Element Exception when reading from a file

I understand that this is a commonly asked question, however, I'm not sure why I'm getting the error even after doing research.
import java.io.*;
import java.util.*;
public class readfile {
private Scanner x;
public void openFile(){
try{
x = new Scanner(new File("input.txt"));
}
catch(Exception e){
System.out.println("Oh noes, the file has not been founddd!");
}
}
public void readFile(){
int n = 0;
n = Integer.parseInt(x.next()); //n is the integer on the first line that creates boundaries n x n in an array.
System.out.println("Your array is size ["+ n + "] by [" + n +"]");
//Create n by n array.
int[][] array = new int[n][n];
//While there is an element, assign array[i][j] = the next element.
while(x.hasNext()){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
array[i][j] = Integer.parseInt(x.next());
System.out.printf("%d", array[i][j]);
}
System.out.println();
}
}
}
public void closeFile(){
x.close();
}
}
I'm reading a text file that contains an adjacency matrix, where the first line indicates how large the matrix will be. ie) line 1 reads 5. Therefore I create a 2d array that is 5x5. The problem I'm having is after I read the file and print it, I get a NoSuchElement Exception. Thanks ahead of time!
Note: I am curious, I've seen that I need to user x.hasNext() when in a loop, so I do not assume there is input when there isn't. However, I've done this. Not sure what the problem is.
Output:
Your array is size [7] by [7]
0110011
1000000
1001000
0010001
0000001
1000001
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at readfile.readFile(readfile.java:32)
at verticies.main(verticies.java:8)
It looks like your code is reading a whole line as an int, is each of those numbers:
0110011 1000000 1001000 0010001 0000001 1000001
meant to be the 7 digits forming each row?
If that is the case, you need to split each value into the its component parts for its corresponding sub array.
In which case, use this section of code instead:
while(x.hasNext()){
for(int i = 0; i < n; i++){
String line = x.next();
for(int j = 0; j < n; j++){
array[i][j] = line.charAt(j) - '0';
System.out.printf("%d", array[i][j]);
}
System.out.println();
}
}

Categories

Resources