get 2D array from text file - java

I'm trying to get the 2D array from the text file. So far I accessed the file and got all the numbers in the file, but all these numbers are string so I used split() and then convert it to double. How can convert this to double 2D array?
1.65 4.50 2.36 7.45 3.44 6.23
2.22 -3.24 -1.66 -5.48 3.46
4.23 2.29 5.29
2.76 3.76 4.29 5.48 3.43
3.38 3.65 3.76
2.46 3.34 2.38 8.26 5.34
This is what I have so far:
public static void main(String[] a) throws FileNotFoundException {
File file = new File("district3.txt");
Scanner scan = new Scanner(file);
String b;
String[] c;
int r = 6;
double[][]arr = new double[r][];
while(scan.hasNextLine()) {
//get number as String
b = scan.nextLine();
//split them
c = b.split(" ");
for(String i:c)
System.out.println(Double.parseDouble(i) );
}
}

Change your for to print inline and then add a println after you've printed all the numbers:
for(String i:c)
System.out.print(i + " ");
System.out.println()
To store the numbers you can do the following:
double[][]arr = new double[r][];
int i = 0;
while(scan.hasNextLine()) {
//get number as String
b = scan.nextLine();
//split them
c = b.split(" ");
arr[i] = new double[c.length];
for(int j = 0; j < c.length; ++j) {
arr[i][j] = Double.parseDouble(c[j]);
// Display them if needed
System.out.print(c[j] + " ");
}
System.out.println();
++i;
}

Related

Finding multiple set of given words in a paragraph array

I'm searching for word(s) in a string array and if found I want to return their line.
I have tried to divide the searched input in an array and then search it in the paragraph array line by line. Which does not really work.
public static void main(String[] args) {
String paragraph[] = new String[10];
String toBeSearched;
String curSearch;
boolean intIndex = false ;
paragraph[0] = "Hello my name is";
paragraph[1] = "Jack the reaper";
paragraph[2] = "what up";
System.out.printf("enter string:");
Scanner myScanner = new Scanner(System.in);
toBeSearched = myScanner.nextLine();
String[] divide = toBeSearched.split(" ");
for(int j = 0 ;j <=10 ; j++) {
curSearch = divide[j];
for (int k = 0; k <=paragraph[j].length() ; k++) {
intIndex = paragraph[j].contains(curSearch);
if(intIndex == true) {
System.out.printf("Found at line %d \n",j );
}
}
}
Assuming I can search for at most 10 words at a time.
Lets say user enters : "Hello name the up"
I want the answer : At line 1
At line 1
At line 2
At line 3
If I ask for a word in the 2nd or the 3rd index of the paragraph it does not work I dont understand why (getting no error messages)
Here is a working code compare it to yours and figure out the issue:
public static void main(String[] args)
{
String paragraph[] = {"Hello my name is","Jack the reaper", "what up"};
String toBeSearched;
String curSearch;
boolean intIndex = false ;
System.out.printf("enter string:");
Scanner myScanner = new Scanner(System.in);
toBeSearched = myScanner.nextLine();
String[] divide = toBeSearched.split(" ");
for(int i = 0; i < divide.length ; i ++) {
String word = divide[i];
for(int y = 0; y < paragraph.length ; y++) {
if(paragraph[y].contains(word)) {
System.out.println(word+ "found at line: "+ y);
}
}
}
}

Where am I doing wrong in getting the outputs?

import java.util.Scanner;
public class Qa2QeArray2 {
public static void main(String[] args) {
int numOfAircrafts;
Scanner sc = new Scanner(System.in);
System.out.print("Enter num Of Aircrafts : ");
numOfAircrafts = sc.nextInt();
//To Determine the length of the Array
String[] stringArray = new String[numOfAircrafts];
System.out.println("Please enter the names of the Aircrafts : ");
for(int i = 0; i < numOfAircrafts; i++)
{
stringArray[i] = sc.next();
}
//To insert the string values to the Array
double[] doubleArray = new double[numOfAircrafts];
System.out.println("Please enter the shipment rate through each aircraft carrier : ");
for(int i = 0; i < numOfAircrafts; i++)
{
doubleArray[i] = sc.nextDouble();
}
//To insert the double values to the Array
String[] dubArr = new String [stringArray.length * doubleArray.length];
for (int x = 0; x < stringArray.length ; x++)
for (int y = 0; y < doubleArray.length ; y++) {
System.out.println(stringArray[x] + " \t " + doubleArray[y]);
}
}
}
I am looking for o/p as below
Emirates 20.89
Indigo 10.34
But I am getting o/p as
Emirates 20.89
Emirates 10.34
Indigo 20.89
Indigo 10.34
You have two nested loops that are running.
The x loop and y loop.
When x=0 prints the values and again when x=1
it prints values.
That is why you are getting output two times.
Remove one loop and you are good to go.

Java exception error for input string

I am a beginner in Java programming. I am trying to write a simple program to take size of input followed by list of numbers separated by spaces to compute the sum.
The first input is getting in fine for the second one system shows error as it is trying to parse a blank string into integer. Can you please help with the mistake I am making?
import java.util.Scanner;
public class InputStringforarray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print(" Enter size of input ");
int num = scan.nextInt();
System.out.println("Enter data separated by spaces: ");
String line = scan.nextLine();
String[] str = line.split(" ");
int[] A = new int[num];
int sum = 0;
for (int i = 0; i < num; i++)
A[i] =Integer.parseInt(str[i]);
for (int i = 0; i < num; i++)
sum = sum + A[i];
System.out.println("Sum is " + sum);
}
}
The reason you get an exception in your code is because int num = scan.nextInt(); does not process the newline character after the number.
So when the statement String line = scan.nextLine(); is used, it processes the newline character and hence you get an empty string ""
You can either fetch the entire line and parse it to Integer, like this:
int num = Integer.parseInt(scan.nextLine());
or you can go with using nextInt() and then use a blank scan.nextLine() to process the new line after the number, like this:
int num = scan.nextInt();
scan.nextLine();
Your Program has only one error that you were making only one scan object of scanner class, you have to make two scanner class object one will help in getting array size while another will help in getting array element.
import java.util.Scanner;
public class InputStringforarray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scan1 = new Scanner(System.in); // change 1
System.out.print(" Enter size of input ");
int num = scan.nextInt();`enter code here`
System.out.println("Enter data separated by spaces: ");
String line = scan1.nextLine();// change 2
String[] str = line.split(" ");
int[] A = new int[num];
int sum = 0;
for (int i = 0; i < num; i++)
A[i] =Integer.parseInt(str[i]);
for (int i = 0; i < num; i++)
sum = sum + A[i];
System.out.println("Sum is " + sum);
}
}

Reading int, double and strings and ignore tokens

12.9 ; I # 13 jav
3.8 ; can # 6 aru
4.0 ; read # 109 les
The program is supposed to read this in as a string and then add all the doubles, integers, and then to add the first string together and the last string together. So the program should provide
Double total : 20.7
Integer total : 128
Line : I can read
Word: javarules
This is what I have so far , I know that I have to use scanner to skip over the tokens .
public class Test {
public static void main (String args[]) throws FileNotFoundException {
Scanner sc = new Scanner(Test4.class.getResourceAsStream("week2inputdata.txt"));
double doubletotal = 0;
int inttotal = 0;
String line = " ";
String word;
Scanner scanLine;
while (sc.hasNextLine()){
scanLine = new Scanner (sc.nextLine());
scanLine.next();
line += sc.hasNextLine();
inttotal += sc.nextInt();
// scanLine = new Scanner (sc.nextLine());
// scanLine.next();
// line += sc.next() + " ";
// inttotal += sc.nextInt();
doubletotal += sc.nextDouble();
}
System.out.println(inttotal);
System.out.println(doubletotal);
System.out.println(line);
}
}
This is rather ugly but it will work,
String[] weirdLookingString = new String[] { "12.9 ; I # 11 jav", "3.8 ; can # 11 aru"
,"4.0 ; read # 109 les" };
double doubleValue = 0.0;
String strValue1 = "";
String strValue2 = "";
int integerValue = 0;
for (int i = 0; i < weirdLookingString.length; i++) {
String array[] = weirdLookingString[i].split("[;\\#]\\s+");
String lastString[] = array[2].split("\\s");
integerValue += Integer.parseInt(lastString[0]);
doubleValue += Double.parseDouble(array[0]);
strValue2 += lastString[1];
strValue1 += array[1];
}
System.out.println("Integer value: " + integerValue);
System.out.println("Double value: " + doubleValue);
System.out.println("Words: " + strValue2);
System.out.println("Line: " + strValue1);
output,
Integer value: 131
Double value: 20.7
Words: javarules
Line: I can read
You can create an arraylist of double, Integers and then create a sb builder for the first set of string and a stringBuilder for the second set of strings.
String line = "12.9 ; I # 13 jav";
String str[] = line.split("[;\\#\\s+]");
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
ArrayList<Double> doubleArray = new ArrayList();
ArrayList<Integer> intArray = new ArrayList();
for(int i =0; i < str.length; i++){
if(i == 0){
doubleArray.add(Double.parseDouble(str[i]));//convert to double and add it to the list
}else if(i == 1){
sb.append(str[i]);
}else if(i == 2){
doubleInt.add(Integer.parseInt(str[i]));//convert it to integer and add to the list
}else if(i == 3){
sb2.append(str[i]);
}
}
you can put everything in a loop so you won't have to rewrite everything. after everything has been added you can build a string using the stringBuilder and add everything using the array from arrayList

How do I add user input to an Array in java?

public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int i;
int n;
String a;
System.out.println("Enter the Class:");
a = user_input.next();
System.out.println("Enter the number of Students:");
n = user_input.nextInt();
for (i= 1; i <= n; i++) {
String g = a + i;
System.out.println(g);
}
}
This is my program. It gets user input for the Class and prints the Roll Number for the students.
For example: If the class is 10A and the number of students is 10, it prints a series like 10A1 , 10A2, 10A3 ... 10A10
How do I get the program to store these as elements in an array?
For example:
array[0] = 10A1;
array[1] = 10A2;
array[2] = 10A3;
etc.
Your code should look like this:
public static void main (String args[])
{
Scanner user_input = new Scanner(System.in);
int i;
int n;
String a;
System.out.println("Enter the Class:");
a = user_input.next();
System.out.println("Enter the number of Students:");
n = user_input.nextInt();
String []strings = new String[n]; // Creating an are of string with the given number
for(i= 0; i < n ;){
strings[i] = a + ++i; // Storing strings on to the array !
System.out.println(strings[i-1]);
}
}
You can just edit each index in your current for loop:
String[] arr;
for(i=0; i < n ; i++){
int j = i+1;
String g = a + j;
System.out.println(g);
arr[i] = g;
}
So all your printed g's will be part of the array arr.
First, declare a String array of the appropriate size.
Second, in your for loop, assign the strings you are currently printing, to positions in the array.
String[] things = new String[n];
for (i=1; i <= n; i++) {
String g = a + i;
System.out.println(g);
things[i-1] = g;
}
The strings are now in an array.
Following code is modified, for storing values in array.
public static void main(String[] args) {
// TODO code application logic here
Scanner user_input = new Scanner(System.in);
int i;
int n;
String a;
System.out.println("Enter the Class:");
a = user_input.next();
System.out.println("Enter the number of Students:");
n = user_input.nextInt();
String[] arr = new String[n]; // create string array of size n.
for(i= 1; i <= n ; i++){
String g = a + i;
System.out.println(g);
arr[i-1]=g; // assign your g veriable vale to array index
}
for(String s : arr){
System.out.println(s); // print your array
}
}

Categories

Resources