This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have made a program inside of which, there is a specific method that makes sure that all of the objects in an array that point to null point to a blank space. For some reason, whenever I run the code, it gives me a java.lang.NullPointerException.
I understand what a NullPointerException is, which is why I added the if statement, so that it wouldn't give the error, but it still does
Code:
public class TextGraphics {
public static void main(String[] args) {
displaySize size = new displaySize(5,5);
displaySize.output(5,3,size,"H");
displaySize.run(size);
}
}
class displaySize {
public static int indent;
public static int sizeX = 0;
public static int sizeY = 0;
public displaySize() {
}
public displaySize(int screenX, int screenY) {
sizeX = screenX;
sizeY = screenY;
indent = sizeX;
}
public static void output(int x, int y, displaySize size, String print) {
rarray(size)[x + y * size.sizeX] = print;
}
public static String[] rarray(displaySize size) {
String [] display;
return display = new String[sizeX * sizeY];
}
public static void run(displaySize size) {
int next = 0;
for (int i = 0; i < sizeY; i++) {
for (int b = 0; b < indent; b++) {
next++;
if(rarray(size)[next].equals(null) )
{
System.out.print( rarray(size)[next] + " ");
rarray(size)[next] = " ";
}
System.out.print( rarray(size)[next] + " ");
}
System.out.println("/n");
}
}
}
first problem used .equals(null) instead of == null
second problem your code throws a arrayoutofindex because your next++ was in the wrong for loop
finally your new line character was wrong its \n not /n
corrected code
public class TextGraphics {
public static void main(String[] args) {
displaySize size = new displaySize(5,5);
displaySize.output(5,3,size,"H");
displaySize.run(size);
}
}
class displaySize {
public static int indent;
public static int sizeX = 0;
public static int sizeY = 0;
public displaySize() {
}
public displaySize(int screenX, int screenY) {
sizeX = screenX;
sizeY = screenY;
indent = sizeX;
}
public static void output(int x, int y, displaySize size, String print) {
rarray(size)[x + y * size.sizeX] = print;
}
public static String[] rarray(displaySize size) {
String [] display;
return display = new String[sizeX * sizeY];
}
public static void run(displaySize size) {
int next = 0;
for (int i = 0; i < sizeY; i++) {
next++;
for (int b = 0; b < indent; b++) {
if(rarray(size)[next]==(null) )
{
rarray(size)[next] = " ";
System.out.print( rarray(size)[next] + " ");
}
System.out.print( rarray(size)[next] + " ");
}
System.out.println("\n");
}
}
}
Related
i am making a progress bar for my school assignment. But when i run my code my progress bar come outside my bracket, but the = most be inside the bracket.
public static String repeatString(int number, String str) {
for (int i = 0; i < number; i++) {
System.out.print(str);
}
return str;
}
public static String formatPercentage(int percentage) {
if (percentage == 100) {
return "done";
}
else{
return percentage + "%";
}
}
public static String formatBar(int percentage, int length) {
int amount = percentage * length/ 100;
int size = length - amount;
return "[" + repeatString(amount, "=") + repeatString(size, " ") + "] " + formatPercentage(percentage);
}
this is the result:
[= ] 5%
== [= ] 20%
======= [= ] 70%
==========[= ] done
============== [= ] 70%
Change your repeatString method to the following: Don't print anything here, just build up the string and return it.
public static String repeatString(int number, String str) {
String pad = "";
for (int i = 0; i < number; i++) {
pad += str;
}
return pad;
}
Try this:
public class ProgressBar {
private int length;
private int maxSteps;
private int step;
private char symbol;
public ProgressBar(int length, int maxSteps, char symbol) {
this.length = length;
this.maxSteps = maxSteps;
this.symbol = symbol;
}
public void increment() {
increment(1);
}
public void increment(int numSteps) {
step+=numSteps;
print();
}
private void print() {
float percentage = (float)step/(float)maxSteps;
int numSymbols = (int) Math.floor((double)length*percentage);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < Math.min(numSymbols, length); i++) {
builder.append(symbol);
}
for (int i = Math.min(length, numSymbols); i < length; i++) {
builder.append(' ');
}
builder.append(String.format("[%s ]", symbol));
if (numSymbols >= length) {
builder.append(" done");
} else {
builder.append(String.format("%d %%", (int)(percentage*100)));
}
System.out.println(builder.toString());
}
public static void main(String [] args) {
ProgressBar bar = new ProgressBar(10, 50, '=');
bar.increment(10);
bar.increment(15);
bar.increment(20);
bar.increment(5);
System.out.println("Now exceeding max..");
bar.increment(10);
bar.increment(5);
}
}
I'm new to java and making a hotel system. I have three major classes Room, Floor, and Hotel. Each floor has same type of rooms except for their room number. So I only make say 10 rooms and then give them all to my 5 floors and then assign the room number to each room in the respective floor.
The room number has its first digit as that of the floor no and the remaining digit(s) are from 1-10.
However, all my rooms in the hotel get assigned with the 5th floor number.
Heres snippets of my code.
class Floor
{
private int floorNo;
private Room[] Rooms;
public Floor()
{
floorNo = 0;
Rooms = null;
}
public Floor(int f, int t)
{
floorNo = f;
Rooms = new Room[t];
}
public void createRooms(Room[] R)
{
for (int i = 0; i < 10; i++)
{
Rooms[i] = new Room();
Rooms[i] = R[i];
}
}
public void setRoom(int i, int f, int r)
{
Rooms[i].setFloorNo(f);
Rooms[i].setRoomno(r);
}
}
public class Main
{
public static void main(String[] args)
{
Room[] Rooms = new Room[10];
for (int n = 0; n < 10; n++)
{
Rooms[n] = new Room();
}
}
Floor[] Floors = new Floor[5];
for (int n = 0; n < 5; n++)
{
Floors[n] = new Floor(n + 1, 10);
Floors[n].createRooms(Rooms);
for (int i = 0; i < 10; i++)
{
Floors[n].setRoom(i, n + 1, i + 1);
}
for (int n = 0; n < 5; n++)
{
Floors[n].print();
}
}
}
class Floor
{
private int floorNo;
private Room[] Rooms;
public Floor()
{
floorNo=0;
Rooms=null;
}
public Floor(int f, int t)
{
floorNo=f;
Rooms = new Room[t];
}
public void createRooms(Room[] R)
{
for(int i = 0 ; i < 10; i ++)
{
Rooms[i] = new Room();
Rooms[i] = R[i];
}
}
public void setRoom(int i, int f, int r)
{
Rooms[i].setFloorNo(f);
Rooms[i].setRoomno(r,f);
}
}
class Room
{
public void setFloorNo(int i)
{
System.out.println("floor no is "+i);
}
public void setRoomno(int j,int k)
{
System.out.println("room no is "+k+""+j);
}
}
public class main
{
public static void main(String[] args)
{
Room [] Rooms= new Room[10];
for(int n = 0; n < 10; n++)
{
Rooms[n] = new Room ();
}
Floor [] Floors= new Floor[5];
for(int n=0; n<5; n++)
{
Floors[n] = new Floor (n+1,10);
Floors[n].createRooms(Rooms);
}
for(int n=0; n < 5; n++)
{
for(int i=0;i<10;i++)
Floors[n].setRoom(i, n+1, i+1);
enter code here
}
}
}
You can try smth like this:
public class Hotel {
private List<Floor> floors = new ArrayList<>();
public boolean addFloor(Floor floor) {
return floors.add(floor);
}
public static void main(String[] args) {
int totalFloors = 5;
int totalRoomsOnAFloor = 10;
final Hotel hotel = new Hotel();
int roomNumber = 0;
for (int floorNumber = 0; floorNumber < totalFloors; floorNumber++) {
Floor floor = new Floor(floorNumber);
for (int floorRoomNumber = 0; floorRoomNumber < totalRoomsOnAFloor; floorRoomNumber++) {
Room room = new Room(floor, roomNumber++);
floor.addRoom(room);
System.out.println("Added " + room.toString());
}
}
}
public static class Floor {
private List<Room> rooms = new ArrayList<>();
private int number;
public Floor(int number) {
this.number = number;
}
public boolean addRoom(Room room) {
return rooms.add(room);
}
public int getNumber() {
return number;
}
#Override
public String toString() {
return "Floor{" +
"number=" + number +
'}';
}
}
public class Room {
private final Floor floor;
private final int number;
public Room(Floor floor, int number) {
this.floor = floor;
this.number = number;
}
public int getNumber() {
return number;
}
public Floor getFloor() {
return floor;
}
#Override
public String toString() {
return "Room{" +
"number=" + number +
", on the floor=" + floor +
'}';
}
}
}
Output:
Added Room{number=0, on the floor=Floor{number=0}}
Added Room{number=1, on the floor=Floor{number=0}}
Added Room{number=2, on the floor=Floor{number=0}}
...
Added Room{number=47, on the floor=Floor{number=4}}
Added Room{number=48, on the floor=Floor{number=4}}
Added Room{number=49, on the floor=Floor{number=4}}
Can someone see why the user can enter more than 27 apple, blueberry, or peanut pies? Even after declaring a final int for the max number of each type of pie.
The object here is to continually prompt the user for type of pie until the user wants to quit. Each time one of the valid inputs is entered it is stored in it's own array. After the user has indicated they are finished, calculations are done and a message is printed.
import javax.swing.JOptionPane;
public class CalcPieProfit {
public static void main(String[] args) {
final int MAX_PER_TYPE = 27;
int appleTotal = 0;
int blueberryTotal = 0;
int peanutTotal = 0;
String typeOfPie = getPieType();
while (!typeOfPie.equalsIgnoreCase("q")) {
if (typeOfPie.equalsIgnoreCase("apple")) {
String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
appleTotal++;
}
else if (typeOfPie.equalsIgnoreCase("blueberry")) {
String[] blueberryArray = fillBlueberry(typeOfPie, MAX_PER_TYPE);
blueberryTotal++;
}
else if (typeOfPie.equalsIgnoreCase("peanut")) {
String[] peanutArray = fillPeanut(typeOfPie, MAX_PER_TYPE);
peanutTotal++;
}
typeOfPie = getPieType();
}
if (typeOfPie.equalsIgnoreCase("q")) {
int totalPies = calcTotalPies(appleTotal, blueberryTotal, peanutTotal);
double profit = calcProfit(appleTotal, blueberryTotal, peanutTotal);
printReport(totalPies, appleTotal, blueberryTotal, peanutTotal, profit);
}
}
public static String getPieType() {
String pieType;
do {
try {
pieType = JOptionPane.showInputDialog("Enter a pie type:");
}
catch (NumberFormatException e) {
pieType = "";
}
if (!pieType.equalsIgnoreCase("apple") && !pieType.equalsIgnoreCase("blueberry") &&
!pieType.equalsIgnoreCase("peanut") && !pieType.equalsIgnoreCase("q")) {
JOptionPane.showMessageDialog(null, "Enter 'apple', 'blueberry', 'peanut', or 'q' only.");
}
} while (!pieType.equalsIgnoreCase("apple") && !pieType.equalsIgnoreCase("blueberry") &&
!pieType.equalsIgnoreCase("peanut") && !pieType.equalsIgnoreCase("q"));
return pieType;
}
public static String[] fillApple(String typeOfPie, int MAX_PER_TYPE) {
String[] appleArray = new String[MAX_PER_TYPE];
for (int i = 0; i < appleArray.length; i++) {
appleArray[i] = typeOfPie;
}
return appleArray;
}
public static String[] fillBlueberry(String typeOfPie, int MAX_PER_TYPE) {
String[] blueberryArray = new String[MAX_PER_TYPE];
for (int i = 0; i < blueberryArray.length; i++) {
blueberryArray[i] = typeOfPie;
}
return blueberryArray;
}
public static String[] fillPeanut(String typeOfPie, int MAX_PER_TYPE) {
String[] peanutArray = new String[MAX_PER_TYPE];
for (int i = 0; i < peanutArray.length; i++) {
peanutArray[i] = typeOfPie;
}
return peanutArray;
}
public static int calcTotalPies(int appleTotal, int blueberryTotal, int peanutTotal) {
int total = appleTotal + blueberryTotal + peanutTotal;
return total;
}
public static double calcProfit (int appleTotal, int blueberryTotal, int peanutTotal) {
final double APPLE_PROFIT = 5.94;
final double BLUEBERRY_PROFIT = 5.89;
final double PEANUT_PROFIT = 6.95;
double profit = (APPLE_PROFIT * appleTotal) + (BLUEBERRY_PROFIT * blueberryTotal) +
(PEANUT_PROFIT * peanutTotal);
return profit;
}
public static void printReport(int totalPies, int appleTotal, int blueberryTotal, int peanutTotal, double profit) {
if (totalPies > 0) {
JOptionPane.showMessageDialog(null,
"Pie Report\n\n" +
"Total pies: " + totalPies +
"\nTotal of apple pie: " + appleTotal +
"\nTotal of blueberry pie: " + blueberryTotal +
"\nTotal of peanut butter pie: " + peanutTotal +
"\nTotal profit: $" + String.format("%.2f", profit));
}
else {
JOptionPane.showMessageDialog(null, "Enjoy your day off.");
}
}
}
You are not really using the String[]s appleArray, blueberryArray and peanutArray - they are created in their respective method but not used anywhere else. For calculating the profits, you are (rightfully) only the total variables.
Instead of
if (typeOfPie.equalsIgnoreCase("apple")) {
String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
appleTotal++;
}
you should do something like
if (typeOfPie.equalsIgnoreCase("apple")) {
if (appleTotal >= MAX_PER_TYPE) {
JOptionPane.showMessageDialog(null, "Too many apples.");
} else {
appleTotal++;
}
}
(and the same for other pie types).
You're redeclaring the pie arrays each time you go to add them.
public static String[] fillApple(String typeOfPie, int MAX_PER_TYPE) {
String[] appleArray = new String[MAX_PER_TYPE];
for (int i = 0; i < appleArray.length; i++) {
appleArray[i] = typeOfPie;
}
return appleArray;
}
Each time you call this method, a new "appleArray" is generated. If you want it to persist between calls to this method, declare the appleArray as private static outside of the loop, and reference that instead.
I wrote two classes. The main class runs the program. It asks for user input. Based on user input, the second class will print out a square. Each square will print out ---- for every number and | for every number for the walls.
For example, say that the user entered two. In that case, it will print out a square.
----- -----
| |
| |
----- -----
The problem is that I cant get the square the grow based on the user input.
This is the main class
import java.util.Scanner;
public class Assignment4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
SquareBuilder square = new SquareBuilder(scan.nextInt());
System.out.print(square.toString());
square.changeSize(scan.nextInt());
System.out.print(square.toString());
square.changeSize(scan.nextInt());
System.out.print(square.toString());
square.changeSize(scan.nextInt());
System.out.print(square.toString());
square.changeSize(scan.nextInt());
System.out.print(square.toString());
}
}
public class SquareBuilder
{
final private int LENGTH_RATIO = 4;
final private String CEILING_FLOOR = "----";
private int size;
private int spaces;
private String square;
public SquareBuilder(int size)
{
this.size = size;
constructSquare();
}
private void spaces()
{
spaces = LENGTH_RATIO * size - 2;
}
private void ceilingAndFloor()
{
square += "\n";
for (int i = 0; i < size; ++i)
{
square += CEILING_FLOOR;
}
}
private void walls()
{
for (int i = 0; i < size; ++i )
{
square +="\n|";
for (int j = 0; j < spaces; ++j)
{
square +=" ";
}
square +="|";
}
}
private void constructSquare()
{
spaces ();
square = "";
ceilingAndFloor();
walls();
ceilingAndFloor();
}
public int area()
{
return size * size;
}
public void changeSize(int size)
{
this.size = size;
}
public String toString()
{
String retVal = square;
retVal += "\nSize: " + size + " Area: " + area();
return retVal;
}
}
You're not even changing the part of your square that renders.
I think you want to invoke your constructSquare() method from your changeSize() method, or at least call constructSquare() before you print it again
put the constructSquare() in the changeSize function.
required changes:
public SquareBuilder(int size)
{
changeSize( size);
// constructSquare();
}
public void changeSize(int size)
{
this.size = size;
constructSquare();
}
Building a rectangular with character input and specified column and rows. whitespace in the middle.
using standard input for string s, int r, int c
private static void printstuff(String s, int r, int c) {
colums(s, c);
rows(s, c, r);
colums(s, c);
}
// straight columns
private static void colums(String cs, int cc) {
for (int i = 1; i <= cc; i++) {
System.out.print(cs);
}
}
this creates desired whitespace or "" to concat string with ie making
x""""""""x
private static String whitespace(int wc) {
String ws = " ";
for (int i = 1; i <= wc - 3; i++) {
ws += " ";
}
return ws;
}
whitespace to built a rectangular.
// downwards building
private static void rows(String rs, int rc, int rr) {
String ws = whitespace(rc);
for (int i = 1; i <= rr - 1; i++) {
System.out.println(rs + ws + rs);
// put strings together
}
}
}
whitespace and character rows to built a rectangular. needless to say it failed.
sample output:
XXXX X
X X
xxxx
desired output:
xxxx
x x
xxxx
one quick solution below.. Cheers
public class Main {
public static void main(String[] args) {
String s = "X";
int totalColumns = 4;
int totalRow = 3;
colums(s, totalColumns);
rows(s, totalColumns, totalRow);
colums(s, totalColumns);
}
private static void colums(String cs, int cc) {
for (int i = 0; i < cc; i++) {
System.out.print(cs);
}
}
private static String whitespace(int tc) {
String ws = " ";
for (int i = 1; i < tc - 2; i++) {
ws += " ";
}
return ws;
}
private static void rows(String rs, int tc, int tr) {
System.out.println();
for (int i = 0; i < tr - 2 ; i++) {
System.out.println(rs + whitespace(tc) + rs);
}
}
}
Im not sure if this what you want but throw a System.out.println(""); after the for loop in colums