How to take multiple inputs in java in a single line - java

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num = Integer.parseInt(br.readLine()); //Length of Array
int t = num * 2;
String s;
for(int i = 0; i<num; i++) {
s = br.readLine();
}
int[] arr= new int[t];
String[] s1 = s.split(" ");
for(int i=0;i<num;i++)
{
arr[i]=Integer.parseInt(s1[i]);
}
for(int j = 0; j< arr.length; j++) {
System.out.println(arr[j]);
}
Here i have attempted to taken a value in variable num and i want to take input the number of times in a single line according to variable num but if i am printing the arr i am getting only two values which i have given the input in last rest are 0. I think s is replaced with the new input i have entered please help me to solve this

You can add string like this:
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num = Integer.parseInt(br.readLine()); // Length of Array
String s = "";
for (int i = 0; i < num; i++) {
s += br.readLine() + " ";
}
int[] arr = new int[num * 2];
String[] s1 = s.split("[\\s]");
for (int i = 0; i < s1.length; i++) {
arr[i] = Integer.parseInt(s1[i]);
}
System.out.println(Arrays.toString(arr));
}
, output
2
1 2
3 4
[1, 2, 3, 4]

You can try this:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num = 0; //Length of Array
try {
num = Integer.parseInt(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
int t = num * 2;
int[] arr= new int[t];
String s;
for(int i = 0, j = 0; i<num; i++) {
try {
s = br.readLine();
String[] s1 = s.split(" ");
arr[j++] = Integer.parseInt(s1[0]);
arr[j++] = Integer.parseInt(s1[1]);
} catch (IOException e) {
e.printStackTrace();
}
}
for(int j = 0; j< arr.length; j++) {
System.out.println(arr[j]);
}

You can use Scanner Class to directly take the input as integer.
import java.util.Scanner;
public class prac {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int num, i;
num = in.nextInt();
int ar[][] = new int[num][2];
for (i = 0; i < num; i++) {
ar[i][0] = in.nextInt();
ar[i][1] = in.nextInt();
}
for (i = 0; i < num; i++) {
System.out.println(ar[i][0] + " " + ar[i][1]);
}
}
}
OUTPUT :
2
1 5
6 8
1 5 //This is the Output
6 8
The above code is storing input in 2D array. You could store the same in 1D array also.

Related

"Cannot read the array length because "contents" is null" in word unscrambler

I'm trying to program a word unscrambler in java, but I keep getting this error Cannot read the array length because "contents" is null. I tried to use java.io.File, but it also gave me the same error when I tried it.
public static void main(String[] args) throws FileNotFoundException {
String[] contents = txtToString("allwords.txt");
Scanner in = new Scanner(System.in);
System.out.println("Insert your letters");
String input = in.nextLine();
char[] inputArray = input.toCharArray();
for(int i = 0; i < contents.length; i++)
{
for(int j = 0; j < contents[i].length()-1; j++)
{
char[] word = contents[i].toCharArray();
for(int c = 0; c < word.length-1; c++)
{
while(c<inputArray.length)
{
if(word[c]==inputArray[c])
{
word[j]=' ';
for(int s = 0; s < word.length-1;s++)
{
if(word[s]!= ' ')
{
break;
}
else
{
System.out.println("The word is "+contents[i]);
break;
}
}
}
}
}
}
}
}
private static String[] txtToString(String file) {
int count = 0;
try {
Scanner g = new Scanner(new File (file));
while(g.hasNextLine()) {
count++;
}
String[] textToArray = new String[count];
Scanner helloReader = new Scanner(new File(file));
for(int z = 0; z < count; z++) {
textToArray[z] = helloReader.next();
}
return textToArray;
}
catch (FileNotFoundException e){
}
return null;
}
Why am I getting this error?

How to take array size and elements' inputs from a text file in java?

This is for an online judge (Codeforces). Input file is like this
input.txt
6
4 3 2 1 5 6
First line is the array size and second line contains the array elements.
I've tried it by using this
public static int readFiles(String file){
try{
File f = new File(file);
Scanner Sc = new Scanner(f);
int n = Sc.nextInt();
return n;
}
catch(Exception e){
return 0;
}
}
public static int[] readFiles(String file,int n){
try{
File f = new File(file);
Scanner Sc = new Scanner(f);
Sc.nextInt();
int arr [] = new int [n];
for(int count = 0;count < n; count++){
arr[count] = Sc.nextInt();
}
return arr;
}
catch(Exception e){
return null;
}
}
public static void main (String args [] ){
int n = readFiles("input.txt");
int arr [] = readFiles("input.txt",n);
You could call the method that builds the array without provide n:
public static void main (String args [] ){
int arr [] = readFiles("input.txt");
System.out.println(Arrays.toString(arr));
int n = arr.length;
System.out.println("n is: " + n);
}
public static int[] readFiles(String file){
try{
File f = new File(file);
Scanner Sc = new Scanner(f);
int n= Sc.nextInt();
int arr [] = new int [n];
for(int count = 0;count < n; count++){
arr[count] = Sc.nextInt();
}
return arr;
}
catch(Exception e){
System.out.println("The exception is: " + e);
e.printStackTrace();
return null;
}
}
if you need n, you can get it by this line arr.length.
your code will never work because is not even compiling
if this method readFiles(String file) return an int then it makes no sense doing this
int arr [] = readFiles("input.txt",n);
hint:
read the file line by line,
check if spaces are there
get the numbers as string
parse those into integers
put them in the array
return at the end that array.
You could add a bufferedreader to read the lines one at a time, like this.
public static void main(String[] args) {
int[] numberArray = readFile();
}
public static int[] readFile(){
try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
int arraySize = Integer.parseInt(br.readLine());
String[] arrayContent = br.readLine().split(" ");
int[] newArray = new int[arraySize];
for(int i = 0; i<arraySize; i++){
newArray[i] = Integer.parseInt(arrayContent[i]);
}
return newArray;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Why don't you try this on your for loop to split the numbers between empty spaces and store it in an array :
int temp[] = Scanner.readLine().split(" ");

Importing data from file into an int array that's called from a different class

I am working on a program that deals with inheritance. Below is one of the class that is extended from my super class bus.
public BusTrip(){
super();
int totalPassenger = 0;
fare = new int [3];
numOfPassenger = new int [3];
String destination = "";
}
I am having trouble in my driver class to import data into my ArrayList. I understand that it's reading everything in the data file position 4 all the way to the end of to the string. I have tried a while loop as well but that does not seem to go past the first set of data. Is tokenizer the only method? Is there a way for me to prevent the for loop from reading pass a certain point?
Data File
cr, greyhound, 2015, 30, 22, 44, 14, 10, 5, 15, New York
public static void readAllBus(ArrayList<Bus> busInformation){
File infile = null;
Scanner scan = null;
int[] fare = new int [3];
int[] numOfPassenger = new int [3];
try{
infile = new File("busData.csv");
scan = new Scanner(infile);
}//end try
catch(FileNotFoundException e){
System.out.println("Error! File not found!");
System.exit(0);
}//end catch
while(scan.hasNext()){
String [] str = scan.nextLine().split(",");
if(str[0].equals("cr")){
for(int i = 0; i < fare.length; i++)
for(int j = 4; j < str.length; j++)
fare[i] = Integer.parseInt(str[j]);
//error For input string: "Bahamas"
for(int i = 0; i < numOfPassenger.length; i++)
for(int j = 7; j < str.length; j++)
numOfPassenger[i] = Integer.parseInt(str[j]);
//error For input string: "Bahamas"
busInformation.add(new BusTrip(str[1],
Integer.parseInt(str[2]),
Integer.parseInt(str[3]),
fare,
numOfPassenger,
str[10]));
}//end if
}//end while
}//end readAllBus
I think you have a bug in the for loop. You are executing the inner loop multiple times when you just wanted to read the value only once. You could rewrite your logic as follows -
public static void readAllBus(ArrayList<Bus> busInformation){
File infile = null;
Scanner scan = null;
int[] fare = new int [3];
int[] numOfPassenger = new int [3];
try{
infile = new File("busData.csv");
scan = new Scanner(infile);
}//end try
catch(FileNotFoundException e){
System.out.println("Error! File not found!");
System.exit(0);
}//end catch
while(scan.hasNext()){
String [] str = scan.nextLine().split(",");
if(str[0].equals("cr")){
if(str.length>7){
for(int i = 0; i < 3; i++){
fare[i] = Integer.parseInt(str[i+4]);
}
}
if(str.length>10){
for(int i = 0; i < 3; i++){
numOfPassenger[i] = Integer.parseInt(str[i+7]);
}
}
busInformation.add(new BusTrip(str[1],
Integer.parseInt(str[2]),
Integer.parseInt(str[3]),
fare,
numOfPassenger,
str[10]));
}//end if
}//end while
}//end readAllBus

Unable to scan all the elements of the string array using scanner in java

I am unable to scan all the elements of the string array in Java. I don't know what is the error.. please help
I'm unable to scan the first element of the array.its not even showing an error.
import java.util.*;
public class uhu {
public static void main(String[] args) {
System.out.println("Hit n");
Scanner sc = new Scanner(System.in);
try {
int n = sc.nextInt();//scan the size of the array
String[] str=new String[n];
System.out.println("Enter elements");
for (int i = 1; i < n; i++) //scanning the elements
{
str[i]=sc.nextLine();
}
for (int i = 0; i < n; i++) //printing all the elements
{
System.out.println(str[i]);
}
} finally {
if (sc != null)
sc.close();
}
}
}
Here you go :
System.out.println("Enter elements");
for (int i = 0; i < n; i++) //scanning the elements
{
str[i]= sc.next();
}
start from i=0 and use next() instead of nextLine().
In case you want to read whole lines then a BufferedReader will do the job, here in our case Scanner nextLine() is skipping the last line or taking a blank line as input at the end.
Use BufferedReader to get your job done.
System.out.println("Hit n");
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
try {
int n = Integer.parseInt(buf.readLine());//scan the size of the array
String[] str=new String[n];
System.out.println("Enter elements");
for (int i = 0; i < n; i++) //scanning the elements
{
str[i]= buf.readLine();
}
for (int i = 0; i < n; i++) //printing all the elements
{
System.out.println(str[i]);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (buf != null)
buf.close();
}

read file, convert string to double, store in 2d array

I need to read a list of numbers in a file and store it into a 2d array.
This is what I have so far. How would I go about achieving this goal?
//this is only part of my code
public class RainFall
{
double[][] precip;
public RainFall()
{
precip = new double [5][12];
}
public void readFile(BufferedReader infile) throws IOException
{
FileInputStream infile = new FileInputStream("numbers.dat");
BufferedReader br = new BufferedReader(new InputStreamReader(infile));
String[][] myarray = new String[5][12];
while (infile.readLine() != null)
{
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < 12; i++)
{
myarray[j][i] = infile.readLine();
}
}
}
infile.close();
}
numbers.dat is 60 lines of:
1.01
0.03
2.14
0.47
//Is each number on a new line? You're very close, I added a few lines below.
public class RainFall
{
double[][] precip;
public RainFall()
{
precip = new double [5][12];
}
public void readFile(BufferedReader infile) throws IOException
{
//FileInputStream infile = new FileInputStream("numbers.dat");
BufferedReader br = new BufferedReader(new FileReader("numbers.dat"));
String line = "";
String[][] myarray = new String[5][12];
while ((line = br.readLine()) != null)
{
double num = Double.parseDouble(line.trim());
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < 12; i++)
{
precip[j][i] = num;
}
}
}
br.close();
}
Instead of
String[][] myarray = new String[5][12];
use
double[][] myarray = new double[5][12];
Then sub this into the loop:
myarray[j][i] = Double.parseDouble(infile.readLine());

Categories