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;
}
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 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
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 4 years ago.
Improve this question
I want to use a Class to hold user inputs. For example "example_name";"example_value";"example_city" is the form of the input and I want to make objects from an input stream of theese three inputs line by line from a file. So whenever I enter Adam;27; London it should be saved into an Object(Adam,27,London) and ask for the next input.
Thank you for your help, I know this might be a stupid question but I'm new to OO programming and I have a C background and don't want to use two dimensional arrays.
Let's break this problem into 3 section. First, we will have to design the class. Second, we will take the user input and create an object of that class until the user press n(no). Third, we will display the user information. Here I have used a LinkedList data structure for storing the inputs.
Section 1:
class example{
String example_name;
int example_value;
String example_city;
example(String name,int value,String city)
{
this.example_name = name;
this.example_value = value;
this.example_city = city;
}
}
section 2:
LinkedList<example> ob = new LinkedList<>();
Scanner input = new Scanner(System.in);
System.out.println("Press y to Continue n to Exit");
char i = input.next().charAt(0);
while(i!='n')
{
input.nextLine();
System.out.println("Enter name");
String name = input.nextLine();
System.out.println("Enter value");
int value = input.nextInt();
input.nextLine();
System.out.println("Enter city");
String city = input.nextLine();
ob.addLast(new example(name,value,city));
System.out.println("Press y to Continue n to Exit");
i = input.next().charAt(0);
}
Section 3:
for(example x:ob)
System.out.println(x.example_name + " " + x.example_value + " "+x.example_city);
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
We ask to the user if he wants to do it again or finish.
The thing is we let him put [Y] or [N] answer, but can be that he mistakes.
So my problem enters here...
Structure one
//kb = keyboard
Scanner kb = new Scanner(System.in);
//String for the [Y] or [N] answer
String r = "";
//boolean to go out the loop and finish
boolean out = true;
do {
//rest of the code of the program
some stuff
//
System.out.println("Do you want to do it again?\n"
+ "[Y] or [N]");
r = kb.next();
}while(r == "y" || r == "Y");
Structure two
do {
//rest of the code of the program
some stuff
//
System.out.print("Do you want to do it again?\n"
+ "[Y] or [N]");
String answer = kb.next();
switch (answer)
{
case "Y": out = true;
break;
case "y": out = true;
break;
case "N": out = false;
break;
case "n": out = false;
break;
default :
System.out.println("Not a valid option") ;
break;
}//end switch
}while(out);
And how I can do it better if the user answer with another word?
This is really a style question. There's no exact right answer.
The switch is a lot more code, so I'd avoid that.
You can take care of the case issue with
r = kb.next().toUpperCase();
and then use
while ( r.equals("Y") )
since r is a string.
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
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 8 years ago.
Improve this question
I'm currently taking my first java class and have become completely stuck on an exercise. I'm supposed to read data from a text file containing student IDs and their corresponding test scores, have the program grade them then print the results.
I kind of understand the problem, but the book we're working from is kinda hard to read. It all blurs together and I feel like they want me to read two separate things and make a logical leap on how to put them together and I just don't get it.
TTFTFTTTFTFTFFTTFTTF
ABC54102 T FTFTFTTTFTTFTTF TF
DEF56278 TTFTFTTTFTFTFFTTFTTF
ABC42366 TTFTFTTTFTFTFFTTF
ABC42586 TTTTFTTT TFTFFFTF
My main issue is that I don't see how I tie the array to the data I have.
I am not gonna post the whole solution but give some steps to start.
Follow this example
BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
ArrayList<String> array = new ArrayList<>();
while ((line = reader.readLine()) != null) {
array.add(line);
}
and to split the string like this
str.split(" "); // considering that ids and name are separated by spaces
So, since blanks are allowed in your list of T's and F's, which I assume means the student left the answer to the question blank, you do not have the luxury of using a convenience method like split to easily separate the answers. Instead we use our knowledge that the number of questions must be the same, and id's must have a common length. You can use the substring method to parse out the what you need.
Here's some pseudocode:
final int NUM_QUESTIONS = 25; //I didn't actually count, that's your job
final int ID_LENGTH = 8;
int currentIndex = 0;
//assuming you can fit the whole string in memory, which you should in an intro java class
//do the operations that googling "read a file into a string java" tells you to do in readFileToString
String fileContents = readFileToString("saidFile.txt");
while(fileContents.charAt(currentIndex) != fileContents.length()){
String userAnswers = fileContents.substring(currentIndex, currentIndex+NUM_QUESTIONS);
//move index past userAnswers and the space that separates the answers and the id
currentIndex = currentIndex + NUM_QUESTIONS + 1;
String userId = fileContents.substring(currentIndex, currentIndex+ID_LENGTH)
//move currentIndex past userId and the space that separates the userId from the next set of answers
currentIndex = currentIndex + ID_LENGTH + 1;
//either create an object to store the score with the userId, or print it right away
int score = gradeAnswers(userAnswers)
System.out.println(userId + " scored " + score);
}