String array error or bad declaring - arrays

public class Hotel{
int lb;
String nazwa;
String [] tablicaPok;
public Hotel (int lbH , String nazwaH){
nazwa = nazwaH;
lb = lbH;
String [] tablicaPok = new String [lb];
}
public String dajNazwe (){
return nazwa;
}
public int ilePokoi (){
return lb;
}
public void TestTab (){ co_w_tablicy
for(int i=0 ; i < lb ; i++)
tablicaPok[i] = ("element nr: " + i );
}
public void whatsInTab (){
for(int i =0 ; i < lb ; i++)
System.out.println ("el. nr : " + i + " ma wartosc " + tablicaPok[i]);
}
}
I created class Hotel with the ability to save some String to created in object Hotel array. When I tested it, it throws a NullPointerException. I'm not sure if I am testing that array badly or if it is declared incorrectly.

In your constructor, you should use
tablicaPok = new String [lb];
instead of
String [] tablicaPok = new String [lb];
so that you are referencing the same variable.
You should also initialize it so that when you call whatsInTab(), it will have something to show for it. Something like:
for(int i=0 ;i < lb ; i++){
tablicaPok[i] = "";
}

Related

Storing each digit from double to an array

I am a newbie at this and I am not sure on how to go about to store the digits of a double to an array. I have this double value: 0120.1098
I want it to be stored as something like this:
value[1] = 0
value[2] = 1
value[3] = 2
value[4] = 0
value[5] = 1
`
and so on...
How do I do it?
I'm not sure if you really need to extract them, but as I don't know much more about your context, here you go.
You could turn it into a String, split it on . and iterate. This way you get two int arrays. One for the digits before the decimal and on for the digits after de decimal.
public static void main(String[] args) {
double d = 12323.213432;
String asString = String.valueOf(d);
String[] splitOnDecimal = asString.split("\\.");
int[] upperBound = getIntArray(splitOnDecimal[0]);
int[] lowerBound = getIntArray(splitOnDecimal[1]);
System.out.println(Arrays.toString(upperBound));
System.out.println(Arrays.toString(lowerBound));
}
private static int[] getIntArray(String numberString) {
int[] tmpArray = new int[numberString.length()];
for (int i = 0; i < numberString.length(); i++) {
tmpArray[i] = Integer.parseInt(numberString.substring(i, i + 1));
}
return tmpArray;
}
Try this, it will even show your zeroes:
String dbl = "0012300.00109800";
int dblArraylength = dbl.length();
char[] c = dbl.toCharArray();
int dotId= dbl.indexOf(".");
int a[] = new int[dblArraylength-1];
for(int i=0; i<dotId; i++){
a[i]=Integer.parseInt(Character.toString ((char)c[i]));
}
for(int i=dotId; i<a.length; i++){
a[i]=Integer.parseInt(Character.toString ((char)c[i+1]));
}
for(int i=0; i<a.length; i++){
System.out.println("a[" +i+ "] = " + a[i]);
}

If the input is a1bc2def3 output should be abcbcdefdef

If the given input is a1bc2def3 then output should be abcbcdefdefdef
Whenever the number comes then we should repeat previous substring that many number of times.
Please provide the algorithm or code to accomplish this.
Here's another approach that doesn't rely on regex.
public String splitRepeat(String str)
{
StringBuilder out = new StringBuilder();
boolean number = false;
for(int i=0,j=0,k=0; i<=str.length(); i++)
{
if(i==str.length() || Character.isDigit(str.charAt(i)) != number)
{
if(number)
{
for(int r = Integer.parseInt(str.substring(j, i)); r>0; r--)
{
out.append(str.substring(k, j));
}
}
else
{
k=j;
}
j=i;
number = !number;
}
}
return out.toString();
}
My suggestion would be:
Try using regex so you can get an array of numbers and characters,
then convert the number Parsable elements of the array into an integer,
after that loop with the index of the arrays to append n-times the characters of the array
then print the final result
Example:
public static void main(String[] args) {
String stringToProcess = "a1bc2def3";
String[] regexSplitted = stringToProcess.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
StringBuilder sb = new StringBuilder();
String appender = "";
for (int i = 0; i < regexSplitted.length; i++) {
try {
int kilo = Integer.parseInt(regexSplitted[i]);
for (int j = 0; j < kilo; j++) {
sb.append(appender).append(regexSplitted[i - 1]);
appender = "-";
}
} catch (NumberFormatException e) {
}
}
System.out.println(sb.toString());
}
this will print
a-bc-bc-def-def-def
that is pretty much what you are looking for.

Splitting an integer into an array

I am trying to take an array of information (array of 8) and split it so that I can send it to an ArrayList.
I can run a a split if I create and make them all strings, but I am trying to reduce the coding (as there has to be a better way).
The first 4 of the array are strings, and the next 4 are int.
ArrayList<student> studentID = new ArrayList<student>();
String[] studentInfo = {"","","",""};
int [] studentInfo2 = {0,0,0,0};
for (int x = 0; x < students.length; x++)
{
if (x < 4)
{
studentInfo = students[x].split(",");
}
else
{
**studentInfo2 = students[x]();**
}
for (int counter = 0; counter < 8; counter++)
{
if (counter < 4) //First 4 in the array are strings
{
studentID.add(new student(studentInfo[counter]));
}
else //Everything after the first 4 are Integers
{
studentID.add(new student(Integer.valueOf(studentInfo[counter])));
}
}
}
I cannot figure out how to split the last 4 into an array, as I did the first 4.
EDIT:
static String[] students = "1,John,Smith,John2233#gmail.com,20,88,79,59,
2, Becky,Jones,JonesBecky123#hotmail.com,44,90,89,44,99"
This information is being piped into a class as seen below:
public class student
{
private String studentNumber;
private String firstName;
private String lastName;
private String emailAddress;
private int age;
private int []score = {0,0,0};
private int score0;
private int score1;
private int score2;
/**
* Constructor for objects of class studentObject
*/
public student(String theStudentNumber, String theFirstName, String theLastName, String theEmailAddress, int theAge, int theScore0, int theScore1, int theScore2)
{
// initializing the instance variables
studentNumber = theStudentNumber;
firstName = theFirstName;
lastName = theLastName;
emailAddress = theEmailAddress;
age = theAge;
score[0] = theScore0;
score[1] = theScore1;
score[2] = theScore2;
}
Then it will call this method
public void print(student printStudentInfo)
{
System.out.print(printStudentInfo.getStudentNumber()+"\t");
System.out.print("First Name: " + printStudentInfo.getStudentNumber()+"\t");
System.out.print("Last Name: " + printStudentInfo.getStudentNumber()+"\t");
System.out.print("Age: " + printStudentInfo.getStudentNumber()+"\t");
System.out.print("Scores : " + printStudentInfo.getStudentNumber()+"\t");
System.out.println();
}
Thanks for the help ahead of time.

Creating a static method

Here's my code.
public static String hBlanks(String a, String b){
StringBuilder blanks = new StringBuilder();
int j;
for(int x = 0; x < a.length(); x++){
blanks.append('-');
}
System.out.println(blanks);
String strBlanks = blanks.toString();
for(int i = 0; i < a.length(); i++){
j = 0;
while(j < b.length()){
boolean check = a.contains(b.charAt(j));
//I keep getting an error on the boolean check = a.contains(b.charAt(j)); line. It says: "contains(java.lang.CharSequence) in java.lang.String cannot be applied to (char)"
if(check == true){
strBlanks = blanks.replace('-', "" + a.charAt(i));
//And I get another error at the str = strBlanks.replace('-', "" + a.charAt(i)); line. That one says "cannot find symbol
symbol : method replace(char,java.lang.String)
location: class java.lang.String"
}else{
j++;
}
}
return strBlanks;
}
}
To get rid of your compilation issues,
Change strBlanks.replace('-', "" + a.charAt(i)); to
strBlanks.replace('-', a.charAt(1));
Also change a.contains(b.charAt(j)); to
a.contains("" + b.charAt(1));
How about just one line, instead of all that code:
public static String wordBlanks(String a, CharSequence b){
return a.replaceAll("[^" + b + "]", "-");
}
This works by creating a regex that matches every character not in b and using that to replace ever occurrence in a with a dash.

NPC movement in the array

I am doing a an array game, below is my Board class, which paints the array and spawns 5 hunters at 11,11, my 'route1' method should be the one to move hunters around whenever the player moves, however my hunter.x and hunter.y stay 11 after each re-paint, how do I fix this?
public class Board {
public String emptyfield = "-";
public String [][]a2 = new String[12][12];
public Hunter hunters[] = new Hunter[5];
public void paint(){
int numHunters =5 ;
for (int i =0; i < numHunters; i ++){
hunters[i] = new Hunter(11,11,"H");
}
Player player = new Player();
for (int r = 0 ; r < a2.length; r++){
for (int c= 0; c <a2[r].length; c++){
a2 [r][c] = emptyfield;
a2[Player.x][Player.y] = Player.name;
for (int i = 0; i < numHunters; i++){
Hunter h = hunters[i];
a2[h.x][h.y]=h.name;
}
System.out.print(" "+a2[r][c]);
}
System.out.println("");
}
System.out.println(" Strength: "+Player.hp);System.out.println(" Score "+Player.score);
}
public void route1(){
Board board = new Board();
Hunter Hunter = new Hunter(11,11,"H");
Scanner in = new Scanner(System.in);
Random number = new Random(2);
int random = number.nextInt(2);
if(random ==1)
Hunter.x = Hunter.x -1;
else
Hunter.y = Hunter.y -1;
}
If I read this correctly, you are recreating all your hunters at position 11,11 each time you call paint.
public void paint(){
int numHunters =5 ;
for (int i =0; i < numHunters; i ++)
{
hunters[i] = new Hunter(11,11,"H");
}
This code is replacing your array of hunters each time paint is called, erasing any changes made later on in code. You need to move (new Hunter(11,11,"H") to somewhere that is only called once.

Resources