I've been trying to figure out how add a string to an array.
I have a class which represents a list and I want to add "cup" to the list by calling addTo.
I've tried this, but it fills the entire array and then when the method is called again it overwrites the entire array:
private String[] option;
private int position;
public Menu()
{
option = new String[0];
position = 0;
}
public void addTo(java.lang.String option)
{
option = new String[20];
++position;
option[position] = option;
}
Hope this is better.
This line
option = new String[20];
is clearing your list.
You should initilize your list only in a constructor, for example.
Your Menu class can be something like:
public class Menu{
private final int LIMIT = 20;
private String[] option;
private int position;
public Menu()
{
option = new String[LIMIT];
position = 0;
}
public void addTo(String item)
{
if(position == LIMIT)
{
// We do not want a IndexOutOfBoundsException here
return;
}
option[position++] = item;
}
public void printList(){
for(int i = 0; i< LIMIT; i++)
{
System.out.println( i + ": " + option[i] );
}
}
public static void main(String[] args)
{
Menu m = new Menu();
m.addTo("book");
m.addTo("cup");
m.addTo("test");
m.printList();
}
}
Tested and working!
Best regards,
Miguel
Related
I followed some discussion on the website and implemented some suggestions but I was not able to complete the task.
I have this assignment to build Tic Tac Toe game in Java.
There's a lot of tutorials on the web I know, but I wanted to build it using threads for each player so that only one player at a time could enter X/O to the board and I was not able to figure out the implementation for the wait/ notify.
To be honest, I find it a bit confusing! I guess the logic is 90% done, and I am wondering how to finish it.
Basically, I have these classes:
abstract public class Player extends Thread
public class HumanPlayer extends Player
public class MachinePlayer extends Player
public class Board
public class Game
public class Main
I'll paste first the players classes. Notice the run method I tried to Synchronize on top of the gameOver variable:
Player.java
abstract public class Player extends Thread {
abstract int getMyTurn() ;
abstract String getPlayerName() ;
abstract void setPlayerName(String n ) ;
abstract void setSign(int n ) ;
abstract int getSign() ;
}
MachinePlayer.java
import java.util.Random;
public class MachinePlayer extends Player {
private String name ;
private int sign ;
Board board ;
public MachinePlayer(Board board) {
this.board = board;
}
#Override
public void run() {
System.out.println("Player "+name+" turn:" );
while (!board.isGameOver())
{
board.setCurrentPlayerTurn(this.getSign()); // i think it keeps track of which player is holding the lock ?
Move move = generateRandomMove();
board.makeMove(this, move.getX(), move.getY() );
}
}
#Override
int getMyTurn() {
return 0;
}
#Override
public String getPlayerName() {
return name;
}
#Override
public void setPlayerName(String name) {
this.name = name;
}
#Override
void setSign(int sign) {
this.sign = sign ;
}
#Override
int getSign() {
return sign;
}
private Move generateRandomMove(){
while (true)
{
int x = getRandomNumber(0,board.getBoardSize()) ;
int y = getRandomNumber(0,board.getBoardSize()) ;
if (board.isPositionAvalabile(x, y ))
{
return new Move(x,y);
}
}
// todo implement the best move !
}
public int getRandomNumber(int min, int max) {
return (int) ((Math.random() * (max - min)) + min);
}
}
HumanPlayer.java
public class HumanPlayer extends Player {
private String name ;
private int sign ;
private Board board ;
public HumanPlayer(Board board) {
this.board = board;
}
#Override
public void run() {
while (!board.isGameOver())
{
board.setCurrentPlayerTurn(this.getSign()); // I think it keeps track of which player is holding the lock ?
Move move = requestMoveFormHuman(); // request move for human player // will be changed in the GUI?
board.makeMove(this, move.getX() , move.getY()); // check for move logic here >
}
}
#Override
int getSign() {
return sign;
}
#Override
int getMyTurn() {
return 0;
}
#Override
public String getPlayerName() {
return name;
}
#Override
public void setPlayerName(String name) {
this.name = name;
}
#Override
void setSign(int n) {
this.sign = n ;
}
// logic
private Move requestMoveFormHuman(){
int i=0 ;
while (true)
{
System.out.println(i);
Move move = requestMove() ;
int x = move.getX();
int y = move.getY();
if (board.isPositionAvalabile(x,y))
{
return new Move(x,y);
}
}
}
private Move requestMove() {
System.out.println("Player "+name+" turn:" );
System.out.println("Enter Row number: ");
int x = ScanInt();
System.out.println("Enter Coulmn number ");
int y = ScanInt();
return new Move(x ,y ) ;
}
private int ScanInt(){
Scanner scan = new Scanner(System.in);
// This method reads the number provided using keyboard
int num = scan.nextInt();
// Closing Scanner after the use
return num;
}
}
Main.java
public class Main {
public static void main(String[] args) {
Game game = new Game() ;
game.start();
}
}
Board.java
import java.util.HashMap;
import java.util.Scanner;
public class Board {
private int currentPlayerTurn = 0 ;
public int getBoardSize() {
return boardSize;
}
private int boardSize ;
private int[][] board_values ;
private boolean gameOver ;
private HashMap<String , String> result_history;
public Board(int boardSize) {
this.boardSize = boardSize;
board_values = new int[boardSize][boardSize];
for (int i = 0; i < boardSize; i++) {
for (int j = 0 ; j < boardSize; j++)
board_values[i][j] = 0 ;
}
System.out.println("");
}
private String getSign(int n) {
if (n==1)
return "X" ;
if (n==2)
return "0" ;
return " " ; // empty cell
}
public void printBoard(){
// todo change to ui components
for (int i = 0 ; i < boardSize ; i++)
{
for (int j = 0 ; j < boardSize ; j++)
{
System.out.print("|");
System.out.print(" " + getSign(board_values[i][j])+ " ");
System.out.print("|");
}
System.out.println("");
System.out.println("----------------------------------" );
}
}
/** is this the Synchronized one ? */
public boolean makeMove(Player player , int x , int y ) {
/*Update Board Value
insert 1 in the 2d board at x,y for player 1
insert 2 in the 2d board at x,y for player 2
*/
int sign = player.getSign();
updateBoard(x,y , sign ) ;
/*print Board*/
printBoard();
/* check for winner */
doWeHaveAwinner(x,y , sign);
return true ;
}
/*check the whole row (x) for if all signs are equals
, checks the whole column (x) for if all signs are equals
check diagonal if x=y */
private boolean doWeHaveAwinner(int x, int y, int sign) {
// TODO: 16/01/2022
return false ;
}
private void updateBoard(int x, int y , int sign ) {
board_values[x][y] = sign ;
}
public boolean isPositionAvalabile(int x , int y ){
return !(x>this.boardSize || x < 0 || y>this.boardSize || y < 0) ;
}
private void checkMove() {
// todo > ?
}
private void resetBoard(){
// todo set al values to 0
}
private void updateResultHistory(){
// TODO: 16/01/2022 update <Winner Name , Ps+1 >
}
private int ScanInt(){
Scanner scan = new Scanner(System.in);
System.out.print("Enter any number: ");
// This method reads the number provided using keyboard
int num = scan.nextInt();
// Closing Scanner after the use
return num;
}
/*Get Set*/
public synchronized boolean isGameOver() {
return gameOver;
}
public void setGameOver(boolean gameOver) {
this.gameOver = gameOver;
}
public int getCurrentPlayerTurn() {
return currentPlayerTurn;
}
public void setCurrentPlayerTurn(int currentPlayerTurn) {
this.currentPlayerTurn = currentPlayerTurn;
}
}
And here is Game.java, it basically inits 2 players.
Notice that in each player init I passed the board instance as a parameter.
It might a look little bit messy but I think passing the board instance for the players is the important thing here. Also I called the player1().start and player2.start()
Game.java
public class Game {
private Player player1 ;
private Player player2 ;
private Board board ;
private void initBoard(){
/* request board size */
int board_size = requestBoardSize();
board = new Board(board_size); // Synchronized class fields ?
}
private void initGameMode(){
/*
init the players objects as follows
1 - for human-machine game
2 - for machine-human game, and
3 - for human-human game
*/
System.out.println(Utils.str_gameType);
Scanner scanner = new Scanner( System.in);
int game_mode = scanner.nextInt( );
switch (game_mode) {
case 1:
/* init game type1 human-machine Game*/
player1 = new HumanPlayer(board);
player2 = new MachinePlayer(board);
break;
case 2:
player1 = new MachinePlayer(board);
player2 = new HumanPlayer(board);
break;
case 3:
player1 = new HumanPlayer(board);
player2 = new HumanPlayer(board);
break;
default:
throw new IllegalStateException("Unexpected value: " + game_mode);
}
player1.setSign(1);
player2.setSign(2);
System.out.println("");
}
private void initPlayersName(){
/*request name player 1 */
System.out.println(Utils.str_player1Name); /*Scan first name*/
Scanner scan1 = new Scanner(System.in);
String name1 = scan1.next();
player1.setPlayerName(name1);
/*request name player 2 */
System.out.println(Utils.str_player2Name); /*Scan first name*/
Scanner scan2 = new Scanner(System.in);
String name2 = scan2.next();
player2.setPlayerName(name2);
}
public Game() {
System.out.println(Utils.str_start_game);
initBoard();
initGameMode();
initPlayersName();
}
public void start() {
// todo change who starts first
player1.start();
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(300);
player2.start();
}catch (Exception e)
{
}
}
}).start();
}
private int requestBoardSize() {
System.out.println(Utils.str_request_board_size);
Scanner scanner = new Scanner(System.in) ;
int i = scanner.nextInt() ;
return i ;
}
}///End of Class
The program is meant to modify the List items (defined at top), and there appears to be trouble printing the modified version to console.
Could I get some tips as to where (and perhaps what, for efficiency) to modify?
import java.util.*;
public class Quiz4 {
public static class ItemHolder{
private List<Integer> items = new ArrayList<>();
public List<Integer> getItems(){
return items;
}
public void addItems(Integer item){
items.add(item);
}
public int size(){
return items.size();
}
public String toString(){
return items.toString();
}
public void remove(Object obj) {
items.remove(obj);
}
public boolean equals(int a, int b){
boolean ret = false;
if (a == b){
ret = true;
}
return ret;
}
public int get(int index){
return items.get(index);
}
}
public static ItemHolder modify(ItemHolder items){
for (int i = 0; i < items.size(); ){
if(items.get(i) == (items.get(i+1))){
items.remove(items.get(i));
}
}
return items;
}
public static void main(String[] args){
ItemHolder items = new ItemHolder();
Scanner up = new Scanner(System.in);
items.getItems();
for (int i = 0; i < 6; i++){
System.out.println("Please enter number. -1 to quit");
String input = up.nextLine();
int check = Integer.parseInt(input);
if (check >= 0){
items.addItems(check);
}
else{
continue;
}
}
modify(items);
System.out.println(items);
up.close();
}
}
Thank you!
Modify your Modify method it will work
for (int i = 0; i < items.size()-1;i++ ){
if(items.get(i) == (items.get(i+1))){
items.remove(items.get(i));
}
I have 3 classes for this program. I want to print out the total price of the items after shopping, but there is a problem with the output. Though each time shopping are different in the number of items, the output are all the same. Could you please help me to fix it?
Here are my code:
This is the first class:
public class LineItem {
private String name;
private int quantity;
private double pricePerUnit;
/**
*
*/
public LineItem(String name, int quantity, double pricePerUnit) {
this.name = name;
this.quantity = quantity;
this.pricePerUnit = pricePerUnit;
}
public double getCost() {
return quantity*pricePerUnit;
}
public void setQuantity(int newQuantity) {
quantity=newQuantity;
}
}
This is the second class:
import java.util.ArrayList;
public class ShoppingCart {
/**
*
*/
private LineItem[] item;
private int check;
public ShoppingCart() {
item = new LineItem[10];
check = 10;
}
public void add(LineItem newItem) {
int i = 0;
while (item[i] == null && check != 0){
item[i] = newItem;
i++;
check -= check;
}
}
public double getTotalCost() {
double totalCost = 0.0;
for(int i=0; i< item.length;i++){
if(item[i]!=null)
totalCost += item[i].getCost();
}
return totalCost;
}
}
This is the third class:
public class ShoppingCartTester{
public static void main(String[] args){
ShoppingCart singleItemCart = new ShoppingCart();
LineItem item1 = new LineItem("Dove shampoo",1,4.52);
singleItemCart.add(item1);
System.out.println(singleItemCart.getTotalCost());
//
ShoppingCart typicalCart = new ShoppingCart();
item1 = new LineItem("Dove shampoo",1,4.52);
typicalCart.add(item1);
LineItem item2 = new LineItem("apples",5,10.80);
typicalCart.add(item2);
LineItem item3 = new LineItem("avocados",5,20);
typicalCart.add(item3);
LineItem item4 = new LineItem("chocolate",1,4.25);
typicalCart.add(item4);
LineItem item5 = new LineItem("green onions",3,3.49);
typicalCart.add(item5);
System.out.printf("%.2f", typicalCart.getTotalCost());
System.out.println();
}
}
I think the problem is in the add method, but i have no idea how to fix it.
Thank you in advance
I suggest to maintain a global variable with current item in cart (noOfItems),
So that while adding you can directly add new item
So instead of
public void add(LineItem newItem) {
int i = 0;
while (item[i] == null && check != 0){
item[i] = newItem;
i++;
check -= check;
}
}
use
public void add(LineItem newItem){
item[++noOfItems] = newItem;
}
or second way
its better to create ArrayList instead of array of object
Problem is in your Add method:
public void add(LineItem newItem) {
int i = 0; <--- Problem begins
while (item[i] == null && check != 0){
item[i] = newItem;
i++;
check -= check;
}
}
Everytime you are calling add i is getting reset to 0.
Fix1:: To have a list instead of array. Array comes with a fix size which you might want to avoid.
I have the following code. I'm trying to do a breadth first search of a tree that I created call HabitItem.
Here is queue traveral
import java.io.File;
import java.util.*;
import java.util.concurrent.PriorityBlockingQueue;
public static void traverseQueue() {
queueHabitItems.add(head);
while(!queueHabitItems.isEmpty()){
HabitItem node = queueHabitItems.peek();
for(int i = 0; i < node.children.size(); i++)
{
HabitItem it = node.children.get(i);
System.out.print("node: ");
System.out.print(node.name);
System.out.print(", child: ");
System.out.println(it.name);
queueHabitItems.offer(it);
}
queueHabitItems.poll();
System.out.println("Something Good Is Coming");
}
}
I'm trying to implement a Queue. And I'm using the Poll() function to remove elements. Suppose I have the following Data in the Queue.
A B C D E
And I want to use poll() to remove the front element. Well for some reason, E goes to the front of the list, such that it becomes
E B C D
Am I doing something wrong or is there something that I don't fundamentally understand about Queues? Shouldn't B be the front item?
public class myMain {
static PriorityQueue<HabitItem> queueHabitItems = new PriorityQueue<HabitItem>();
static HabitItem head = new HabitItem("A");
static HabitItem B = new HabitItem("B");
static HabitItem C = new HabitItem("C");
static HabitItem D = new HabitItem("D");
static HabitItem E = new HabitItem("E");
static HabitItem F = new HabitItem("F");
static HabitItem G = new HabitItem("G");
static HabitItem H = new HabitItem("H");
static HabitItem I = new HabitItem("I");
static HabitItem J = new HabitItem("J");
static HabitItem K = new HabitItem("K");
static HabitItem L = new HabitItem("L");
static HabitItem M = new HabitItem("M");
static HabitItem N = new HabitItem("N");
static HabitItem O = new HabitItem("O");
public static void hardCodeHabits() {
System.out.print(D.id);
head.children.add(B);
head.children.add(C);
head.children.add(D);
head.children.add(E);
B.children.add(F);
B.children.add(G);
B.children.add(H);
C.children.add(I);
B.children.add(J);
E.children.add(K);
I.children.add(L);
L.children.add(N);
L.children.add(M);
N.children.add(O);
System.out.print(D.id);
}
public static void traverseQueue() {
queueHabitItems.add(head);
while(!queueHabitItems.isEmpty()){
HabitItem node = queueHabitItems.peek();
for(int i = 0; i < node.children.size(); i++)
{
HabitItem it = node.children.get(i);
System.out.print("node: ");
System.out.print(node.name);
System.out.print(", child: ");
System.out.println(it.name);
queueHabitItems.offer(it);
}
queueHabitItems.remove();
System.out.println("Something Good Is Coming");
}
}
public static void main(String[] args) {
System.out.println("Hello world");
hardCodeHabits();
traverseQueue();
try{
Scanner x = new Scanner(new File("justText.txt"));
Formatter y = new Formatter(new File("output.txt"));
y.format("%s", "hey");
y.close();
while (x.hasNext()) {
System.out.println(x.next());
}
}
catch(Exception e) {
System.out.println("Couldn't open the file!");
}
}
}
This is my HabitItems class
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class HabitItem implements Comparable<HabitItem> {
static int Counter = 0;
String name;
boolean completed[] = new boolean[7];
List<HabitItem> children = new ArrayList<HabitItem>();
int id;
public String getName(){
return name;
}
public boolean[] getCompleted(){
return completed;
}
public void setCompleted(int index, boolean checked){
completed[index] = checked;
}
public boolean isChecked(int index){
return completed[index];
}
public HabitItem(String name) {
super();
Counter++;
this.id = Counter;
this.name = name;
for(int i = 0; i < 7; i++){
completed[i] = false;
}
}
public HabitItem(int id) {
super();
Counter++;
this.id = id;
}
public int compareTo(HabitItem o) {
if(o.id == this.id)
{
return 1;
}
else
{
return 0;
}
}
}
Again, don't use peek, use remove:
while (!queueHabitItems.isEmpty()) {
//!! HabitItem node = queueHabitItems.peek();
HabitItem node = queueHabitItems.remove();
for (int i = 0; i < node.children.size(); i++) {
HabitItem it = node.children.get(i);
System.out.print("node: ");
System.out.print(node.name);
System.out.print(", child: ");
System.out.println(it.name);
queueHabitItems.offer(it);
}
// !! queueHabitItems.remove();
System.out.println("Something Good Is Coming");
}
The peek call just peeks into the collection but does not respect the priority. The poll and remove do respect this.
This is very old and probably doesn't matter anymore. But I will just say that it turned out that I was confused because I thought a priorityQueue was the exact same thing as a queue.
How to sort the jComboBox elements list into sorted list.
JComboBox box=new JComboBox();
box.addItem("abc");
box.addItem("zzz");
box.addItem("ccc");
add(box);
i used many jComboBox Components but it's not working.
How to sort this list into ascending order?
You can have a look at the SortedComboBoxModel.
This model extends the DefaultComboBoxModel and has two additional
pieces of functionality built into it:
upon creation of the model, the supplied data will be sorted before
the data is added to the model when adding new items to the model, the
items will be inserted so as to maintain the sort order
The default sort order will be the natural sort order of the items
added to the model. However, you can control this by specifying a
custom Comparator as a parameter of the constructor.
Here's an example how to use it (taken from there):
String[] items = { "one", "two", "three" };
SortedComboBoxModel<String> model = new SortedComboBoxModel<String>(items);
JComboBox<String> comboBox = new JComboBox<String>(model);
comboBox.addItem("four");
comboBox.addItem("five");
comboBox.setSelectedItem("one");
Source code
You can override the default behavior of addItem to suit your needs.
Runnable Example
public class SortedCombobox {
#SuppressWarnings("serial")
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Overriden JCombobox");
frame.getContentPane().setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox box = new JComboBox(){
#Override public void addItem(Object obj){
int count = getItemCount();
String toAdd = (String) obj;
List<String> items = new ArrayList<String>();
for(int i = 0; i < count; i++){
items.add((String)getItemAt(i));
}
if(items.size() == 0){
super.addItem(toAdd);
return;
}else{
if(toAdd.compareTo(items.get(0)) <= 0){
insertItemAt(toAdd, 0);
}else{
int lastIndexOfHigherNum = 0;
for(int i = 0; i < count; i++){
if(toAdd.compareTo(items.get(i)) > 0){
lastIndexOfHigherNum = i;
}
}
insertItemAt(toAdd, lastIndexOfHigherNum+1);
}
}
}
};
box.addItem("zzz");
box.addItem("hh");
box.addItem("aa");
box.addItem("yy");
box.addItem("uu");
box.addItem("bb");
box.addItem("rr");
box.addItem("aa");
box.setSelectedIndex(0);
frame.getContentPane().add(box);
frame.pack();
frame.setVisible(true);
}
});
}
}
The SortedComboBoxModel link from Alexis C. does not appear to work anymore, although the source link still works.
Nonetheless, I created a SortedComboBoxModel for classes that implement Comparable (based on this example).
public class SortedComboBoxModel<E extends Comparable<? super E>> extends DefaultComboBoxModel<E> {
public SortedComboBoxModel() {
super();
}
public SortedComboBoxModel(E[] items) {
Arrays.sort(items);
int size = items.length;
for (int i = 0; i < size; i++) {
super.addElement(items[i]);
}
setSelectedItem(items[0]);
}
public SortedComboBoxModel(Vector<E> items) {
Collections.sort(items);
int size = items.size();
for (int i = 0; i < size; i++) {
super.addElement(items.elementAt(i));
}
setSelectedItem(items.elementAt(0));
}
#Override
public void addElement(E element) {
insertElementAt(element, 0);
}
#Override
public void insertElementAt(E element, int index) {
int size = getSize();
for (index = 0; index < size; index++) {
Comparable c = (Comparable) getElementAt(index);
if (c.compareTo(element) > 0) {
break;
}
}
super.insertElementAt(element, index);
}
}
This can be used like so:
public static void main(String[] args) {
javax.swing.JComboBox<String> sortedComboBox = new javax.swing.JComboBox<>();
String[] testArray = new String[]{"DDD", "AAA", "CCC", "BBB"};
sortedComboBox.setModel(new SortedComboBoxModel<>(testArray));
//print out the sorted contents
for (int i = 0; i < sortedComboBox.getItemCount(); i++) {
System.out.println(i + ": " + sortedComboBox.getItemAt(i));
}
}