Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am making a very simple game of Battleship to get my head around the concept of OOP.
I have a Board object filled with Square objects, and each Square object keeps track of whether there's a ship(also an object) on it and whether the player has already hit the Square. My method is supposed to take in coordinates from the player and then update the character on the board ("x" or "o") depending on whether the player hit a ship or not.
It's working fine, except that I have to press enter twice after inputting the coordinates before the program will show me the updated board? Why is this happening? How do I prevent the scanner from prompting that additional 'enter' from being pressed?
I have tried to add a String to read the new line after entering the ints (s.nextLine()), but it doesn't seem to make any difference.
public Square[][] userGuess() {
System.out.println("Please enter your coordinates: x y");
Scanner s = new Scanner(System.in);
int row = s.nextInt();
int col = s.nextInt();
Square target = board[row][col];
Battleship ship = target.getShip();
target.setUncovered(true);
if(target.isOccupied() == true && ship.getHealth() == 2) {
ship.setHealth(ship.getHealth()-1);
System.out.println("Hit!");
}
else if(target.isOccupied() == true && ship.getHealth() == 1) {
ship.setHealth(ship.getHealth()-1);
ship.setAfloat(false);
System.out.println("You sunk a ship!");
}
else if(target.isOccupied() == false) {
System.out.println("Miss!");
}
return board;
}
Just String inputString = scanner.nextLine() and then split the string on a whitespace using String.split method and convert the string tokens to ints using Integer.valueOf
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 hours ago.
Improve this question
I am a beginner in Java and this issue arose when I was working on a HackerRank problem that I have solved but it still confuses me why it wouldn't work the first iteration of code I made to solve it. This code function is to separate a string and an integer into two columns with the integer being limited to three digits and string having 10 chr limit, covered by "========". Also, I intend the code only ends when the user has inputted "nothing" or white spaces.
However, the do while loop keeps going as its condition does not match the inputted variables created by the scanner, being white spaces. I had a clue that it might be when I used an integer scanner as it interfered with the string scanner, but I tried clearing the scanner by using nextLine(), and it wouldn't work with the loop. I tried using scanner.reset() and also declaring the integer first as a string and then converting it back to an integer but the loop keeps going. I tried simplifying it, and I found out that the loop ends when I use "word = scanner.nextLine();" but it wouldn't work with the loop. Hope you guys can educate me and possible ways to fix this issue.
package hackerRankTestCode;
import java.util.Scanner;
import java.lang.*;
import java.util.concurrent.atomic.DoubleAdder;
public class TestCode {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word = "";
Integer number = 0;
String baruNumber = "";
System.out.println("================================");
do {
word = scanner.next();
number = scanner.nextInt();
String blank = new String(new char[15 - word.length()]).replace("\0", " ");
if(number<100 && number>=10){
baruNumber = "0"+number;
System.out.println(word+blank+baruNumber);
}
else if(number>=0 && number<10) {
baruNumber = "00"+number;
System.out.println(word+blank+baruNumber);
}
else if(number>=100) {
System.out.println(word+blank+number);
}
}
while(!word.isBlank() && number != 0);
scanner.close();
System.out.println("================================");
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a function that, for example, read numbers line by line, and calculates the sum of those numbers.
The user enters the numbers, one number per line, and when enters 'null', the program breaks and give the result.
For example:
>>8
>>5
>>4
>>
The result is 17
How can I do that the program breaks when the input is empty and give the result?
This is the code that I thought of using scanner. The comment in the code is where I think you might have messed up on, key areas, and things that you asked.
public static void sumInputs(){
Scanner data=new Scanner(System.in);
ArrayList <Double> allNumbers=new ArrayList<>();
while(true){
System.out.print("Number:");
try{
//IMPORTANT: Notice I use "nextLine" and not "next", because next will wait till user inputs something not null
//and ignours the "enter" key pressed, while "nextLine" executes when the user presses the key "enter" regardless
//of whether there is input.
//I would imagine this is your problem
String number=data.nextLine();
//The part you are looking for
//Right here is the part you are looking for
if(!number.isEmpty()){
//what to do if it is not null (store the numbers
//in an ArrayList).
allNumbers.add(Double.parseDouble(number));
}else{
//add up all the numbers if it is null
double sum = 0;
for( double i : allNumbers) {
sum += i;
}
System.out.println("The result is "+ sum);
System.exit(0);
}
}catch(InputMismatchException e){
System.out.println("Not number");
}
}
}
string mystr;
getline(cin,mystr);
if(mystr.empty())
//do stuff
else
//do stuff
i am sorry i tought this was a c++ question when i saw >> anyway here is the java version
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
if(text.isEmpty())
//do stuff
else
//do stuff
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I have a little bit of programming experience in web development languages such as HTML, CSS, JQuery, JavaScript, PHP, Python etc., but I am no taking an AP Computer Science class at school to learn Java. To see how similar it is to other languages in both syntax and how to go about different problems I decided to make a simple blackjack game that i have made in other languages before.
I have run into and error where I want to check to see what the user has input, and if it is a certain character, output different things such as a help sentence, welcome message, or just simply start or stop the game. For some reason it reads the input and I can log it to the console but it will not run the methods that I have created and called in the if statement inside the while loop. I am going to post the whole script since I have only been programming in Java for 2 weeks or so now and have no idea where my error could be.
import java.util.Scanner;
public class testClass {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
// Creates a scanner to get input from the keyboard
boolean gameStart = false;
// starts false, turns true when 'B' is input
welcome();
//displays the welcome message
while (true) {
// loop to play the game
String input = kbd.nextLine().toUpperCase();
// gets the next input from the user
if (input == "B") {
// checks the users input
gameStart = true;
// 'turns on' the game
double[] hand = drawCards();
// makes an array of 2 cards
System.out.print(input); //REMOVE
} else if (input == "?") {
// checks the users input
help(gameStart);
// displays the help message depending on if the game has started or not
System.out.print(input); //REMOVE
} else if (input == "Q") {
// checks the users input
System.out.print(input); // REMOVE
break;
// ends the game loop
} // ends if
} // ends while
} // end main
public static void welcome() {
// displays the welcome message
System.out.printf("Welcome to blackjack! %nEnter 'B' to begin. %nEnter '?' at any time to see help %nEnter 'Q' at any time to quit %n => ");
// the welcome message
}
public static void help(boolean gameStart) {
//displays the help message
if (gameStart) {
System.out.printf("Enter '?' at any time to see help %nEnter 'Q' at any time to quit %nEnter 'H' to hit %nEnter 'S' to stay %n => ");
// the help message when the game has already started
} else {
System.out.printf("Welcome to blackjack! %nEnter 'B' to begin. %nEnter '?' at any time to see help %nEnter 'Q' at any time to quit %nEnter 'H' to hit %nEnter 'S' to stay %n => ");
// the help message when the game hasn't started
}
} // end help
public static double randCard() {
// creates a random card
double card = Math.round(Math.random() * 10);
// number 1-10
if (card == 10 || card == 0) {
// no cards at 10 or 0
double x = Math.round(Math.random() * 10);
// variable used to choose J Q K or A when card is 0 or 10
if (x < 3) {
// Jack
card = 11;
} else if (x < 5) {
// Queen
card = 12;
} else if (x < 7) {
// King
card = 13;
} else {
// Ace
card = 10;
}
}
return card;
// returns a single card
} // end randCard
public static double[] drawCards() {
//creates 2 random cards and returns an array
double card1 = randCard();
double card2 = randCard();
// stores the 2 random cards in variables
double[] cards = {card1, card2};
// places the 2 random cards in an array
return cards;
// returns the array of cards
} // end drawCards
} // end class
There are list of things you need to correct:
As per Java Naming Conventions it's recommended to have class names starting with First letter as caps - Camel Case convention
String comparison should be done via equals() and not '==' that compares references.
That means that, change the occurrences of:
input == "B" to input.equals("B")
input == "?" to input.equals("?")
input == "Q" to input.equals("Q")
Be aware that if the inputis null, it will result in NullPointerException. Better practice would be to use "B".equals(input) in that case. Looks like these are already answered as part of comments as well.
P.S : I can't say that your program will work correct after this change, But correction of these should help you.
Use equals() method of string instead of ==. Hope that helps.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The code runs properly the first time then run it again using the while loop and lets say the first time I entered AA and it becomes CC then it runs again I enter AA again it will come out with CCCC do it again it comes out with CCCCCC I don't want that I need it to not keep the data from the string each time it loops.
import java.util.*;
public class SecretCypher {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
StringBuffer e = new StringBuffer();
System.out.println("Welcome to Secret Cypher!");
char loop = 'Y';
while(loop == 'Y' || loop == 'y') {
System.out.println("");
System.out.println("Enter your cypher in upper case.");
String s = kb.nextLine();
char[] cs = s.toCharArray();
for (int i = 0; i < cs.length; i++) {
e.append((char)('A' + (cs[i] - 'A' + 2) % 26));
}
if(s == s.toLowerCase()) {
System.out.println("Remember to use upper case letters!");
System.exit(0);//Also I was bored of using break and this works any where in the code.
}
System.out.println(e.toString());
System.out.println("Do you want to enter another cypher? > ");
String again = kb.nextLine();
if(again.charAt(0) == 'N') {
System.out.println("Hope you come back again!");
break;
}
}
}
}
You're reusing the same string buffer. If you keep putting things into the same buffer without clearing it, you're obviously going to get extraneous stuff from previous iterations.
Simply declare the StringBuffer inside the while loop so that it is created on each iteration.
Anyway, you should learn to use your debugger, instead of asking here for us to debug. If anything, using the debugger can offer extremely valuable insight into the troubles that you are having here.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
hi i'm trying to make a questions game to try my knowledge and abilities
anyway i'm trying to use an integer to be the points and every question the user
answer gets a special amount of points anyway i was trying to do like this
switch (Ques){ case 1 : //first question about India and where it is in the map
System.out.println("in what continent India is?");
Scanner IndiaAns = new Scanner(System.in); //Scanner to receive user answer
String IndiaAns2 , IndiaAnswer ; //strings to be used to receive user input and matching with the correct ones
IndiaAns2 = IndiaAns.nextLine(); //Scanner will work here and receive...
IndiaAnswer = "asia"; //the correct answer here and will be matched with user ones
if (IndiaAns2 == IndiaAnswer)
{int Twopoints = 2; Points = + Twopoints; } else{}
case 2:
System.out.println("the Appstore founds in any phone model?");
Scanner Appstore =new Scanner(System.in);
String AppstoreAns1 ,AppstoreAns2; //strings saving
AppstoreAns1 = Appstore.nextLine(); //Scanner
AppstoreAns2 = "iphone"; //matching with user answer
if (AppstoreAns1 == AppstoreAns2)
{ int Threepoints = 3; Points = +Threepoints;} else { Points = +0;}
.. there's two other case and the points integer is in not in the code sample area is in upper line any ways if the full codes its necessary i'll put it
About your code ,
if (IndiaAns2 == IndiaAnswer)
{int Twopoints = 2; Points = + Twopoints; } else{}
Should be something like
if(indiaAns2.equals(indiaAnswer)){
points += QUESTION_1_POINTS;
}
Where QUESTION_1_POINTS is defined as a constant like `
public static final int QUESTION_1_POINTS =2;
There you are assigning to points variable , points + QUESTION_1_POINTS.
points += someInteger --> points = points + someInteger
Some advices,
1) Follow Java Code Conventions , variable names start with lower-case
2) For object comparision always use equals() instead of ==
Example:
Change
if (IndiaAns2 == IndiaAnswer)
to:
if (indiaAns2.equals(indiaAnswer))
3) You need to make switch statement
switch(condition){
case 1:
//code
break;
case 2:
//code
break;
default:// some code;
}