How to use System.arraycopy? - java

I want to read from a txt file and I am using System.arraycopy to copy
parts[] to scores[].
I know that scores must be a String in order to work. My
constructor has to be an int[] array for scores. So scores is an int[]. Is there any solution?
private void processLine(String line) {
String mygoden1 = "";
//String mygoden2 = "";
try {
String parts [] = line.split(",");
mygoden1= parts[0];
Name name = new Name(parts[1]);
int gN1=Integer.parseInt(mygoden1);
String gL= parts[3];
//gL = gL.trim();
String gC = parts[4];
gC=gC.trim();
int scoresLength = parts.length-4;
String scores[]=new String[scoresLength];
System.arraycopy(parts,4,scores, 0, scoresLength);
Gamer g1 = new Gamer(gN1 ,name,scores, gL, gC);
this.add(g1);
}
This is my constructor:
public class Gamer {
private int gnumb; //The Gamers Number g -> is for gamer
private Name gamerName;
private String glevel;
private String gCountry;
private static final int SCORES_1 =5;
private int [] scores;
//}
public Gamer(int gN ,Name name, int gS[], String gL , String gC)
{
gnumb = gN;
gamerName=name;
scores = new int [SCORES_1];
scores=gS;
glevel =gL;
gCountry =gC;
}

I would replace
String scores[]=new String[scoresLength];
System.arraycopy(parts,4,scores, 0, scoresLength);
with
int[] scores = new int[scoresLength];
for(int i = 0; i < scoresLength; i++)
scores[i] = Integer.parseInt(parts[i + 4]);

Don't use System.arraycopy when you need to transform data. Iterate over parts and parseInt() each element, then store it in scores.

Related

How to group every [0][1][2] of an Array to create a new object?

I have an array and I want to assign values in group of 3s
Name, Id, Population, Name, Id, Population, Name, Id, Population etc.
Is there a way to do that?
This is what I have
while (scanner.hasNext()) { `
scanner.useDelimiter(",");`
list.add(scanner.nextLine());}`
for(int i=0; i<list.size(); i++){
String n = list.get(i);
System.out.println("Hopefully going thru " + n);} //for me to check
String ar =list.toString();
Object [] a = ar.split(",");// splitting the array for each string
for(int h=0;h<a.length;h+=3) { // for [0] += 3 is Name
for(int j=1;j<a.length; j+=3) { // for [1] += 3 is Id
for(int k=2; k<a.length;k+=3) { //for[2]+= is Population
String name = a[h].toString();
String id = a[j].toString();
String population = a[k].toString();
System.out.println("name is "+ name);// this is just to check correct values
System.out.println("id is "+ id);// this is just to check correct values
System.out.println("population is " +population);// this is just to check correct values
CityRow cityRow = new CityRow(name,id,population); //?? I want every set of [0][1][2] to create a new object`
I don‘t think that ar has the correct data and I don‘t understand why you don’t work with list directly, but assuming that ar has the correct data, it should be possible to use:
for(int = 0; i < ar.length ; ) {
var cityRow = new CityRow(
ar[i++],
ar[i++],
ar[i++]
);
// remember to add cityRow to an
// appropriate list
}
You use Scanner so no need to split an array. You can read each separate value one-by-one directly from it.
public class Main {
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\n|,");
System.out.print("Total groups: ");
int total = scan.nextInt();
List<City> cities = readCities(scan, total);
printCities(cities);
}
private static List<City> readCities(Scanner scan, int total) {
List<City> cities = new ArrayList<>(total);
System.out.println("Enter each city on a new line. Each line should be: <id>,<name>,<population>");
for (int i = 0; i < total; i++) {
String id = scan.next();
String name = scan.next();
int population = scan.nextInt();
cities.add(new City(id, name, population));
}
return cities;
}
private static void printCities(List<City> cities) {
System.out.println();
System.out.format("There are total %d cities.\n", cities.size());
int i = 1;
for (City city : cities) {
System.out.format("City №%d: id=%s, name=%s, population=%d\n", i++, city.id, city.name, city.population);
}
}
static class City {
private final String id;
private final String name;
private final int population;
public City(String id, String name, int population) {
this.id = id;
this.name = name;
this.population = population;
}
}
}

Class object array can get only one object

So recently I've got into this problem, that every time I try to add two+ cars(trucks, busses or vehicles) program gets null pointer reference. Seems like my array can only hold one object. Why is that? Array size is set to 200... Adding one object works like a charm. This also works on C#. But not in Java.
public class Town {
public int MaxNumberOfCars = 200;
public String Dealership;
public String Adress;
public String Phone;
public Car[] Cars = new Car[MaxNumberOfCars];
public Bus[] Busses = new Bus[MaxNumberOfCars];
public Truck [] Trucks = new Truck[MaxNumberOfCars];
public Vehicles[] Vehicles = new Vehicles[MaxNumberOfCars];
public static int carCount;
public static int busCount;
public static int truckCount;
public static int vehicleCount;
public int townVehicleCount;
public int DealershipCount;
public double avgage;
public Town(String dealership, String adress, String phone) {
Dealership = dealership;
Adress = adress;
Phone = phone;
}
public void AddCar(Car car) {
Cars[carCount++] = car;
vehicleCount++;
}
The code where I'm accesing the AddCar:
private static void Read(String text, Town[] towns) {
String text1 = text;
String dealership = null, adress = null, phone = null;
ArrayList<String> line = new ArrayList<>();
StringTokenizer st = new StringTokenizer(text1, "\n");
int count = st.countTokens()-3;
if (line != null) {
dealership = st.nextToken();
adress = st.nextToken();
phone = st.nextToken();
towns[townCount] = new Town(dealership, adress, phone);
for(int i = 0; i < count; i++) {
String string = st.nextToken();
String[] values = string.split(";");
String licenseplates = values[0]; // 004
char type = values[1].charAt(0);
String brand = values[2];
String model = values[3];
YearMonth yearofmake = YearMonth.parse(values[4]);
YearMonth techinspection = YearMonth.parse(values[5]);
String fuel = values[6];
int fuelconsumption = Integer.valueOf(values[7]);
switch (type) {
case 'c':
Car car = new Car(licenseplates, brand, model, yearofmake, techinspection, fuel, fuelconsumption);
towns[townCount].AddCar(car);
towns[townCount].AddVehicle(car);
break;
}
townCount++;
}
}
}
Your problem is that you are incrementing townCount without there being enough towns in your array towns. You need to either add more towns to your array, or delete the townCount++; line at the end of your for loop.
Why your count variables are static?
I think first you must change this. then you must add some validation like checking MaxNumberOfCars validation in your addCar method.

Variables being ran generated are displaying int or displaying cards suits (Black Jack program) [duplicate]

public void crearCliente() {
int i, k, j, l;
registro r = new registro();
k = lr.getSize();
for (i = 0; i < k; i++) {
r = lr.get(i);
l = r.getSize();
String contenido[] = new String[8];
for (j = 0; j < l; j++) {
contenido[j] = r.getCampoR(j);
//System.out.println(contenido[j]);
}
c1 = new Cliente(contenido[0], contenido[1], contenido[2], contenido[3], contenido[4], contenido[5], contenido[6], contenido[7]);
c1.verCliente();}
In this code, at the end,I assign a value to c1, but when I print it i get null in all the c1 fields. I write my code down for the class Cliente.
I want to print all the values i gave to c1 but i do not know why it print null in all the fields. I follow the code using the debugger and everything is right until the sentences which assign all the values to the new variable.
public class Cliente {
private String Id_cliente;
private String Cod_postal;
private String Numero;
private String Calle;
private String Provincia;
private String Poblacion;
private String Telefono;
private String Apellidos;
public Cliente(String idc, String cp, String num, String cal, String prov, String pob, String tlf, String aps){
idc = Id_cliente;
cp = Cod_postal;
num = Numero;
cal = Calle;
prov = Provincia;
pob = Poblacion;
tlf = Telefono;
aps = Apellidos;
}
public void verCliente(){
System.out.println("Id_cliente: "+ Id_cliente);
System.out.println("Codigo postal: "+ Cod_postal);
System.out.println("Numero: "+ Numero);
System.out.println("Calle: "+ Calle);
System.out.println("Provincia: "+ Provincia);
System.out.println("Poblacion: "+ Poblacion);
System.out.println("Telefono: "+ Telefono);
System.out.println("Apellidos: "+ Apellidos);
}
}
You should change this
idc = Id_cliente;
to
Id_cliente = idc;.
You are assigning a values to your method parameters, rather than fields. Same applies to all of the parameters in your constructor Cliente.
Your assignments are backwards in your constructor. Switch the left and right hand sides of all those and it should work.
Your constructor for the class Cliente is switching assignement.
Change the idc = Id_cliente to Id_cliente = ic.

Reading input from a text file using scanner into array

I am trying to read the input from a text file using scanner class and pass into an array. I know how to read the input using scanner class. The only problem I am facing here is I am unable to pass into the array.
public class ReadItemData {
public static void main(String[] args) throws Exception {
Scanner aScanner = new Scanner(new FileReader(
"src//chapter11//Items.txt"));
while (aScanner.hasNext()) {
String code = aScanner.next();
String sku = aScanner.next();
double qty = aScanner.nextDouble();
System.out.println(code + " " + sku + " " + qty);
}
}
The above code works without the array concept. I want to extend the same concept to read the above data into a array of size 100. Any suggestions would be helpful. My final aim is to sort the input which is in array by code,sku
This is how I used comparable interface for sorting. How can I extend this concept for arrays?
I used something like this for sorting(without the array concept)
class Item implements Comparable {
private int qty;
private String sku,code;
public Item(int qty, String sku,String code) {
this.qty = qty;
this.sku = sku;
this.code = code;
}
public int getQty() {
return qty;
}
public String getSku() {
return sku;
}
public String getCode() {
return code;
}
public int compareTo(Object o) {
Item i = (Item) o;
if (this.getQty() < i.getQty())
{
return -1;
}
if (this.getQty() > i.getQty())
{
return 1;
}
return 0;
}
}
Thanks!!
String[] array = new String[100];
int currentIndex = 0;
while (aScanner.hasNext()) {
String code = aScanner.next();
String sku = aScanner.next();
double qty = aScanner.nextDouble();
array[currentIndex] = code;
array[currentIndex++] = sku;
array[currentIndex++] = ""+qty;
currentIndex++;
}
As mentioned in the comments, you can use 2D array of 100 rows and 3 columns like this:
Object[][] array = new Object[100][3];
int i=0,j=0;
while (aScanner.hasNext()) {
String code = aScanner.next();
String sku = aScanner.next();
double qty = aScanner.nextDouble();
array[i][j++] = code; // array of row i and columns j
array[i][j++] = sku;
array[i][j] = qty;
i++; // increment i since it's for rows
j=0;//reset j because it's for columns
}

How to pass a multidimensional array into constructors?

I'm declate the multidimensional array propertyArray = new int[numbHuman][40]
where [numbHuman] is the number of rows, and the [40] is the number of columns (or vice versa doesnt really matter). Anyway I create those propertyArray's in a nested for loop, but I'm not sure How I'd pass propertyArray[][] into the player object constructor. Here is my code, I will try to clarify if needed.
import java.util.Scanner;
import java.util.Random;
public class PlayerArray
{
Scanner scan = new Scanner(System.in);
private int numbHuman;
private Player[] arr;
private String[] userName;
//private
private int[] testArray;
private int[][] propertyArray;
private int[] userID;
private int startingMoney;
private int startingPosition;
private int b;
private int c;
private int i;
//private int d;
public PlayerArray()
{
Scanner scan = new Scanner(System.in);
System.out.println("How many players wish to play? Values of 2 through 8 accepted.");
numbHuman = scan.nextInt();
System.out.println(numbHuman + " players selected.");
while (numbHuman < 2 || numbHuman > 8)
{
System.out.println("Invalid entry, try again.");
numbHuman = scan.nextInt();
}
arr = new Player[numbHuman];
i=0;
testArray = new int[40];
propertyArray = new int[numbHuman][40];///// WORK ON DIS
userName = new String[numbHuman];
userID = new int[numbHuman];
startingMoney = 1500;
startingPosition = 0;
b=0;
c=0;
for(int i = 0; i < arr.length; i++)
{
userID[i] = b;
System.out.println("Player " + (i + 1) + ", Please enter your first name:");
userName[i] = scan.next();
for(c = 0; c < 40; c++)
{
propertyArray[i][c] = 0;
}
arr[i] = new Player(userName[i],startingMoney,userID[i],startingPosition,propertyArray[i][c]);
b++;
}
}
I'm trying to pass it into, how do i go about this? All the other variables work but the multidimensional array.
public Player(String userName, int changeInMoney, int userID, int startingPosition, int[][]propertyArray)
{
myID = userID;
myName = userName;
currentPosition += startingPosition;
currentBal -= payBank(changeInMoney);
}
You need to specify a set of square brackets for each dimension, e.g.:
public Player(String userName, int changeInMoney, int userID,
int startingPosition, int[][] propertyArray)
Just add an extra pair of brackets:
public Player(String userName, int changeInMoney, int userID, int startingPosition, int[][] propertyArray)

Categories