How to copy a table to another table greater by 1 - java

I cant use Lists, it must be in tables. How to copy a table to another table greater by 1? Im adding some elements to my table and if there is not enough space i want create new/copy table greater by 1.
Code:
Scanner sc = new Scanner(System.in);
String addNew;
String[] newTab = new String[1];
addNew = sc.next();
for(int i = 0; i<newTab.length; i++) {
if (newTab[i] == null) {
newTab[i] = addNew;
}
else {
//here i want to create new table greater than first one
}
}
Trying with Array.CopyOf but still got error java.lang.ArrayIndexOutOfBoundsException: 1
Code:
int defTab = 1;
for(int i = 0; i<newTab.length; i++) {
if (newTab[i] == null) {
newTab[i] = addNew;
//f
for(int j=0; j<newTab.length; j++) {
System.out.println("array content "+newTab[j]);
}
}
else {
String[] newTab2 = Arrays.copyOf(newTab, defTab+1);
for(int j = 0; j<newTab2.length; j++) {
if (newTab2[j] == null) {
newTab2[j] = addNew;
//f
for(int k=0; k<newTab2.length; k++) {
System.out.println("array content "+newTab[k]);
}
}
}
}
}

Related

How do I get rid of java.lang.NumberFormatException error

This code takes two txt files, reads them puts them in 2d arrays and should check if the numbers in the files are magic squares but it keeps returning NumberFormatException error. I'm new to java so if anyone could help me that would be great. I'm pretty sure the problem come from the txt file being string and the 2d array needing to be in int form. But how and where do I make that conversion on my code?
this is what i have:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class ms {
public static void main(String[] args) throws FileNotFoundException {
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
int nos[][] = null;
nos = getArray(filename1);
boolean b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
System.out.println("\n");
nos = getArray(filename2);
b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
}
private static int[][] getArray(String filename) throws FileNotFoundException {
String line;
int nos[][] = null;
int size = 0, rows = 0;
Scanner sc = null;
try {
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
if (!sc.nextLine().isEmpty())
size++;
}
sc.close();
nos = new int[size][size];
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
line = sc.nextLine();
if (!line.isEmpty()) {
String arr[] = line.split("\t");
for (int i = 0; i < arr.length; i++) {
nos[rows][i] = Integer.valueOf(arr[i]);
}
rows++;
}
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println(e);
}
return nos;
}
private static void printArray(int[][] nos){
for(int i = 0; i<nos[0].length;i++) {
for (int j = 0; j < nos[0].length; j++){
System.out.printf("%-3d",nos[i][j]);
}
System.out.println();
}
}
private static boolean isMagicSquare(int[][] square) {
boolean bool = true;
int order = square.length;
int[] sumRow = new int[order];
int[] sumCol = new int[order];
int[] sumDiag = new int[2];
Arrays.fill(sumRow, 0);
Arrays.fill(sumCol, 0);
Arrays.fill(sumDiag, 0);
for (int row = 0; row < order; row++){
for (int col = 0; col < order; col++) {
sumRow[row] += square[row][col];
}
}
for (int col = 0; col < order; col++) {
for (int row = 0; row < order; row++) {
sumCol[col] += square[row][col];
}
}
for (int row = 0; row < order; row++) {
sumDiag[0] += square[row][row];
}
for (int row = 0; row < order; row++) {
sumDiag[1] += square[row][order - 1 - row];
}
bool = true;
int sum = sumRow[0];
for (int i = 1; i < order; i++) {
bool = bool && (sum == sumRow[i]);
}
for (int i = 0; i < order; i++) {
bool = bool && (sum == sumCol[i]);
}
for (int i = 0; i < 2; i++) {
bool = bool && (sum == sumDiag[i]);
}
return bool;
}
}
SUGGESTION:
Substitute nos[rows][i] = Integer.valueOf(arr[i]); for a custom method that will tell you WHERE the error is occurring.
EXAMPLE:
public static Integer tryParse(String text, int row, int i) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
System.out.println("ERROR: row=" + row + ", i=" + i + ", text=" + text);
return null;
}
}
CAVEAT: This is for helping you troubleshoot ONLY. You definitely wouldn't want to release this in "production code" ;)
What is the NumberFormatException?
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
Offtopic:
A thing that i can notice is that both filesnames have the same name. So you will verify the same file 2 times.
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
I checked your program and you error appears when you put like this on a file:
1. 5 5
2. 5 5
So the error shows beacause you are trying to parse to int the String "5 5". So your code pick the all line and tries to convert to int and " " it's not an int. And there lives the NumberFormatException error.
How do to solve it?
The function that we will work on is the one that you pass from file to an array in
private static int[][] getArray(String filename) throws FileNotFoundException{
The of the function is after we read the file.
As you said, you are leading with a 2d array so to insert all the numbers we need to have loops for each dimension on the array.
So we will start from there.
I will use a while beacause we are dealing with a string and it's easier to verify the text that its left on the line. Will add a new int variable that starts in 0 to pass in every column of a line to use with the while loop. And with this we got this:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
whileIterator++;
}
whileIterator = 0;
}
Next setep, we will divide in 2 behaviors because we will substring the String that has in the line, and will work differently when it's the last number that we are verifying:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need in a line
}else{//All other iterations
whileIterator++;
}
whileIterator = 0;}
To finalize let's add the new logic to insert in nos array. So lets pick all line for example 2 7 6 and we want to add the number 2, so lets do that. You just need to substring(int startIndex, int finalIndex) the line and add to the nos array. After that let remove the number and the space ("2 ") from the line that we are veryfying.
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need
nos[rows][whileIterator] = Integer.parseInt(line.substring(0));//Add to array
line = "";//To not pass the while verification
}else{//All other iterations
nos[rows][whileIterator] = Integer.parseInt(line.substring(0, line.indexOf(" ")));//Add to array
line = line.substring(line.indexOf(" ") + 1);//remove the number we added behind
}
whileIterator++;
}
whileIterator = 0;}
And here you go, that how you add the numbers to an array and don't get the error.
If you need some further explanation just ask. Hope it helps :)

How do I sort a method list in Java?

Down below you'll see an outtake of my code. I need to sort the getTopBids so that the highest bid comes first and after that the second highest one etc.... How do I do this? Very new to Java - this is my first assignment in school!
public String getTopBids(){
StringBuilder topBids = new StringBuilder();
ArrayList<String> topBidsName = new ArrayList<>();
ArrayList<Integer> topBidsAmount = new ArrayList<>();
for(int i = 0; i < 3; i++) {
String name = "";
int amount = 0;
for (Bid bid : this.getBidding()) {
if(amount < bid.getAmount() && !topBidsAmount.contains(bid.getAmount())) {
name = bid.getUser().getName();
amount = bid.getAmount();
}
}
if(amount != 0){
topBidsName.add(name);
topBidsAmount.add(amount);
}
}
for (int i = 0; i < topBidsName.size(); i++){
topBids.append(String.format("%s %d kr", topBidsName.get(i),
topBidsAmount.get(i)));
if(i != topBidsName.size()) topBids.append(", ");
}
return topBids.toString(); }
}
Use
Collections.sort(topBidsAmount);
See also How to use Collections.sort() in Java?

My Remove Method isn't Working

Create a program that keeps track of the following information input by the user:
First Name, Last Name, Phone Number, Age
Now - let's store this in a multidimensional array that will hold 10 of these contacts.
So our multidimensional array will need to be 10 rows and 4 columns.
You should be able to add, display and remove contacts in the array.
*/
import java.util.Scanner;
public class compLab2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[][] contacts = new String [10][4];
System.out.println("Select your options: \n");
while(true){
// Give the user a list of their options
System.out.println("1: Add a new contact to list.");
System.out.println("2: Remove a contact from the list.");
System.out.println("3: Display contacts.");
System.out.println("0: Exit the list.");
// Get the user input
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addContacts(contacts);
break;
case 2:
removeContacts(contacts);
break;
case 3:
displayContacts(contacts);
break;
case 0:
System.out.println("Goodbye!");
System.exit(0);
}
}
}
private static void addContacts (String [][] contacts) {
Scanner input = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
if (contacts[i][0] == null || contacts[i][0].equals(null)) {
contacts[i][0] = input.nextLine();
contacts[i][1] = input.nextLine();
contacts[i][2] = input.nextLine();
contacts[i][3] = input.nextLine();
boolean Inserted = true;
break;
}
}
}
private static void removeContacts(String [][] contacts) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of the contact you want to remove: ");
String removeContact = input.nextLine();
for(int i=0; i<contacts.length; i++){
for(int j = 0; j <contacts[i].length; j++){
if(contacts[i][j].equals(removeContact)) {
contacts[i][0]=" ";
contacts[i][1]=" ";
contacts[i][2]=" ";
contacts[i][3]=" ";
}
}
break;
}
}
private static void displayContacts(String [][] contacts) {
for (int i = 0; i< contacts.length; i++) {
for (int j= 0; j < contacts[i].length; j++) {
System.out.print(contacts[i][j] + " ");
}
System.out.println();
}
}
}
You have to move your break inside the if condition(once element is remove break the loop) otherwise your first for loop will break in i=0 condition.
In if condition you have to check removeContact with contacts[i][j] because contacts[i][j] can be null.
Below you can find the code
if (removeContact != null) { //removeContact should not be null
for (int i = 0; i < contacts.length; i++) {
for (int j = 0; j < contacts[i].length; j++) {
if (removeContact.equals(contacts[i][j])) { //removeContact is not null so check removeContact with contacts[i][j]
contacts[i][0] = " ";
contacts[i][1] = " ";
contacts[i][2] = " ";
contacts[i][3] = " ";
break; //break the loop once you remove
}
}
}
}
You should set null insteam of white space(" ")
if (removeContact != null) {
for (int i = 0; i < contacts.length; i++) {
for (int j = 0; j < contacts[i].length; j++) {
if (removeContact.equals(contacts[i][j])) {
contacts[i][0] = null;
contacts[i][1] = null;
contacts[i][2] = null;
contacts[i][3] = null;
break;
}
}
}
}
Because you are checking null while adding a contact. So setting null will free a space in your array and will allow you to add a new contact to that space.
Also you should check null entry during displaying contacts
private static void displayContacts(String [][] contacts) {
for (int i = 0; i < contacts.length; i++) {
if (contacts[i][0] != null) {
for (int j= 0; j < contacts[i].length; j++) {
System.out.print(contacts[i][j] + " ");
}
System.out.println();
}
}
}
An ArrayList with a custom class can solve this problem easily.

How do I count multiple duplicate elements in an ArrayList?

I have a program that takes in a file list of bands and albums. I need to determine the number of album each band makes and then print out a list of the the bands and the number of albums they made in descending order. I have looked around and seen it done using mapping and collections. I want to know how to do it without either. Here is what I have so far:
public static void processFile(String filename)
{
String bandname = "";
String[][] data = read_spreadsheet(filename);
//takes the file and converts it to a 2d array
ArrayList<String> bands = new ArrayList<String>();
for(int rows = 0; rows < data.length; rows++)
{
bands.add(data[rows][0]);
}
for(int i = 0; i<bands.size()-1;i++)
{
int albumcount = 0;
for(int j = i+1; j<bands.size();j++)
{
if(bands.get(i).equals(bands.get(j)))
{
albumcount++;
}
}
}
}
input example:
band1 -album
band2 -album
band1 -album
band3 -album
band1 -album
band2 -album
output example:
band1: 3
band2: 2
band3: 1
Without collections? You want to use arrays?
String [] names = new String[data.length];
int [] counts = new int[data.length];
int j = 0;
for (int i = 0; i < data.lenght; i++ ) {
while (j < data.length) {
if (data[i][0].equals(names[j])) {
found = true;
counts[j]++;
break;
} else if (names[j] == null) {
names[j] = data[i][0];
counts[j]=1;
break;
}
j++;
}
}
// find max count
// println
// nullify element
// repeat
for (int i = 0; i < j; i++) {
int max = -1;
int k = i;
int pos = -1;
while ( k < j ) {
if ( counts[k] > max ) {
pos = k;
max = counts[k];
}
k++;
}
if ( pos != -1 ) { // we found
System.out.println ( names[pos] + ": " + counts[pos]);
counts[pos] = -1;
}
}
If you sort the list of band names (with duplicates) and then count how many of each band name is in the list, you will get the album count for each band:
public static void processFile(String filename)
{
//takes the file and converts it to a 2d array
String[][] data = read_spreadsheet(filename);
// get all the bands (with duplicates)
ArrayList<String> bands = new ArrayList<String>();
for(int rows = 0; rows < data.length; rows++) {
bands.add(data[rows][0]);
}
// sort the bands alphabetically
Collections.sort(bands);
int albumCount = 1;
String currentBand = bands.remove(0);
while(bands.size() > 0) {
String nextBand = bands.remove(0);
if(currentBand.equals(nextBand)) {
albumCount++;
} else {
// print the current band album count and setup for the next band
System.out.println(currentBand + ": " + albumCount);
currentBand = nextBand;
albumCount = 1;
}
};
// print the final band album count
System.out.println(currentBand + ": " + albumCount);
}

Why is there StringOutofBoundException?

My code needs to read information from the textfile. And the textfile looks like this:
X...................
....................
....................
....................
....................
....................
....................
....................
....................
..X.................
Yes, I need to get # of rows and columns and also identify the number and location of 'X's. I'm almost done except my second constructor is giving me a StringOutOfBoundException in the line:
treasureLocations[location] = new Coord(i, j);
I need help only with the second constructor. Could smb please help me with that?
import java.util.Scanner; // Required to get input
import java.io.File; // Required to get input from files
// A 2D treasure map which stores locations of treasures in an array
// of coordinates
public class TreasureMap{
int rows, cols; // How big is the treasure map
Coord [] treasureLocations; // The locations of treasures
Scanner kbd = new Scanner(System.in);
// Prompt the user for info on the treasure map and then create it
// COMPLETE THIS METHOD
public TreasureMap(){
int numberOfTreasures = 0;
System.out.println("Enter map size (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
System.out.println("Enter number of treasures (1 int): ");
numberOfTreasures = kbd.nextInt();
treasureLocations = new Coord[numberOfTreasures];
for (int i = 0; i < numberOfTreasures; i++)
{
System.out.println("Enter treasure " + i + " location (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
treasureLocations[i] = new Coord(rows, cols);
}
}
// Read the string representation of a map from a file
// COMPLETE THIS METHOD
public TreasureMap(String fileName) throws Exception{
rows = 0;
cols = 0;
int treasures = 0;
char x = 'X';
Scanner data = new Scanner(new File(fileName));
while(data.hasNextLine())
{
String line = data.nextLine();
for (int i = 0; i < line.length(); i++)
{
if(x == line.charAt(i))
{
treasures++;
}
}
cols = line.length();
rows++;
}
int location = 0;
treasureLocations = new Coord[treasures];
Scanner temp = new Scanner (new File(fileName));
while(temp.hasNextLine())
{
String line = temp.nextLine();
for(int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if(x == line.charAt(j))
{
treasureLocations[location] = new Coord(i, j);
location++;
}
}
}
}
}
// true if there is treasure at the given (r,c) coordinates, false
// otherwise
// This method does not require modification
public boolean treasureAt(int r, int c){
for(int i=0; i<treasureLocations.length; i++){
Coord coord = treasureLocations[i];
if(coord.row == r && coord.col == c){
return true;
}
}
return false;
}
// Create a string representation of the treasure map
// This method does not require modification
public String toString(){
String [][] map = new String[this.rows][this.cols];
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
map[i][j] = ".";
}
}
for(int i=0; i<treasureLocations.length; i++){
Coord c = treasureLocations[i];
map[c.row][c.col] = "X";
}
StringBuilder sb = new StringBuilder();
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
sb.append(map[i][j]);
}
sb.append("\n");
}
return sb.toString();
}
}
You should not use the for i as you do. Your i means the current row, doesn't it? So every time you input a line(temp.nextLine()), your i must be added one.
int i=0;
while(temp.hasNextLine())
{
String line = temp.nextLine();
for (int j = 0; j < cols; j++)
{
if(x == line.charAt(j))
{
treasureLocations[location] = new Coord(i, j);
location++;
}
}
}
++i;
}

Categories

Resources