I am writing a program which part is presented below:
public class Portal {
private String name;
private int[] positions; // positions of "ship"
private static int moves = 0; // moves made by player to sink a ship
public static int shot; // the value of position given by player
private int hits = 0; // number of hits
private int maxSize = 4; // max size of ship (the size will be randomized)
int first; // position of 1st ship block
int size; // real size of ship (randomized in setPortal method)
public void checkIfHit(){
for (int i : positions){
if (i == shot){
System.out.println("Hit confirmed");
hits++;
} else if (hits == positions.length){
System.out.println("Sunk");
} else {
System.out.println("Missed it");
}
}
moves++;
}
public void setPortal(){
size = 1 + (int)Math.random()*maxSize;
for (int i = 0; i < size - 1; i++){
if (i == 0){
positions[i]= 1 + (int)Math.random()*positions.length;
first = positions[i];
System.out.println(positions[i]);
continue;
}
positions[i]= first + 1;
System.out.println(positions[i]);
}
}
}
public class Main{
public static void main(String[] args){
// write your code here
Portal p1 = new Portal();
p1.setPortal();
}
}
code is split in two Java .class files.
The problem I'm dealing with is that using p1.setPortal(); doesn't show up text in IntelliJ console. The program works though and returns 0.
I don't have such problem in another program when I've put System.out.println in method other than main (also in separate class file).
What may be the cause of such issue?
It should properly throw an exception, because you forgot to initialize the integer array.
Have a look at this thread: Do we need to initialize an array in Java?
The Java's default value is null for an integer array. So your for wont even loop trough. The only thing that wonders me is why there is no exception..
Related
I'm making a card game, and I've arrived at the shufflin' time.
I've to shuffle a few cards (that are chosen before from the user, so they're not always the same amount) and then display them to the user one by one.
As I'm still developing the game's logic I'm displaying cards' name by changing a button text.
But I get stuck when I try to get the cards' name and set them as the button's text.
What happens is me gettin' a blank button or just with "Masons" or "Villager" String. Infact if I check the log I see that all the others cards(characters) get displayed as "null".
This is how I tried to achieve the goal (Yes I'm a newbie):
This is the head:
int demoniac;
int guard;
int masons;
int medium;
int mythomaniac;
int owl;
int villager;
int werehamster;
int all;
int i;
int t;
String[] characters = new String[24];
Button randomButton;
My method to addAll the cards(characters):
public void addAll(){
for(i = 0; i < all; i++){
add(demoniac, "Demoniac");
add(guard, "Guard");
add(medium, "Medium");
add(mythomaniac, "Mythomaniac");
add(owl, "Owl");
add(werehamster, "Werehamster");
add(villager, "Villager");
add(masons, "Masons");
}
}
My method to add and manage the various types of cards(characters):
public int add(int character, String name){
if(character != 0 && name == "Villager"){
for(t = 0; t < character; t++){
i+=t;
characters[i] = name;}
}
else if(character == 2 && name == "Masons"){
characters[i] = name;
i++;
characters[i] = name;
Toast.makeText(randomSelection.this, "works", Toast.LENGTH_SHORT).show();
}else if(character != 0){
characters[i] = name;
}
return i;
}
To randomize:
public void randomize(){
Collections.shuffle(Arrays.asList(characters));
for (int s = 1; s < characters.length; s++)
{
System.out.println(characters[s]);
}
}
The method to display a different card(character) each time the user clicks the button:
public void show(View view){
for (int s = 1; s < characters.length; s++)
{
randomButton.setText(characters[s]);
}
}
EDIT:
I've noticed the no sense for loop I've done, by the way you should know although most of the characters are only 1 of their kind (demoniac, guard, etc..) there are 2 Masons and from 5 to 12 Villagers, so We need to retrieve these ints and add as much Strings to the Array as much we're told from those ints.
Example: If I get 6 Villagers, I've to add the String "Villager" 6 times into the String Array.
Then I've set that s value to 1 'cause I've to display the first
String ([0]) as soon as the Activity gets started, so on the OnCreate() method.
Maybe I'm wrong, if so I please you to correct me!
Getting a blank button or just with "Masons" or "Villager" String
That is because you only set the Button's text with the last element of the list. Which is either null or "Masons" (not seeing how it could be "Villager").
for (int s = 1; s < characters.length; s++)
{
randomButton.setText(characters[s]);
}
If I check the log I see that all the others cards(characters) get displayed as "null"
You only set position 0 of your array. For example, you don't initialize the positions, so these int values default to 0.
int demoniac;
int guard;
int all;
Then
for(i = 0; i < all; i++){
add(demoniac, "Demoniac");
add(guard, "Guard");
Really, that loop shouldn't be entered because all equals 0.
Additionally
Collections are zero-indexed, so this doesn't print element 0. You need to set int s = 0;.
for (int s = 1; s < characters.length; s++)
It isn't clear to me what the add(int character, String name) method is returning, but if you explain it, I will update this answer.
I believe this code fulfills most of what you are trying to achieve
// Where the characters are stored
private ArrayList<String> characters;
public void initDeck() {
if (characters == null)
characters = new ArrayList<String>();
// Extract the numbers if you actually need them, otherwise, they just are constants
addCharacter("Demoniac", 1, characters);
addCharacter("Guard", 1, characters);
addCharacter("Medium", 1, characters);
addCharacter("Mythomaniac", 1, characters);
addCharacter("Owl", 1, characters);
addCharacter("Werehamster", 1, characters);
addCharacter("Villager", 5, characters);
addCharacter("Masons", 1, characters);
}
public void addCharacter(String name, int amount, ArrayList<String> cards) {
if (amount < 0) {
throw new IllegalArgumentException("Must add a non-negative number of characters for " + name);
}
// Don't use '==' for Strings
if (name.equals("Villager")) {
if (amount != 5 || amount != 12) {
throw new IllegalArgumentException("There can only be 5 or 12 " + name);
}
}
for (int i = 0; i < amount; i++) {
cards.add(name);
}
}
public int searchCharacters(String character, ArrayList<String> cards) {
return cards.indexOf(character);
}
public Map<String, Integer> getAllCharacterPositions() {
Map<String, Integer> allPositions = new LinkedHashMap<String, Integer>();
for (int i = 0; i < characters.size(); i++) {
allPositions.put(characters.get(i), i);
}
return allPositions;
}
void run() {
// initialize the characters
initDeck();
// shuffle them
Collections.shuffle(characters);
// print them all out
for (int i = 0; i < characters.size(); i++) {
System.out.printf("%d: %s\n", i, characters.get(i));
}
// Find the position of a character
System.out.println();
String findCharacter = "Owl";
// Option 1 -- always linear search lookup
System.out.printf("%d: %s\n", searchCharacters(findCharacter, characters), findCharacter);
// Option 2 -- one-time linear scan, constant lookup
Map<String, Integer> positions = getAllCharacterPositions();
System.out.printf("%d: %s\n", positions.get(findCharacter), findCharacter);
// Get a random character
System.out.println();
Random rand = new Random(System.currentTimeMillis());
int randPos = rand.nextInt(characters.size());
System.out.printf("%d: %s\n", randPos, characters.get(randPos));
// randomButton.setText(characters.get(randPos));
}
Given the array is already shuffled, just look at the first card:
public void show(View view){
randomButton.setText(characters[0]);
}
If you want to navigate that deck I suggest you put the shuffled list in to a Queue, where you can look at the next card (peek) or take the next card (poll):
private static Queue<string> buildNewShuffledDeck(String[] characters){
List<String> shuffledCharacterList = new ArrayList<String>(characters);
Collections.shuffle(shuffledCharacterList);
Queue<string> deck = new ArrayDeque(shuffledCharacterList);
return deck;
}
public void show(View view){
String nextCard = deck.peek();
if (nextCard != null)
randomButton.setText(nextCard);
else
//deck is empty...
}
Then to take from the deck, say on the random button click:
String nextCard = deck.poll();
General advice on arrays: Stop using them in favor of other data types that are far more useful and interchangeable.
Then next step advice, make a class that represents a Card and stop using Strings, the string you currently have is just one property of a card.
You are just displaying the last character name that you add
Replace with this
public void show(View view){
Random r = new Random(System.currentTimeMillis());
randomButton.setText(characters[r.nexInt(characters.length)])
}
I'm trying to use this code to implement a Priority Queue. There are a number of questions regarding this implementation on the site, but given how many different ways you can write code to do essentially the same thing I am still at a loss after looking through a handful of other examples.
There are some missing lines in this code, but I am limited to editing only the four marked lines and so I find myself stuck on one particular aspect. I can't seem to understand how 'quantity' is incremented.
From my understanding main creates a new object of maxSize = 5. Then calls the insertItem method passing the value of 130. This should be placed into the root (I had put queArray[quantity] = item; into the first blank) at which point the insertItem method exits and is then called again with the next value. So at what point is 'quantity' incremented? Maybe I am missing something incredibly simple, or maybe there is another way of solving this that may not be apparent or known to beginners like me?
I would think you would want to increment quantity under the initial if statement, but that doesn't seem to be an option, so as far as I can tell the else statement can never be executed as quantity doesn't change. I know I am incorrect, but I don't know how, some help would be greatly appreciated.
public class Main {
/**
* #param args the command line arguments
*/
// array in sorted order, from max at 0 to min at size-1
private int maxSize;
private long[] queArray;
private int quantity;
public Main(int s) {
maxSize = s;
queArray = new long[maxSize];
quantity = 0;
}
public void insertItem(long item) {
int i;
if (quantity == 0)
__________; // insert at 0
else
{
for (i = quantity - 1; i >= 0; i--) // start at end,
{
if (item > queArray[i]) // if new item larger,
__________; // shift upward
else
// if smaller,
break; // done shifting
}
__________; // insert it
__________;
} // end else (quantity > 0)
}
public boolean PQEmpty(){
return (quantity == 0);
}
public long removeItemPQ(){
return queArray[--quantity];
}
public long peekMin(){
return queArray[quantity - 1];
}
public static void main(String[] args) {
Main thePQ = new Main(5);
thePQ.insertItem(130);
thePQ.insertItem(450);
thePQ.insertItem(110);
thePQ.insertItem(430);
thePQ.insertItem(280);
while (!thePQ.PQEmpty()) {
long item = thePQ.removeItemPQ();
System.out.print(item + " ");
}
System.out.println("");
}
}
It isn't a style I'd recommend, but you could use queArray[quantity++] = item;.
I have a program and want to create a simple highscore method for it. The method will only tell if the current amount of points is higher than the ones before.
public class Highscore {
public static int Highscore(int poang) {
int count = 0;
int poäng1 = 0;
int poäng2 = 0;
As you see in above, the counter is set to 0;. This is to save the first entry. However, it resets to 0 every time the method is being used. How can i recode this? Here is the rest of the code:
if (count == 0) {
poäng1 = poang;
count++;
} else if (count > 0) {
if (poäng2 > poäng1) {
poäng1 = poäng2;
}
}
return poäng1;
}
}
Local variables are redefined (and re-initialized) every time the block (in your case - a static method) is entered. If you want them to keep their value beyond the scope of that block, they should be defined outside of it.
In this case, you could have count as a (static) member:
private static int count = 0;
public static int Highscore(int poang) {
// Code comes here
Recently, I've been assigned to do a file by my teacher to make a program that simulates a TV.
I am supposed to add volume when the raiseVolume method is called. However, upon calling it, it looks like volume is not being affected whatsoever.
I have no clue as to why this could be.
(myTv is the object of the constructor in Tv)
Here is the Code for the TV Driver Class-
System.out.println ("Crank it up!");
int oldVolume = myTv.getVolume();
do {
oldVolume = myTv.getVolume();
myTv.raiseVolume();
} while (myTv.getVolume() != oldVolume);
System.out.println ("\t\tThe TV is " + myTv.getPower() +
" on channel " + myTv.getChannel() +
" at volume " + myTv.getVolume());
System.out.println ("That's a bit too loud");
myTv.lowerVolume();
myTv.lowerVolume();
and here is my code for the Tv Class-
private int volume = 0;
...
//Volume
public int getVolume(){
return volume;
}
public void raiseVolume(){
volume+=5;
}
public void lowerVolume(){
volume-=1;
if (volume > 0){
volume = 0;
}
}
If you need additional code, I will post it!
I've been called out for putting entire classes in here before, I don't wish to make the same error!
Because when you call lowerVolume after raiseVolume:
public void lowerVolume(){
volume-=1;
if (volume > 0){
volume = 0;
}
}
it will always set the volume to 0, as volume > 0 (at least 5) at that moment, you should change it to:
if (volume < 0){
volume = 0;
}
The two values will never be equal, and your while loop just terminates. Print the volume before and after the call and you'll see that it changes (assuming you're using the code you've posted)
System.out.printf("oldVolume = %d%n", myTv.getVolume());
myTv.raiseVolume();
System.out.printf("newVolume = %d%n", myTv.getVolume());
Also, your lowerVolume method always sets volume to 0 (if it's greater than zero). I think you mean less than
public void lowerVolume(){
volume--; // <-- does - 1
if (volume < 0){ // <-- less than
volume = 0;
}
}
It might be a good idea to add a max for raiseVolume(). Finally, I suggest you set the increment (and decrement) to be the same value (or pass that value in to the method); that is something like
private static final int MAX_VALUE = 100;
private static final int MIN_VALUE = 0;
public void lowerVolume(int change) {
volume -= change;
volume = Math.max(volume, MIN_VALUE);
}
public void raiseVolume(int change) {
volume += change;
volume = Math.min(volume, MAX_VALUE);
}
Or,
public void lowerVolume() {
volume--;
volume = Math.max(volume, MIN_VALUE);
}
public void raiseVolume() {
volume++;
volume = Math.min(volume, MAX_VALUE);
}
try something along the lines of a start volume of 0 so when you getVolume you can write in something like
if(tv.getvolume == 0){
volume++
}
I'm trying to figure out why 1) my Simon game hangs up after saying "Enter A Number"- it doesn't look like it even gets past validation. I'm trying to get user input, and check to see if that was the right number to press at that time. 2) Also, it used to generate a random number but when the user pressed it, it came back as false for some reason. Some other random number would pass though. 3) Also, is the code below color coded for you? Thanks guys.
import acm.program.*;
import acm.graphics.*;
import java.awt.Color;
import java.awt.Font;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.io.DataInputStream;
public class Simon extends Program implements ActionListener
{
Scanner usersInputScanner = new Scanner(System.in);
private int array[];
private int currentSeqLength;
private int usersInput;
private String usersInputString;
public Simon()
{
//Initialize Class Values
array = new int[20];
currentSeqLength = 1;
usersInput = 0;
generateSequence();
while(currentSeqLength < array.length)
{
playSequence();
//Wait For User's Input, Assign To Variable
System.out.println("Enter A Number");
usersInput = usersInputScanner.nextInt();
if (pushButton(usersInput) == true)
{
System.out.println("You Entered: " + usersInput);
currentSeqLength++;
}
else
{
gameOverMessage();
break;
//Reset Variables:
}
}
}
//----------------------- Methods Here On Down -----------------------------
public void generateSequence()
{
//Fill Array With Random Numbers
for (int i = 0; i < array.length; i++ )
{
array[i] = (int)(Math.random()*4);
}
}
public void setLength(int length)
{
//Set Current Length To Size Of Given Argument
currentSeqLength = length;
}
int getLength()
{
return currentSeqLength;
}
int[] playSequence()
{
//Print Out The Current Sequence
//New Local Array To Return
int newArray[]= new int[currentSeqLength];
//Repeat As Many Times As Value Of currentSeqLength
for(int i = 0; i < currentSeqLength ; i++)
{
System.out.println(array[i]);
//Return an array of int's to the player.
newArray[i] = array[i];
}
return newArray;
}
boolean pushButton(int usersInput)
{
//Given A Button Press (0-3), Return Whether That Was The
//Correct Button To Play At The Moment
if (usersInput == array[currentSeqLength])
{
return true;
}
else
{
return false;
}
}
boolean isTurnOver()
{
//If Current Sequence Length Matches Or Exceeds Value Of
//Array Element In Location Of Current Sequence Length
if (currentSeqLength >= array[currentSeqLength])
{
return true;
}
else
{
return false;
}
}
//Not Needed?
boolean isGameOver()
{
if (pushButton(usersInput) == false)
{
return true;
}
else
{
return false;
}
}
String gameOverMessage()
{
return "Game Over";
}
/*public void actionPerformed(ActionEvent event)
{
int input;
}
*/
}
1) my Simon game hangs up after saying "Enter A Number"- it doesn't
look like it even gets past validation.
It's working fine, but you need to System.out.println the string that is returned from gameOverMessage(). Right now, it runs perfectly but there's no output to the console, so it looks unresponsive (and it's not hanging, it just reaches the end of execution, and stops).
else {
gameOverMessage();
break;
}
should be
else {
System.out.println(gameOverMessage());
}
2) Also, it used to generate a random number but when the user pressed
it, it came back as false for some reason.
I'm not getting this behavior in your sample code, it looks like it works as expected.
3) Also, is the code below color coded for you?
Yep, the preview box on SO sometimes takes a second to do the syntax highlighting. It works fine though.
Incidentally, 3 questions in one is a bit of a slog for the answerer. In the future perhaps try to limit yourself to one :)