I can't seem to figure out what my parameters should be for my method "public static int[][] sellSeatByPrice". I need to prompt the user for a price (of a seat), then figure out if that price is taken (if it = 0) and if not, assign it the value 0.
Below is my code, help please!
import java.util.Scanner;
/**
* Write a description of class A10_TheaterSeating here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class A10_TheaterSeating
{
public static void main(String args[])
{
System.out.println("***Welcome to the Ticket Choice App!***");
System.out.println();
int[][] theaterSeats = //set values in seating chart array
{
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 20, 20, 20, 20, 20, 20, 10, 10},
{10, 10, 20, 20, 20, 20, 20, 20, 10, 10},
{10, 10, 20, 20, 20, 20, 20, 20, 10, 10},
{20, 20, 30, 30, 40, 40, 30, 30, 20, 20},
{20, 30, 30, 40, 50, 50, 40, 30, 30, 20},
{30, 40, 50, 50, 50, 50, 50, 50, 40, 30}
};
int[][] seats = theaterSeats;
printArray(seats); //print the seating chart
System.out.println();
//Defining variables
String str = "";
String input = "";
while (!input.equalsIgnoreCase("Q"))
{
System.out.print("Select 'S' to pick a seat, 'P' choose a price or 'Q' to quit: ");
Scanner in = new Scanner(System.in);
input = in.next();
if (input.equalsIgnoreCase("S"))
{
System.out.print("Enter row and seat number desired: ");
int row = in.nextInt();
int seat = in.nextInt();
System.out.println();
sellSeatByNumber(seats, row, seat);
printArray(seats);
System.out.println();
}
else if (input.equalsIgnoreCase("P"))
{
System.out.print("Enter price of seat desired: ");
int price = in.nextInt();
System.out.println();
sellSeatByPrice(seats, row, seat, price);
printArray(seats);
System.out.println();
}
}
System.out.println();
System.out.println("Thank you for choosing the ticket choice app.");
System.out.println();
}
public static void printArray(int[][] currSeat)
{
final int ROWS = 9;
final int COLUMNS = 10;
for(int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLUMNS; j++)
{
System.out.print(currSeat[i][j] + "\t");
}
System.out.println();
}
}
public static int[][] sellSeatByNumber(int[][] seats, int row, int seat)
{
if (row <= 0 || row > 9)
{
if (seat <= 0 || seat > 10)
{
System.out.print("Please enter a valid row and seat: ");
}
}
if (seats[row][seat] == 0)
{
System.out.print("That seat is taken. Please select another seat: ");
}
else
{
seats[seats.length - row][seat - 1] = 0;
}
return seats;
}
public static int[][] sellSeatByPrice(int[][] seats, int row, int seat, int price)
{
if (seats[row][seat] = price)
{
seats[seats.length - row][seat - 1] = 0;
}
return seats;
}
}
Your parameters seem fine - the internal logic and syntax is incorrect.
Since you're using static methods, and passing along the seat matrix, that is okay - but you have to check that the values being passed in are inside the bounds of your matrix - or you will get exceptions on them.
For instance, you don't check the bounds in sellSeatByPrice(). You really should do that, or a bogus row/seat combination could blow your program up.
It's also the case that the comparison given is incorrect:
if (seats[row][seat] = price)
should really be
if (seats[row][seat] == price)
as = is assignment, and == is primitive comparison.
Furthermore, in sellSeatByNumber(), you can still run into issues since an out of bounds row/seat combo will still blow up. You do check the bounds - kudos - but you don't return anything if they're outside of those bounds. In all reality, an IllegalArgumentException should be raised if they're stepping out of bounds, or you can return the matrix unmodified (which may be more straightforward).
Related
I'm trying to decode a huffmann binary code tree with no success. Am using the following code:
public static int decodeTree(String str){
int length = str.length();
int num = 0;
int number = 0;
Node root = tree1.get(0);
String b;
// 0 left
// 1 right
for (int x = 0; x <tree1.size(); x++) {
Node curr = root;
while ((curr.isLeaf() == false) && num < length) {
if (str.charAt(num) == '0') {
curr = curr.Left();
num++;
}
else if (str.charAt(num) == '1') {
curr = curr.Right();
num++;
}
}
number = curr.getValue();
}
return number;
}
It should output:
10, 46, 200, 155, 50, 50, 23, 12, 18, 59, 40, 10, 200, 10, 40, 50, 46, 12, 18, 200, 46
It is currently outputting:
155, 46, 200, 200, 50, 91, 23, 12, 46, 200, 40, 200, 155, 50, 200, 68, 38, 50, 18, 200, 200
It is to return decimal numbers. It decodes some numbers correctly but in the wrong sequence. Do you have any idea what might be wrong?
I'm also uploading my Tree implementation:
public static String[] huffman(int[] histo){
//initial list of nodes
tree1 = new ArrayList<>();
for (int i = 0; i < histo.length; i++)
if(histo[i] != 0) {
tree1.add(new Node(histo[i], i));
}
//get weights until only root node is left out
while(tree1.size() > 1){
combine(tree1);
}
//recursively generate code for each node in the tree
//if the recursion finds a leaf node,
//it sets the correct element in the array to the code of the node
Node root = tree1.get(0);
String[] codage = new String[histo.length];
root.genCodeWord(codage);
return codage;
}
Further information:
This is how I'm trying to decode back:
String[] oneDConvertedBack1 = new String[oneD.length];
System.out.print("\n\nCONVERTED BACK:\n");
for(int i =0; i<oneD.length; i++)
Gray graycode = new Gray();
oneDConvertedBack1[i] = graycode.convertToBinaryCode(oneDGray[i]);
}
for(int i=0; i<oneD.length;i++)
System.out.print(oneDConvertedBack1[i]+ ", ");
int[] oneDConvertedBack2 = new int[oneD.length];
System.out.print("\n\nCONVERTED BACK:\n");
for(int i =0; i<oneD.length; i++) {
oneDConvertedBack2[i] = decodeTree(oneDBinary[i]);
}
The following are the constituents of the Nodes of the tree and its CodeWord method
public Node(Node left, Node right, int value){
l = left;
r = right;
v = value;
i = -1;
}
public void genCodeWord(String[] codes){
if(l != null && r != null){
l.setCodeWord("0"+getCodeWord());
l.genCodeWord(codes);
r.setCodeWord("1"+getCodeWord());
r.genCodeWord(codes);
}else{
codes[i] = getCodeWord();
}
}
I'm trying to avoid hardcoding a whole bunch of numbers into my JavaFX ComboBox, but I don't know any other way to do it. Currently I'm doing this:
length_comboBox.getItems().addAll(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30);
However my aim is to make a call to a method that will generate a list of numbers to some specified upper limit (say 50). I've tried the following but it just adds one last i, instead of all 50:
length_comboBox.getItems().addAll(generator(50));
public static int generator(int limit) {
int i;
for (i = 1; i < limit; i++)
System.out.println(i);
return i;
}
ComboBox cBox = new ComboBox();
cBox.getItems().addAll(generator());
... example ...
private Integer[] generator() {
int size = (int) (Math.random() * 100);
Integer[] result = new Integer[size];
for (int i = 0; i < result.length; i++) {
result[i] = (int) (Math.random() * 50);
}
return result;
}
You can use the one-liner
IntStream.rangeClosed(1,50).boxed().forEach(length_comboBox.getItems()::add);
or, if you want to fire fewer change events to the combo box (in practice it will make very little difference):
length_comboBox.getItems().setAll(
IntStream.rangeClosed(1,50).boxed().collect(Collectors.toList())
);
This program is a work in progress. In it, I created an array of ten objects with five pieces of different data types for each object. I need to find the highest score for q1 which I hoped to accomplish by creating a loop that would compare the variable highScore with each q1 data(8, 3, 10, 8, 9, 7.5, 8.5, 6, 7.5, 7) as the loop went through its cycles, however, I am getting an error message that says "The operator < is undefined for the argument type(s) double, ClassGrade" at the line that is second from the bottom. I don't understand why I am getting this error message, but i suspect that the reason i am getting it is that I am not correctly specifying the specific element that i am trying to access from each object. Any help on the matter would be greatly appreciated.
public class ClassGrade {
public String studentID;
public double q1;
public double q2;
public int mid;
public int finalExam;
public ClassGrade(String studentID, double q1, double q2, int mid, int finalExam)
{
// TODO Auto-generated constructor stub with a few modifications
}
public static void main(String[] args) {
System.out.println("this program works");
double highScore;
highScore = 0;
ClassGrade [] student = new ClassGrade[10];
student[0] = new ClassGrade ("A1", 8, 8.5, 84, 82);
student[1] = new ClassGrade ("B2", 3, 7, 0, 99);
student[2] = new ClassGrade ("C3", 10, 9.5, 92, 84);
student[3] = new ClassGrade ("D4", 8, 8, 89, 86);
student[4] = new ClassGrade ("E5", 9, 10, 83, 91);
student[5] = new ClassGrade ("F6", 7.5, 8.5, 88, 69);
student[6] = new ClassGrade ("G7", 8.5, 0, 81, 52);
student[7] = new ClassGrade ("H8", 6, 8.5, 79, 68);
student[8] = new ClassGrade ("I9", 7.5, 6, 72, 91);
student[9] = new ClassGrade ("J10", 7, 6.5, 58, 77);
for(int i=0; i<10; i++){
if (highScore < student[i])
highScore = student[i];
}
}
}
First, you need to assign your instance variables in you constructor.
You are comparing a double (highscore) with a ClassGrade (student[i]).
You need to create public methods in ClassGrade to return your desired properties.
Accessing an object's properties from an array is just the same way as from a single object. You fetch the object from the array and use '.' to access its public properties or methods. E.g:
array[i].method()
You are comparing the highscore with the actual object in the array, you are comparing a student with grade, so just make some small change - declare a method in your ClassGrade class like getQ1() and then access the q1 from the loop
This should work:
ClassGrade classGrade = (ClassGrade) student[i];
classGrade.method();
Each member of the array is still a ClassGrade, so all you need to do is check its q1 member like you would any other ClassGrade's q1.
for(int i=0; i<10; i++){
if (highScore < student[i].q1)
highScore = student[i].q1;
}
Just think about it as if the array index is part of the name, and it'll make more sense.
// Consider this:
studentZero = new ClassGrade("A1", 8, 8.5, 84, 82);
if (highScore < studentZero)
highScore = studentZero;
// studentZero is not a double. Therefore...
if (highScore < studentZero.q1)
highScore = studentZero.q1;
Alternatively, you can add a getter for q1, and use it.
int score = student[i].getQ1()
if (highScore < score)
highScore = score;
See here for an example of how to access a member of an object in an array:
So i have this slice of code that reads text from a csv file where nums[] goes throughout the file and stores the number of a said student, and grades[][] goes through and stores each of their grades:
Scanner sc = new Scanner(new FileReader("location.csv"));
String [][] stuff = new String [10][];
for(int i = 0; i<10; i++){
String line = sc.nextLine();
stuff[i] = line.split.(",");
}
int [][] grades = new int [10][10];
int [] nums = new int [10];
for(int x = 0; x<10; x++){
nums[x] = Integer.parseInt(stuff[x][0]);
System.out.println(nums[x]);
for(int y = 0; y<11; y++){
grades[x][y] = Integer.parseInt(stuff[x][y]);
}
}
The problem is that numbs works wonderfully, but grades cant store any value that is past the first column of data. If I set grades [x][y] = stuff[any number] [0] it will run, but if I try to go past 0 in the rows, I error terminate.
Part of data file:
1, 66, 82, 85, 87, 65, 80, 97, 75, 68, 72
2, 70, 63, 75, 62, 84, 65, 67, 95, 81, 96
3, 100, 98, 73, 78, 69, 75, 97, 66, 61, 90
4, 75, 62, 79, 78, 87, 73, 74, 76, 63, 84
5, 81, 90, 80, 66, 75, 96, 73, 77, 66, 87
Stack Trace:
java.lang.NumberFormatException: For input string: " 66"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)
Fixed Code ( I apologize, I did not copy the code verbatim and included a few extra errors in it)
public static void main(String[] args)throws FileNotFoundException
{
Scanner sc = new Scanner(new FileReader("location.csv"));
String [][] values = new String [10][];
for(int i = 0; i<10; i++){
String line = sc.nextLine();
values[i] = line.split(",");
}
int [][] grades = new int [10][10];
int [] nums = new int [10];
for(int x = 0; x<10; x++){
nums[x] = Integer.parseInt(values[x][0]);
System.out.println(nums[x]);
for(int y = 0; y<10; y++){
grades[x][y] = Integer.parseInt(values[x][y+1].trim());
}
}
You aren't getting rid of the whitespace between tokens.
Make sure to clear it, preferably with String#trim()
Integer.parseInt(stuff[x][0].trim());
For the record, I'd also look to use better names than stuff.
Also, you're going to get an index out of bounds when you fix those other errors:
for( int y = 0; y < 11; y++ )
grades[x][y] = Integer.parseInt( stuff[x][y] );
All your array indexes go to 10, which in Java means 0 through 9. y here will go to 10, so boom out of bounds.
Considering the syntax errors pointed out in the comments, please in the future copy and paste the EXACT code you are using. It'll be no good if we are debugging different code than what you are actually using.
Let's say I got this map that prints out:
00000
00000
00000
How do I change the element in [0][0] into an X?
In other words, how to make it look like this using Screen input:
X0000
00000
00000
Considering Its an 2D Array of String Type...
arr[0][0] = "X";
Run this:
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
String[][] array = {{"0","0","0"},{"0","0","0"},{"0","0","0"}};
System.out.println("Before: ");
printArray(array);
array[0][0] = "x";
System.out.println("After: ");
printArray(array);
}
private static void printArray(String[][] array){
for(int i=0; i<array.length; i++){
for(int j=0; j<array[0].length; j++){
System.out.print(array[i][j]);
}
System.out.println("");
}
}
}
Or go here: http://ideone.com/2DQC1
In This example user k check array element value and change them
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
Scanner in = new Scanner(System.in);
int inputcol = 0;
int inputrow = 0;
int newnum = 0;
int uinput = 0;
int repeat = 1;
int[][] a = new int[][]{
{ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 },
{ 110, 120, 130, 140, 150, 160, 170, 180, 190, 200 },
{ 210, 220, 230, 240, 250, 260, 270, 280, 290, 300 },
{ 310, 320, 330, 340, 350, 360, 370, 380, 390, 400 },
{ 410, 420, 430, 0, 440, 450, 460, 470, 490, 500 }
};
while(repeat!=0)
{
System.out.println("Select Option:\n 1 for View Value:\n 2 for Replace Value: ");
uinput = in.nextInt();
//int b[][]={{1,3,4},{3,4,5}};
if(uinput==1)
{
System.out.println("Enter Row: ");
inputrow = in.nextInt();
System.out.println("Enter Cols:");
inputcol = in.nextInt();
System.out.println(a[inputrow][inputcol]);
}
else
if(uinput==2)
{
System.out.println("Enter Row: ");
inputrow = in.nextInt();
System.out.println("Enter Cols:");
inputcol = in.nextInt();
System.out.println("Enter New Number: ");
newnum = in.nextInt();
a[inputrow][inputcol] = newnum;
}
else
{
System.out.println("Check your input. ");
}
System.out.println("Want to repeat it? if yes press 1\n for exit press 0 ");
repeat = in.nextInt();
}
}
}