Show student records from input file - java

I am not able to read and add student records from an input file into an existing array.
The original array size is 10. When the array is full, its size is to be doubled.
If the input file contains 25 records, my array shows only the last 5 records. I know my array expansion coding is incorrect, and I am unable to resolve. Here are my classes:
import java.util.*;
public class ClassPeriod {
private int myNumStudents;
private Student[] myStudents;
private String myClassName;
int N = 10;
public ClassPeriod(String classname){
myClassName = classname;
myNumStudents = 0;
myStudents = new Student[N];
}
// add the Student to the myStudents array. If the array is full, create a new
// one twice the size of the current one. Update myNumStudents accordingly.
public void addStudent(Student st){
for (int i=0; i<1; i++){
if (myNumStudents == 10 || myNumStudents == 20) {//student array size is 10, if 10 is reached, double its size
N = 2*myNumStudents;
myStudents = new Student[N];
}
switch (myNumStudents)
{
case 0: myStudents[0] = st; break;
...
...
case 24: myStudents[24] = st; break;
default: break;
}
myNumStudents++;//increment myNumStudents by 1
}
for (int j=0;j<N;j++){
System.out.println("Students: " + myStudents[j]);
}
}
public Student[] getStudents(){
System.out.println("myNumStudents: " + myNumStudents);
Student temp[] = new Student[myNumStudents];
for (int i=0; i<myNumStudents; i++){
temp[i] = myStudents[i];
}
System.out.println("temp: " + temp.length);
return temp;
}
public String toString(){
String s = new String(myClassName + "\n");
int i;
for (i=0; i<myNumStudents-1; i++)
s += myStudents[i].toString() + "\n";
s += myStudents[myNumStudents-1];
return s;
}
}
and
import chn.util.*;
import java.util.Properties;
import java.util.Enumeration;
import java.util.*;
public class ArrayRecordsSortSearchApplication {
private static final String STUDENT_FILENAME = "students25.txt";
public static void main(String args[]) {
Student[] sortedStudents = null;
ClassPeriod p1 = new ClassPeriod("PERIOD 1");
readClass(p1);
ConsoleIO console = new ConsoleIO();
char choice;
do {
showMenu();
choice = console.readLine().charAt(0);
System.out.println();
switch (choice) {
case '1':
showStudents(p1.getStudents());
case '2':
break;
default:
System.out.println("That's not a choice");
break;
}
} while (choice != '2');
}
public static void showMenu() {
System.out.println();
System.out.println("1) Show students in original order");
System.out.println("2) Quit?");
System.out.print("choice: ");
}
public static void showStudents(Student[] studs){
System.out.print("studs.length: " +studs.length +"\n");
for (int i=0; i<studs.length; i++)
System.out.println(studs[i]);
}
public static void readClass(ClassPeriod p1){
System.out.println("Please wait while data file loads...");
FileInput infile = new FileInput(STUDENT_FILENAME);
do {
int id = infile.readInt();
double gpa = infile.readDouble();
String name = infile.readLine();
Student s = new Student(name,id,gpa);
p1.addStudent(s);
} while ( infile.hasMoreLines() );
infile.close();
}
}

This assignment looks like the implementation of ArrayList. As soon as the size of the old array is exceeded, the new array needs to be created of double size and copy the elements of the old array into a new array and then add the new element to be inserted.
In your code:
if (myNumStudents == 10 || myNumStudents == 20) {//student array size is 10, if 10 is reached, double its size
N = 2*myNumStudents;
myStudents = new Student[N];
....somewhere here you should actually copy all the elements from the old array as first elements of the new array and then insert the new element to be inserted in array.
}

Related

Adding to a string array

Working on a program dealing with encapsulation having trouble adding the user input to the array. And most likely there are other problems in here as well. One being the displaying the output when the user enters option 3. Also, I have no idea how to tell the user that they can't add any more to the bag unless they remove an item. I was just gonna work on figuring out adding and display before I even worry about removing.
import java.util.ArrayList;
import java.util.Scanner;
class Bag {
private String[] bag = new String[5];
public String[] bag() {
return bag;
}
public void add(String bag) {
for (int i = 0; i < bag.length(); i++) {
//...
}
return;
}
public void remove(String bag) {
return;
}
void display() {
System.out.println("The contents are: " + this.bag());
}
}
Here is the second class:
import java.util.ArrayList;
import java.util.Scanner;
public class testBag {
public static void main(String[] args) {
cart obj = new cart();
int menu;
int choice;
choice = 0;
Scanner input = new Scanner(System.in);
ArrayList<testcart> cart = new ArrayList<>();
System.out.println(" 1. Add item ");
System.out.println(" 2. Remove item ");
System.out.println(" 3. Display All");
System.out.println(" 4. Exit ");
menu = input.nextInt();
while (menu != 4) {
switch (menu) {
case 1:
while (choice != 2) {
System.out.println("What do you want to enter: ");
String bag = input.next();
obj.add(bag);
System.out.println("Enter another? 1: Yes, 2: No");
choice = input.nextInt();
}
break;
case 2:
System.out.println("Enter item to Remove: ");
friends.remove(input.next());
break;
case 3:
for (int i = 0; i < obj.bag().length; i++) {
obj.display();
}
break;
}
System.out.println(" 1. Add item ");
System.out.println(" 2. Remove item ");
System.out.println(" 3. Display All items ");
System.out.println(" 4. Exit ");
menu = input.nextInt();
}
}
}
Your Bag class has to have a counter for how many bags it already has, and store a new bag in the corresponding position and increment it.
To display the bags you cannot System.out.println the array directly
To remove you need to loop through all the bags and shift them left from the point where you found the one to remove.
Implementing all of this in your Bag class:
public class Bag {
private String[] bag = new String[5];
private int count = 0; //the new count here
public void add(String bagToStore) {
if (count < bag.length){
bag[count] = bagToStore; //store the new bag in the current position
count++; //then increment it
}
}
//the remove has more logic because it has to shift the bags if it removes one,
//not to leave wholes in the array
public void remove(String bagToRemove) {
boolean found = false;
for (int i=0;i < count; ++i){
if (bag[i].equals(bagToRemove)){ //to compare Strings you must use equals
found = true;
}
if (found && count < bag.length){
bag[i] = bag[i+1];
}
}
if (found) count--;
}
void display() {
for (int i = 0; i < count; ++i) //the display has to be done with a for
System.out.println("The contents are: " + bag[i]);
}
}
Your main class would now have to be adjusted as well:
public static void main(String[] args) {
Bag obj = new Bag();
int menu, choice = 0;
Scanner input = new Scanner(System.in);
do {
//only print the menu once, you can use a do while for that
System.out.println(" 1. Add item ");
System.out.println(" 2. Remove item ");
System.out.println(" 3. Display All");
System.out.println(" 4. Exit ");
menu = input.nextInt();
switch (menu) {
case 1:
while (choice != 2) {
System.out.println("What do you want to enter: ");
obj.add(input.next()); //you call add with input.next as well if you want
System.out.println("Enter another? 1: Yes, 2: No");
choice = input.nextInt();
}
break;
case 2:
System.out.println("What do you want to remove: ");
obj.remove(input.next()); //just call the remove method on Bag
break;
case 3: obj.display(); break; //call the display you already implemented!
}
} while (menu != 4);
}
There are few issues in your implementation of Bag class
You have named String array to store your elements as bad and parameter of add method also as bag, so within add function bag is treated as String rather than String array.
you are not checking the current size of bag before adding elements into bag, you can create a variable named bag and increment it, whenever you add element and decrement it whenever you remove element.
In display method you are printing string array directly instead of elements of array.
I have updated your class by correcting these mistakes
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
class Bag
{
private String bag[] = new String[5];
int size = 0;
Scanner scanner = new Scanner(System.in);
String[] array = new String[2];
public String[] bag(){
return bag;
}
public void add(String item)
{
if( size < bag.length)
{
bag[size] = item;
size++;
}
else
{
System.out.println("Bag is full remove item before new insertion");
}
return;
}
public void remove(String item)
{
}
void display(){
System.out.println("The contents are: " + Arrays.toString(bag));
}
}

Java - Looping through ArrayList to scan for matching value [duplicate]

This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 6 years ago.
I'm trying to write a simple program using an ArrayList that adds values, removes values, and prints values. However, I'm having an issue with removing values that the user inputs. The user should input a designated amount of values (determined by the user) and then the program should remove those values (if there are duplicates then it should just remove the first instance of the number which is fine). It's not removing the values and in some cases removes one value. I'm a bit confused as to where my code is bugged. Here is my code for remove values:
private static void removeVals() {
System.out.println("How many values would you like to remove?");
int amountToRemove = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToRemove + " values:");
for(int i = 0; i < amountToRemove; i++) {
int vals = scanner.nextInt();
if(arrayList.get(i).equals(vals)) {
arrayList.remove(i);
}
}
System.out.println("Values removed");
}
And here is my full code:
public class Main {
private static ArrayList<Integer> arrayList = new ArrayList<Integer>();
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
printOptions();
int option = scanner.nextInt();
while (option != 0) {
switch(option) {
case 1:
addVals();
printOptions();
option = scanner.nextInt();
break;
case 2:
removeVals();
printOptions();
option = scanner.nextInt();
break;
case 3:
printVals();
printOptions();
option = scanner.nextInt();
break;
case 4:
printOptions();
printOptions();
option = scanner.nextInt();
break;
default:
System.out.println("Not a valid option, please enter again:");
option = scanner.nextInt();
break;
}
}
}
private static void addVals() {
System.out.println("How many values would you like to add?");
int amountToAdd = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToAdd + " values:");
for(int i = 0; i < amountToAdd; i++) {
int vals = scanner.nextInt();
arrayList.add(vals);
}
}
private static void removeVals() {
System.out.println("How many values would you like to remove?");
int amountToRemove = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToRemove + " values:");
for(int i = 0; i < amountToRemove; i++) {
int vals = scanner.nextInt();
if(arrayList.get(i).equals(vals)) {
arrayList.remove(i);
}
}
System.out.println("Values removed");
}
private static void printVals() {
for(int i = 0; i < arrayList.size(); i++) {
System.out.print(arrayList.get(i) + " ");
}
System.out.println();
}
private static void printOptions() {
System.out.println();
System.out.println("Program options: ");
System.out.println("1. Add values\n2. Remove values\n3. Print values\n4. Print options\n0. Exit\n");
System.out.println("\nWhat would you like to do? (enter an option):");
}
}
arrayList.remove(i) removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).
that is the bug your code
for more details refer below link
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(int) ,

Store/ Display Data Inputs from Arrays

I'm having problems on how and where to put arrays.
I figured out how and where to put a loop so it will keep on gathering multiple user data that will be stored inside the arrays but I don't know where to put arrays. There will be an array for product numbers, an array for product name, and an array for price.
import java.io.*;
public class DataInsideArrays
{
public static DataInputStream a = new DataInputStream(System.in)
public static void main(String args[])throws Exception
{
int y = 0;
for(int x=1;x<=100;x++)
{
System.out.println("1 - Maintenance");
System.out.println("2 - Transaction");
System.out.println("");
System.out.print("Enter code: ");
int code =
Integer.parseInt(a.readLine());
System.out.println("");
if(code==l)
{
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
System.out.print("Price: ");
int price = Integer.parseInt(a.readLine());
System.out.println("");
}
else if(code==2)
{
System.out.println("Display List of Products-Prices")
System.out.print("Enter product number:
") ;
int prodnum
Integer.parseInt(a.readLine());
System.out.println("")
}
if(code==3)
{
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}}}}
First of all, where do you get this l (lowercase L) value in your for loop? Shouldn't this be 1 (number one)? Furthermore, it would be even better if it is 0 (zero) so you can use it as an index for your array.
Second thing, what's the point of int y = 0'? You are not using y anywhere in your program.
int y = 0;
for(int x = l; x <= 100; x++)
Change it to:
for(int x = 0; x < 100; x++)
Since you want to have 3 separate arrays, you should have 3 separate indexes to keep track of them.
Now let's see how to initialize an array to store the data. You should declare the size as a variable at the top of your class (or locally in your main()) to make it easier to change it later across your program. You can do the same with your array. Declare it inside your class or locally inside the main(). I will show you how to declare both outside of the class, but you should try it the other way too for practice.
Now remember, when using arrays you have to know the size of the array in advance as soon as you create it and you cannot change that size after. This means only that many elements can fit inside the array. If you want variable size structures, check out some of the answers with ArrayLists.
public class DataInsideArrays
{
public static DataInputStream a = new DataInputStream(System.in)
public static int size = 100; // now you only change this number and everything works
public static int[] productNumbers = new int[size];
public static String[] productNames = new String[size];
public static int[] productPrices = new int[size];
public static void main(String args[]) throws Exception
{
int prodnumIndex = 0; // index for tracking product numbers
int prodnameIndex = 0; // index for tracking product names
int prodpriceIndex = 0; // index for tracking product prices
for(int x = 0; x < size; x++)
{
// ... your code...
// ...
int prodNum = Integer.parseInt(a.readLine());
// check if we didn't reach our maximum size
if(prodnumIndex < productNumbers.length) {
productNumbers [prodnumIndex] = prodnum;
prodnumIndex++; // increment
} else {
System.out.println("Cannot add product number. Reached maximum amount.");
}
// ...
String prodName = a.readLine();
// check if we didn't reach our maximum size
if(prodnameIndex < productNames.length) {
productNames [prodnameIndex] = prodName ;
prodnameIndex++; // increment
} else {
System.out.println("Cannot add product name. Reached maximum amount.");
}
// ...
int prodPrice = Integer.parseInt(a.readLine());
// check if we didn't reach our maximum size
if(prodpriceIndex < productPrices.length) {
productPrices [prodpriceIndex] = prodPrice ;
prodpriceIndex++; // increment
} else {
System.out.println("Cannot add product number. Reached maximum amount.");
}
// ...
}
Another way you can achieve this is to create an object called Product that will contain the properties you need and then have an array of that object.
class Product {
int num;
String name;
int price;
Product(int num, String name, int price) {
this.num = num;
this.name = name;
this.price = price;
}
}
// ...
// declare your array of `Product` objects...
Product[] products = new Product[size];
// ...
// then you can do something like
System.out.println("Enter product number:");
int prodNum = Integer.parseInt(a.readLine());
System.out.println("Enter product name:");
String prodName = a.readLine();
System.out.println("Enter product price:");
int prodPrice = Integer.parseInt(a.readLine());
products[INDEX] = new Product(prodNum, prodName, prodPrice);
// ...
Also, consider using a double of a float for the product price since it is more realistic representation of actual products.
Do you have to use an array and "if" statements?
Common practice is to use a List as switch statement:
int[] productArray = new int[100];
List<Integer> productList = new ArrayList<Integer>();
for(int x=1;x<=100;x++) {
switch (code){
case 1:
productArray[x-1] = Integer.parseInt(a.readLine());
productList.add(new Integer(a.readLine()) );
break;
default:
System.out.println("Invalid")
break;
}
}
You should use a List instead of an array, because you don't know a priori the length for them.
A List allows you to dinamically add an element as soon as you got it, so you should "put the array" under the user input.
List<String> names = new ArrayList<String>(); //<-- do the same for price(Integer) and product number (Integer)
public static void main(String args[]) throws Exception) {
//...
if(code==1) //<-- This was a l, check again your code.
{
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
names.add(prodname); //<-- add value to ArrayList
System.out.print("Price: ");
int price = Integer.parselnt(a.readLine());
System.out.println("");
}
//...
}
To print the array content you just need to iterate over the ArrayList:
for(String prodname: names)
System.out.println(prodname); //<-- This will print all your product names
public class DataInsideArrays {
public static DataInputStream a = new DataInputStream(System.in);
List<String> productname=new ArrayList<String>();
public static void main(String args[]) throws Exception {
// rest of your code...
if(code == 1) {
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
System.out.print("Price: ");
int price = Integer.parseInt(a.readLine());
System.out.println("");
////////////////////////to store data place arraylist here/////////////////////////////
productname.add(prod);
///////////////////// //same way use arr to store price and product no
} else if(code == 2) {
System.out.println("Display List of Products-Prices") ;
System.out.print("Enter product number:") ;
int prodnum=Integer.parseInt(a.readLine());
System.out.println("");
}
if(code == 3) {
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}
}
}
Here's the correct codes for the output I want. Maybe is there any other way I can get the same output of this with different coding?
import java.io.*;
import java.util.ArrayList;
public class DataArrays
{
public static DataInputStream a = new DataInputStream(System.in);
public static void main(String args[])throws Exception
{
ArrayList<Integer> prodNum = new ArrayList<Integer>(100);
ArrayList<String> prodName = new ArrayList<String>(100);
ArrayList<Integer> prodPrice = new ArrayList<Integer>(100);
ArrayList<Integer> prodPay = new ArrayList<Integer>(100);
for(int x=1;x<=100;x++)
{
System.out.println("1 - Maintenance");
System.out.println("2 - Transaction");
System.out.println("");
System.out.print("Enter code: ");
int code = Integer.parseInt(a.readLine());
System.out.println("");
int y = 1;
if(code==1)
{
System.out.print("") ;
System.out.println("Product number: "+ x);
prodNum.add(x); //this brings 1st input to array element #0 which is not needed
prodNum.add(x);
System.out.print("Product name: ");
String prodname = a.readLine();
prodName.add(prodname); //this brings 1st input to array element #0 which is not needed
prodName.add(prodname);
System.out.print("Price: ");
int prodprice = Integer.parseInt(a.readLine());
prodPrice.add(prodprice); //this brings 1st input to array element #0 which is not needed
prodPrice.add(prodprice);
System.out.print("Payment: ");
int prodpay = Integer.parseInt(a.readLine());
prodPay.add(prodpay); //this brings 1st input to array element #0 which is not needed
prodPay.add(prodpay);
System.out.println("");
System.out.println("Start New Transaction:");
System.out.println("");
}
else if(code==2)
{
System.out.println("Display List of Products-Prices");
System.out.print("Enter product number: ");
int i = Integer.parseInt(a.readLine());
i = prodNum.get(i); //this gets the data stored in the arraylist. Assuming it starts with 1 and above
prodNum.set(1, i);
System.out.println("");
System.out.println("Product name: "+ prodName.get(i));
System.out.println("Product price: "+ prodPrice.get(i));
System.out.println("Product payment: "+ prodPay.get(i));
System.out.println("");
System.out.println("Start New Transaction:");
}
else if(code>=3)
{
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}
else if(code==0)
{
System.out.println("Program will end");
break;
}}}}
Thank for helping me guys. Really appreciated it.

how to prevent duplicates string in array and

package jellyProblem;
import java.util.*;
public class jellyProblem {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
int studentNumbers = input.nextInt();
input.nextLine();
String [] name =new String [100];
int [] volume=new int[100];
while(true){
if (studentNumbers==0)
break ;
else
for(int i=0;i<studentNumbers;i++){
name[i]=input.next();
int length =input.nextInt();
int width =input.nextInt();
int height =input.nextInt();
System.out.printf("\n%s %d %d %d\n",name[i],length,width,height);
volume[i]=length*height*width;
}
int minimum=0,maximum=0;
for(int i=1;i<studentNumbers;++i){
if (volume[i]<volume[minimum])
minimum=i;
if (volume[i]>volume[maximum])
maximum=i;
}
if(volume[minimum]==volume[maximum])
System.out.println("\nno child lost his jelly\n");
else
System.out.printf("\n%s has lost jelly to %s.\n",name[minimum],name[maximum]);
studentNumbers = input.nextInt();
input.nextLine();
}
}
}
First request I don't know how to:
Prevent string duplicates in names[] array like
I want to stop array if characters of name[] is more than past (names[i].length<=10) it doesn't work with me
Maybe you can do it like this:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int studentNumbers = input.nextInt();
input.nextLine();
List<String> names = new ArrayList<String>();
int[] volume = new int[100];
// clear all data to make it clean
names.clear();
while (true) {
if (studentNumbers == 0)
break;
else
for (int i = 0; i < studentNumbers; i++) {
String studentName = input.next();
// here is how prevent string duplicates in names[] array like
if (names.contains(studentName)) {
continue;
}
if (studentName.length() > 10) {
break;
}
names.add(studentName);
int length = input.nextInt();
int width = input.nextInt();
int height = input.nextInt();
System.out.printf("\n%s %d %d %d\n", names.get(i), length, width, height);
volume[i] = length * height * width;
}
int minimum = 0, maximum = 0;
for (int i = 1; i < studentNumbers; ++i) {
if (volume[i] < volume[minimum])
minimum = i;
if (volume[i] > volume[maximum])
maximum = i;
}
if (volume[minimum] == volume[maximum])
System.out.println("\nno child lost his jelly\n");
else
System.out.printf("\n%s has lost jelly to %s.\n", names.get(minimum), names.get(maximum));
studentNumbers = input.nextInt();
input.nextLine();
}
}
}
a. Instead of using an Array of string you can use an ArrayList. The ArrayList will give you the power to perform various function over the list of String. Incase you want to write your own method and only allow non duplicates to be inserted into the Array then u can iterate over the array and check whether you encounter the same value. eg.
String newName = input.nextLine();
boolean checkDuplicate = dupliacteFunction(newName,name);
boolean dupliacteFunction(String newName , String []nameArray) {
for(String nameValue : nameArray) {
if(newName .equals(nameValue))
return true;
}
else return false;
}
b. String newName = input.nextLine();
newName.length();// This will give u the size of the string being read.
Please try and implement these changes and then we can suggest further alternatives. Happy Coding!!!
To answer your first question, there is no real way to prevent duplicates in an array. I would use an ArrayList object. If it is absolutely impossible to use an ArrayList, you could create a method like this:
public static String[] removeDupes(String[] array){
ArrayList<String> uniqueItems = new ArrayList<String>();
for(String s : array){
if(uniqueItems.contains(s) == false)
uniqueItems.add(s);
}
array = uniqueItems.toArray(array);
return array;
}
And to answer your second question, I don't know what you mean by "stop array" but it seems like all you need is a simple if-statement with exactly the condition you described.

Scanner cannot read input

package algo.chapter1.Ex1_1_33;
import java.util.Scanner;
import edu.princeton.cs.introcs.StdIn;
import edu.princeton.cs.introcs.StdOut;
public class MatrixClient
{
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
while(true)
{
switch (getInput())
{
case 1:
//Dot Product
performDotProduct();
break;
case 2:
performMatrixProduct();
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
StdOut.println("Thank You!");
System.exit(0);
break;
default:
StdOut.println("Invalid Choice!!!");
}
}
}
public static int getInput()
{
StdOut.println("******************************");
StdOut.println("1.Dot Product");
StdOut.println("2.Matrix-Matrix product");
StdOut.println("3.Transpose");
StdOut.println("4.Matrix-Vector Product");
StdOut.println("5.Vector-Matrix product");
StdOut.println("6.Exit");
StdOut.println("******************************");
StdOut.print("\nChoose one from the above: ");
return StdIn.readInt();
}
public static void performDotProduct()
{
StdOut.print("Enter elements of vector A: ");
double[] A = readVector();
StdOut.print("Enter elements of vector B: ");
double[] B = readVector();
StdOut.println("The dot product is: " + Matrix.dot(A, B));
}
public static void performMatrixProduct()
{
StdOut.print("Enter the size of matrix A: ");
int size = scan.nextInt();
double[][] A = readMatrix(size);
for (double[] row : A)
{
for (double item : row)
StdOut.print(item + "\t");
StdOut.println();
}
}
public static double[] readVector()
{
String[] input = scan.nextLine().split(" ");
double[] x = new double[input.length];
for (int i = 0; i < input.length; i++)
x[i] = Double.parseDouble(input[i]);
return x;
}
public static double[][] readMatrix(int N)
{
int counter = 0;
double[][] matrix = new double[N][N];
while (counter < N)
{
StdOut.print("Enter elements of row " + (counter + 1) + ": ");
matrix[counter] = readVector();
counter++;
}
return matrix;
}
}
I'm using readVector() method to read a row of doubles and return a double array. When it is used for dot product, input is being read returned fine, but when I use matrix-matrix multiplication option, readVector() doesn't wait for input. It throws NumberFormatExcpetion: empty string.
I don't understand why readVector() behaves differently.
The problem is in this line:
int size = scan.nextInt();
When your code asks to enter the size of the matrix, you enter a number, and then hit enter. The above code, however, only reads the number that you enter. It does not consume the enter (\n character).
After your code consume the matrix size, your code does:
String[] input = scan.nextLine().split(" ");
which consumes the enter (\n character), and then split it by space. This (scan.nextLine()), of course, returns an empty string.
To fix it, instead of using:
int size = scan.nextInt();
use:
int size = scan.nextInt();
scan.nextLine();
In your code change:
int size = scan.nextInt();
To
int size = scan.nextInt();
scan.nextLine();

Categories