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
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 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 3 years ago.
Improve this question
Code I wrote is below -
public class Demo{
public static void main(String[] args){
System.out.print(“Hearing in the distance”);
System.out.print(“Two mandolins like creatures in the “);
System.out.print(“dark”);
System.out.print(“Creating the agony of ecstacy.”);
System.out.println(“ - George Barker”);
}
}
I want to show each print one by one after each enter button pressed.
`
use java.util.Scanner
if you call Scanner.nextLine() your app waits until you write something and press enter or you can press enter without writing anything.
You can do like this below - after every enter button press it will print next value of course you can edit the code accordingly
private static void printNext(){
Scanner scanner = new Scanner(System.in);
int count = 3;
while(count> 0) {
if(count == 1){
System.out.println("Hearing in the distance");
}else if(count ==2 ){
System.out.println("Two mandolins like creatures in the");
}else {
System.out.println("Creating the agony of ecstacy.");
}
count--;
if (scanner.hasNextLine()) {
scanner.nextLine();
}
}
}
Hope this will help you.
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 4 years ago.
Improve this question
I want to get a user input number to print out "Color 1 Color 2..." etc. depending on what number the input is.
I want to do this but in java, and I'm not quite sure where to find it.
How to iterate a for loop for a user input in Java?
That will do the work, using only standard java classes (java.io.Console):
import java.io.Console;
public class Consoler {
public static void main(String[] args) {
final Console console = System.console();
console.printf("How may times?\n");
final String line = console.readLine();
try {
final int quantity = Integer.parseInt(line);
for (int i = 1; i <= quantity; i++) {
System.out.printf("Color %d ",i);
}
System.out.println();
} catch (final NumberFormatException e) {
System.err.println(line + " is not a number.");
}
}
}
java.util.Scanner is probably what you're looking for. As for the for loop, you should google Java for loop and read up on how they work. Then combine the two concepts.
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 8 years ago.
Improve this question
Also, how would I prompt the user to try again until they enter something with only 1 or 0 in it?
I realize I must use a for, or a while loop, but I'm not sure what to put as the condition.
I'm trying to have it so the user is prompted to enter something in binary, and if they don't enter something in binary, to be asked again to enter something in binary, and repeated until they do.
Thanks in advance!
You can do this by a simple regular expression matching:
if (inputString.matches("^[01]+$")) {
// accept this input
}
Simply use Integer.parseInt (str, 2);
it will throw a NumberFormatException if not binary
You can inspect every character of the String like so:
String s;//user input
boolean bad=false;//Starts false-will change to true if the input is bad
for(char c:s.toCharArray())
if(!(c=='0'||c=='1')){//if c isn't 0 or 1
bad=true;
break;//break out of loop because we've already found a problem
}
You may want to use the pattern below. The concept is to provide a "regular expression" that provides the rules for a conforming string, along with the message to prompt the user for input and the source to read the user's input from. The loop continues until a conforming string is found, or the user breaks out with "exit". The function would return the conforming string, or a null if the user wants to exit.
public String getConformingString(Scanner source, String message, String pattern) {
String result = null;
boolean isConformingString = false;
System.out.println(message);
String trialString = source.mextLine();
while (!isConformingString) {
if (trialString.matches(pattern) {
isConformingString = true;
result = isConformingString;
} else if ("exit".equalsIgnoreString(trialString)) {
isConformingString = true;
} else {
System.out.println(message);
trialString = source.nextline();
}
}
return result;
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
i am getting "illegal character '\u600b' in my return statement for the following code:
public static int getNum() {
Scanner in = new Scanner(System.in);
int number;
boolean goodInput = true;
do {
goodInput = true;
try {
System.out.print("Please enter a positive number: "); // prompts the user
number = Integer.parseInt(in.nextLine()); // Tries to make the next input a number
} catch (Exception e) { // if it breaks
System.out.println("The number you entered was invalid."); // it tells the user it was wrong
goodInput = false; // and runs the loop again
}
if(number <= 0) { // makes sure that the number entered was valid
System.out.println("The number you entered was invalid.");
goodInput = false; // or it re runs the loop
}
}while (!goodInput)
return number;
}
any one know how to fix this?
In looking at the Markdown source of your post, I found a stray non-printable character right before the return. You need to delete that entire line and retype it (or delete that character itself).
If you place the cursor between the r and the e, and press <- a few times, you will see that the cursor does not move one of those times.