Parking Lot doesn`t save in matrix more than 1 line - java

So I have this project for my college and I'm stuck here, I tried everything I had in mind to make this code save more than 1 slot, as I must save up to 100 into a matrix database. Everything works great but the program always overwrites the first line, never passes on to the second...Here's the code:
Reserve part method:
for (n=1; n<100; n++) {
parkinglot[n][0] = Integer.toString(n);
parkinglot[n][1] = JOptionPane.showInputDialog(null, "License plate: ").toUpperCase();
String hourofreservation = JOptionPane.showInputDialog(null, "Reservation hour(hh:mm): ");
parkinglot[n][2] = hourofreservation;
parkinglot[n][3] = formatter.format(date);
parkingtime = Integer.parseInt(JOptionPane.showInputDialog(null, "Hours : "));
parkinglot[n][4] = Integer.toString(parkingtime);
int totalfee = (toMinutes(parkingtime)/30) * fee;
pay(totalfee);
//SaveReservation(nrinmat, parkinglot);
//save
JOptionPane.showMessageDialog(null, "This is yout reservation" + "\n\n" + " | " + parkinglot[n][0] + " | " + parkinglot[n][1] + " | " + parkinglot[n][2] + " | " + parkinglot[n][3] + " | " + parkinglot[n][4] + " HOURS |");
break;
}
Database method:
public static String[][] database(String [][]parkinglot)
{
System.out.println("This is database");
for (int i = 1; i < parkinglot.length; i++) {
for (int j = 0; j < parkinglot[i].length; j++) {
System.out.print(parkinglot[i][j] + "\t");
}
System.out.println();
}
return parkinglot;
}

Your program is starting at 1 every time because you have this line:
for (n=1; n<100; n++)
which initializes n to 1 before you enter the loop. (As noted in a comment, usually you would initialize n to zero, but that's not your problem here.)
Later, you break out of the loop, when n is still 1. When you call this code again (I assume it's in a function), it reinitializes n to 1 at the start of the loop. So n is never anything other than 1.
If you only want to fill in one record each time you run the program, then you don't need a loop at all. You need to store the value of n somewhere (like on disk, or in a database) and then read it back when you run the program again. Or, if you're saving the contents of parkinglot somewhere and reading it back in, you could scan it (using a for loop) to find the first empty entry, and initialize n to that, something like:
int n = 1; // or 0
for (; n < parkinglot.length && parkinglot[n][0] != null; n++);
if (n < parkinglot.length) {
populateParkingLotEntry(parkinglot, n);
} else {
// No more slots left...
}

Related

How do I stop this array from only printing/remembering the latest thing put into the array?

I don't know if the array itself is broken or if the code to print the array is broken
/*This is the main class that prints out everything */.
//Start the problems loop
for (int i = 0; i < session.getNumProb(); i++) {
//Set random values for factors
cards.setFactors();
//Create problems
cards.setProb(session);
//Determine correct/incorrect answer, update running score
cards.setResponse(session);
//Add the problem to the history array
session.setHistory(cards);
}
//Set score percentage
session.setScorePct();
//Print out summary
session.prtSummary();
//Print out history array and outro
session.prtHistoryAndOutro();
______________________________________________________________________________
/* This sets the history based on questions asked */
//setHistory
public void setHistory(Cards c) {
for (int i = 0; i < numProb; i++) {
history[i] = c.getA() + oper + c.getB() + " = " + c.getResponse() + ", " + c.getCorInc() + ", correct answer is " + c.getC();
System.out.println();
}
}
____________________________________________________________________________
/* This prints out the history array */
//prtHistoryAndOutro
public void prtHistoryAndOutro() {
System.out.println("Problems");
for (int i = 0; i < numProb; i++) {
System.out.println(history[i]);
}
System.out.println();
System.out.println();
System.out.println("Thank you for using the 3312 FlashCard System, " + name + ".");
System.out.println("Come back and play again real soon!");
}
I don't know where something is going wrong but it should be within these three pieces of code. Also the bottom two pieces are within the same class

Variable value not correctly increasing

In my code I have a variable, points, that increments based on the consanants and vowels in strings inputted. The method parseSentence is supposed to increase points per word but also ignore spaces.
I've tried running a debugger to see where the problem is but the debugger dies when it reaches the for loop in parseSentence. The method makes the point variable's value the word's point value instead of adding it to the variable. What could be causing this?
import java.util.*;
public class WordGolf1 {
public static int points = 1;
public static void main(String[] args) {
String Input;
System.out.println("Enter word: ");
Scanner sc = new Scanner(System.in);
Input = sc.nextLine();
System.out.println("Not enough points. " + (100 - points) + " needed.");
while (points < 100) {
System.out.println("Enter word: ");
Input = sc.nextLine();
parseSentence(Input);
System.out.println(points + ": points");
System.out.println("Not enough points. " + (100 - points) + " needed.");
}
boolean overshot = true;
Loop:
while (overshot = true) {
if (points == 100) {
overshot = false;
break Loop;
}
points = 100 - (points - 100);
System.out.println("Overshot by " + (points - 100) + " points.");
Input = sc.nextLine();
parseSentence(Input);
}
System.out.println("Congratulations you win!");
sc.close();
}
public static int parseSentence(String input) {
String[] pieces = input.split("\\s+");
for (int y = 0; y < pieces.length; y++) {
if (pieces.length > 1) {
if (y == 0) {
parseWord(input);
} else {
parseWord(input, y);
}
} else {
parseWord(input);
}
}
return points;
}
public static int parseWord(String input) {
String[] pieces = input.split("\\s+");
String charList = "aeiouyAEIOUY";
String consanantList
= "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ";
int pointsTemp = 1;
for (int x = 0; x < pieces[0].length(); x++) {
if (charList.indexOf(pieces[0].charAt(x)) != -1) {
pointsTemp *= 2;
} else if (consanantList.indexOf(pieces[0].charAt(x))
!= -1) {
pointsTemp++;
}
}
points = pointsTemp;
return points;
}
public static int parseWord(String input, int number) {
String[] pieces = input.split("\\s+");
String charList = "aeiouyAEIOUY";
String consanantList
= "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ";
int pointsTemp = 1;
for (int x = 0; x < pieces[number].length(); x++) {
if (charList.indexOf(pieces[number].charAt(x)) != -1) {
pointsTemp *= 2;
} else if (consanantList.indexOf(pieces[number].charAt(x)) != -1) {
pointsTemp++;
}
}
points += pointsTemp;
return points;
}
}
You are not using the value returned by the parseSentence method.
Edit: I tried to rewrite this to be as close your original code with making the changes I feel where necessary.
Now Obviously your teacher has requirements and we can't go against that, but some points of interest you should keep in mind.
Multi Splitting
In your example you split the text to get the amount of words. Then instead of looping the already split text. You are sending the original input and then splitting it again. The "Double" splitting is why you needed "three" methods. If you don't double split you can simply loop the length from the single split and just use a single ParseWord method.
Deducting Values
In your example you take away 100 if the player overshot. The problem with this is let's say the person received a score like 200. Then it would loop twice to lower the value submitting the "You overshot message" twice. However let's say by some magical way a score of 100,000,000 was received. Then as you can see we would loop 1 million times to deduct this value essentially creating an not infinite but might as well be infinite loop.
To resolve this problem we simply do the below.
Value = Value % 100.
This will give us the remainder of our Value between 0 and 99. I.e. 167 will equal 67 and 12384 will be equal 84.
Using String (IndexOf)
What this does is takes the Character you provided and loop iterates over the String you provided. The worst case is 12 loops. There's also a lot of other stuff String and IndexOf do that is extra work and I recommend staying away from it if you can.
The alternative solution which I did is take the character and use " | 32" on it. I'm not going to go deep into how bits work, but basically these characters are 8 bit values but we only use 7 of it's bits ranging from 32 to 127. The amount of bits is like the power of 2. so 2^7 = 128 and 2^8 = 256. When we perform the "|" we are turning a bit on so if it's already on it won't change the value.
So in our example let's say we have the value 64.
This is bit 6 turned on. Now we want to turn on bit 5 "32" so the value becomes 96, but if we already had the value 96 and we turn bit 32 on it will still be 32.
Full List of ASCII Characters..
https://www.ascii-code.com/
The Game Loop
In your example you created "TWO" game loops the first one is when you start off, but once you overshot your score you enter the second loop and forget the first one. The problem is now your "Enter Words" and "You Undershot" code are never used anymore. So all someone will see is the line to enter text with no information on what to do or what occurred unless they overshot then they get the overshot message.
To fix this I made a single Game Loop which processes until the code ends via the SCORE == 100. You can see in the code that we begin every game loop with "Enter Words: " and parse the sentence. Then we add up our score and compare. If we undershot we simply restart the loop and try again. If we overshot we reduce the score and try again. If we succeeded we prompt the user if they would like to play again or end the game. Playing again will set the SCORE to 0 and start over the loop. Ending the game will "BREAK" the loop and cause it to end.
The Full Working Code With Recommended Changes
Feel free to comment if you need additional assistance.
import java.util.*;
public class WordGolf1
{
private static int SCORE = 0;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while (true)
{
System.out.print("\n\nEnter word: ");
ParseSentence(sc.nextLine());
if (SCORE == 100)
{
System.out.print("\nYou Won! Would you like to play again: Y/N?");
if ((sc.nextLine().charAt(0) | 32) == 'y')
{
SCORE = 0;
System.out.print("\nResetting Game...");
} else {
break;
}
}
else
{
if (SCORE > 100)
{
int overshot = SCORE - 100;
SCORE = SCORE % 100;
System.out.print("\nYou Overshot By " + overshot + " Points. You now have " + SCORE + " points.");
} else {
System.out.print("\nYou currently have " + SCORE + " points you need " + (100 - SCORE) + " more.");
}
}
}
}
private static int ParseSentence(String input)
{
String[] split = input.split(" ");
for (Strng s : input)
SCORE += ParseWord(s);
}
private static int ParseWord(String word)
{
int value = 1;
for (int i = 0; i < word.length(); ++i)
{
int c = (int)word.charAt(i) | 32;
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
value *= 2;
} else {
value += 1;
}
}
return value;
}
}

Adding numbers 1 to n with a loop

So the code posted works and seems to give correct values. The only problem is that it prints every line in the loop instead of just the answer. How can I make it just print the answer instead of every line leading up to it?
import java.util.Scanner;
public class CountLoop{
public static void main (String[] args){
Scanner in = new Scanner (System.in);
int i = -1;
int limit = 0;
System.out.println("Please enter a number");
String end1 = in.nextLine();
int end = Integer.parseInt(end1);
while (i < end){
i++;
limit = (i + limit);
System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);
}
}
}
I'm fine with using other types of loops as well, as I'll need to show an example with all the different types of loops being used anyway, so any help is appreciated.
Move your system.out.println outside of your while loop
while (i < end){
i++;
limit = (i + limit);
}
System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);
Or the modern version in Java 8:
int sum = IntStream.range(startInclusive,endExclusive).sum();
System.out.println("The sum of the numbers in between " + startInclusive +
" and " + (endExclusive -1) + " is sum = " + sum);
Renamed variables ;-)
limit -> sum
0 -> startInclusive
end -> endExclusive - 1

Round Robin by using Linked List. The input cannot use more than one process

The image shows there are logic errors. I can only input one process. If I add more, there will be an error. The system says that I have an array out of boundary by where. I really need help for this problem. The reason why I converted linked list to array is because I don't have any expertise using linked list.
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LinkedList<Integer> cpuburst = new LinkedList<>();
LinkedList<Integer> priority = new LinkedList<>();
LinkedList<String> process = new LinkedList<>();
LinkedList<Integer> nextTime = new LinkedList<>();
int clockTime = 0;
double totalWaitTime = 0;
int quit, quantum = 2;
int processesComplete = 0;
do {
System.out.print("input process");
process.add(sc.next());
System.out.print("input cpu_burst");
cpuburst.add(sc.nextInt());
if (cpuburst.add(0)) {
processesComplete++;
}
System.out.print("input priority");
priority.add(sc.nextInt());
nextTime.add(0);
System.out.print("more?");
quit = sc.nextInt();
} while (quit != 0);
String[] Process = process.toArray(new String[process.size()]);
Integer[] cpu_burst = cpuburst.toArray(new Integer[cpuburst.size()]);
Integer[] Priority = priority.toArray(new Integer[priority.size()]);
Integer[] next = nextTime.toArray(new Integer[nextTime.size()]);
for (int i = 0; i < next.length; i++) {
System.out.println(Process[i] + "\t\t" + cpu_burst[i] + "\t\t" + Priority[i]);
}
int roundRobinIndex = 0;
System.out.println(" | Process | CPU Burst | Priority | Time | Clock Time | Wait Time |");
while (processesComplete < cpu_burst.length) {
if (cpu_burst[roundRobinIndex] > 0) {
int time = Math.min(quantum, cpu_burst[roundRobinIndex]);// compare value
cpu_burst[roundRobinIndex] -= time;
if (cpu_burst[roundRobinIndex] == 0)
processesComplete++;
int waitTime = clockTime - next[roundRobinIndex];
totalWaitTime += waitTime;
System.out.println(" | " + Process[roundRobinIndex] + " | " + cpu_burst[roundRobinIndex]
+ " | " + Priority[roundRobinIndex] + " | " + time + " | " + clockTime
+ " | " + waitTime + " |");
//clockTime += quantum;
clockTime += time;
next[roundRobinIndex] = clockTime;
}
roundRobinIndex = (roundRobinIndex + 1) % cpu_burst.length;
}
System.out.println("Average wait time" + totalWaitTime / cpu_burst.length);
}
}
Well, I think there are several problems with this code, but to answer the question: You get the IndexOutOfBounds error because every time you add a process, when you call
if (cpuburst.add(0)) {
processesComplete++;
}
you're adding an additional item (value 0) to the cpuburst-list, so that list is double the length of the others, alternating between the input values and zeros. Later on, you wrote
if (cpu_burst[roundRobinIndex] > 0) {
//...some code here...
}
roundRobinIndex = (roundRobinIndex + 1) % cpu_burst.length;
which means, the code in there will be executed the first time around when there's a cpuburst value the user put in, then the next time it won't because there's a zero and the third time (when you tested with two processes), it will again enter the if-clause but you get indexOutOfBounds errors at
int waitTime = clockTime - next[roundRobinIndex];
because next only has two entries.

Java Powers display table

I need to display an output like this:
Enter an integer: 3
Number Squared Cubed
====== ======= =====
1 1 1
2 4 8
3 9 27
But instead, when I run the code, I get this output:
Number Squared Cubed
====== ======= =====
3 9 27
In other words, I need to display the powers of an integer,including the powers of the numbers less than or equal to the integer. The numbers of the lesser integers need to be listed but are not displayed along with the integer being entered. How do I fix the code to make sure it outputs all of the integers that are less than or equal to the integer being entered? There are no errors (i.e. red exclamation mark circles) but I need to figure out the proper calculation.
Here is the code:
====================
import java.util.Scanner;
public class Powers
{
public static void main(String[] args)
{
System.out.println("Welcome to the Squares and Cubes Table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
while(choice.equalsIgnoreCase("y"))
{
// get the input from the user
System.out.println("Enter an Integer: ");
int integerNext = sc.nextInt();
System.out.println("Number" + " " + "Squared" + " " + "Cubed");
System.out.println("======" + " " + "======" + " " + "======");
for(int i = 1; i <= integerNext; i++)
{
i = integerNext;
int numberSquared = (int) Math.pow(i, 2);
int numberCubed = (int) Math.pow (i, 3);
String message = "\n" + i + " " + numberSquared + " " + numberCubed;
System.out.println(message);
System.out.println();
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
}
Help is always appreciated. Thanks.
Firstly, as Nikhil said: "Remove the line i = integerNext; It is resetting the value of I and therefore only last row is printed".
Secondly, move the first closing curly brace to before getting user input - you want to run the loop, and only ask about continuing when that's finished, if I understand correctly.
Remove the line i = integerNext; It is resetting the value of I and therefore only last row is printed
Your are almost there. Since you are looping from 1 to integerNext (which is 3 in your text), the looping variable i will get the values [1,2,3] each iteration, so you don't have to set i manually. When you do:
i = integerNext;
you are setting i to 3, so the loop will finish when it reaches the loop condition.
You may also want to put the "Continue?" check outside the loop:
for (int i = 1; i <= integerNext; i++) {
int numberSquared = (int) Math.pow(i, 2);
int numberCubed = (int) Math.pow(i, 3);
String message = "\n" + i + " " + numberSquared + " " + numberCubed;
System.out.print(message);
}
// see if the user wants to continue
System.out.print("\nContinue? (y/n): ");
choice = sc.next();
System.out.println();
import java.util.Scanner;
public class SquaresAndCubes {
public static void main(String[] args)
{
// Welcome the user
System.out.println("Welcome to the Squares and Cubes table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
do
{
// Get input from the user
System.out.print("Enter an integer: ");
int integer = sc.nextInt();
// Create a header
String header = "Number " + "Squared " + "Cubed " + "\n"
+ "====== " + "======= " + "===== ";
System.out.println(header);
int square = 0;
int cube = 0;
String row = "";
for (int i = 1; i <= integer; i++)
{
square = i * i;
cube = i * i * i;
row = i + " " + square + " " + cube;
System.out.println(row);
}
// See if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
while (!choice.equalsIgnoreCase("n"));
}
}
Basic way to do it with foor loop and some printlines
Scanner sc = new Scanner(System.in);
System.out.print("What number would you like to go up to? ");
int userInt = sc.nextInt();
System.out.println("");
System.out.println("Here is your table!");
System.out.println("");
System.out.println("number | squared | cubed");
System.out.println("------ | ------- | -----");
for (int i = 1; i <= userInt; i++){
System.out.println(i + " | " + (i * i) + " |" + " " +(i * i * i));
}

Categories

Resources