This question already has answers here:
Why Wont My Java Scanner Take In input?
(3 answers)
Closed 7 years ago.
When I run my code, it works right up until it asks the question "which operation do you want to use from ( sum , subst , multi , div )". No matter what the user picks, there is no response from my program!
Why is this happening?
import java.util.Scanner;
import java.io.*;
public class three3 {
public static void main (String[] args) {
int x;
int y;
int opera;
String oper;
Scanner in = new Scanner (System.in);
System.out.println(" write the first number ");
x = in.nextInt();
System.out.println(" write the second number ");
y = in.nextInt();
System.out.println(" which operation do you want to use from ( sum , subst , multi , div )");
oper = in.nextLine();
if (oper == "sum") {
opera=x+y;
System.out.println(" the sum of two numbers is " + opera );
}
if (oper == "subst") {
opera = x - y;
System.out.println(" the subtraction of two numbers is " + opera );
}
if (oper == "multi") {
opera = x * y;
System.out.println(" the multi of two numbers is " + opera );
}
if (oper == "div") {
opera = x / y;
System.out.println(" the division of two numbers is " + opera );
}
}
}
Because none of those if-clauses is executed.
You're comparing Strings with == which is wrong. Use oper.equals("sum") instead. See this question for reference. The conclusion for you is to always use equals for Strings.
You need to call in.nextLine() right after the last call to in.nextInt() The reason is that just asking for the next integer doesn't consume the entire line from the input, and so you need skip ahead to the next new-line character in the input by calling in.nextLine().
int y = in.nextInt();
in.nextLine();
This pretty much has to be done each time you need to get a new line after calling a method that doesn't consume the entire line, such as when you call nextBoolean() etc.
In addition, you don't check for String equality with the == operator, use the .equals() String method instead.
The problem is that in.nextLine() consumes the \n inserted implicitly when you clicked enter after the int was entered. That means that the program doesn't expect any other input from the user. To fix this you could consume a new line with in.nextLine() before putting it int your actual variable, something like this:
System.out.println(" write the second number ");
y=in.nextInt();
System.out.println(" which operation do you want to use from ( sum , subst , multi , div )");
in.nextLine(); //New line consuming the \n
oper=in.nextLine();
if(oper.equals("sum")){//replace == by .equals
opera=x+y;
}
Apart from that, and as runDOSrun said, you should replace the comparisons of strings from a==b to a.equals(b)
Adding on to other people's points, you should also consider using else if{} and else{} statements so you can catch invalid input.
Related
I am stuck in this program that is string method, my issue is that I cannot get the loop to stop and the program to print the output that is currently stored after the keyword has been entered. I am not trying to compare strings, I am trying to input multiple strings and add a word, in this case, "not" to the strings until the word "stop" is entered. Once "stop" has been entered. the system will output the entire string stored.
Here is the question for the program:
(StringConcat.java) This program asks the user to repeatedly enter a String. It ,should concatenate those Strings together, but insert spaces and the word “not” between every pair of words the user enters. Stop when the user enters the String “stop”. Display the final String. For instance, the program output might look like:
Please enter some Strings:
"Such"
"eyes"
"you"
"have"
"stop"
"Such not eyes not you not have"
Here is my code so far:
import java.util.*;
public class StringConcat{
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
String s = new String();
System.out.print("Please enter some Strings: ");
for(int x=0; x<s.length(); x++){
s = sc.nextLine();
s = s + "not ";
if(s == "stop"){
System.out.println(s);
break;
}
else{
continue;
}
}
}
}
Several issues with your code:
(1) Why do you use a for loop and iterate up to s.length() when the length of s (which is 0 at that point) has nothing to do with your problem?
You need a loop which has not predefined number of iterations like a while (true) from which you will exit with a break.
(2) In each iteration you get the user's input and store it in s, so you lose all previous values.
You need a separate variable to store the user's input.
(3) The continue statement is not needed as the last statement in a loop.
(4) Because at each iteration you append " not " at the end, after the loop has finished you must delete that last " not " from s
(5) Don't use == when you compare strings. There is the method equals() for this.
This is my solution:
Scanner sc = new Scanner(System.in);
String s = "";
System.out.print("Please enter some Strings: ");
while (true){
String input = sc.nextLine();
if(input.equalsIgnoreCase("stop"))
break;
s += input + " not ";
}
if (s.length() >= 5)
s = s.substring(0, s.length() - 5);
System.out.println(s);
Use while loop.
Why while loop?
Usually we have to use while loops always when we don't know the number of loops we will do. In this case only when the user inputs "stop".
So you need a String field to hold the user words. Also we can use a number field to track if is the first or the second word, thinkg in append the "not" word.
Then, take a look in this example:
Scanner s = new Scanner(System.in);
String currentAnswer = "";
String userWords = "";
int tracker = 0;
while (!currentAnswer.equals("stop")){
currentAnswer = s.nextLine();
userWords += currentAnswer + " ";
if (tracker % 2 != 0) {
userWords += "not ";
}
tracker++;
}
System.put.println(userWords);
This can be done using for loop too but I really recommend the while loop to this case.
EDIT:
As you saw, I used equals() instead == to compare two Strings because we are wiling to check for its value, not for its object equality.
When we use == operator we are trying to check if two objects target to the same memory adress, but we only want to know if two Strings have the same value.
For this case is valid to know that we can compare it using other ways, such as Objects.equals() or even contentEquals().
Check this discussion to learn more about comparing strings.
here is my code
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] data = new int[10];
int count = 0;
do {
System.out.print("Enter a number or ctrl + z when you are done: ");
data[count] = input.nextInt();
}
while (input.hasNextDouble());
}
}
output
Enter a number or ctrl + z when you are done: 2
4
Enter a number or ctrl + z when you are done: 6
Enter a number or ctrl + z when you are done: 8
My question is i don't know why the code jumps the System.out.print("Enter a number or ctrl + z when you are done: "); after do { when entering the loop the second time. This can be seen in second line of the output. Please what are my doing wrong?
I have searched for cases where my question might have already been answered but was only able to find solutions relating to code skipping nextLine()
The reason is first time do block is executed and then check for condition in while.
About hasNextDouble() in orcale doc:
Returns true if the next token in this scanner's input can be
interpreted as a double value using the nextDouble() method. The
scanner does not advance past any input.
As a solution you can change the condition like below:
do {
System.out.print("Enter a number or ctrl + z when you are done: ");
data[count] = input.nextInt();
count++;
}
while (count < 10);
Also:
If you are using input.nextInt();, better to check using hasNextInt().
ah your while loop is waiting to see if input hasNextDouble()
how can it know until your user has entered the next double or hit ctrl-z?
you'll have to do something Ugly like
System.out.print("Enter a number or ctrl + z when you are done: ");
do {
data[count++] = input.nextInt();
System.out.print("Enter a number or ctrl + z when you are done: ");
}
while (input.hasNextDouble());
note the count++ above as well i think it fixes another bug.
This happens because the first call to input.hasNextDouble() waits for a number to be entered before proceeding.
So the message in the second iteration of the loop won't appear until input.hasNextDouble() at the end of the first iteration of the loop has run - which of course fetches the second number.
You need to print the message before you call either hasNextDouble or hasNextInt.
I wasn't sure how to give a title for this problem, but basically this is part of my blackjack program. Also, since I did not know how to title this, I wasn't sure how to look it up, which is why I am asking here. So I am saying that when the user enters either 1 or 11 for the ace value, if they enter something other than 1 or 11, it asks the user again to put in 1 or 11. In my program everything works fine except when the user enters 1, then it just asks the question again. The program should only asks again if the input is not equal to 1 or 11. Here is my code as I made sure it always gives an ace for testing purposes:
String card1="A";
int total=0;
Scanner input_var=new Scanner(System.in);
if (card1=="A"){
System.out.println("Do you want a 1 or 11 for the Ace?: ");
int player_ace_selection=input_var.nextInt();
if ((1|11)!=(player_ace_selection)){
System.out.println("Please enter a 1 or 11: ");
int new_selection=input_var.nextInt();
total=total + new_selection;
}
else {
total=total + player_ace_selection;
}
}
System.out.println(total);
Thanks in advance.
The expression (1|11) uses binary OR, which produces 11:
11 = 01001
1 = 00001
(11|1) = 01001
Hence, the comparison is the same as 11!=player_ace_selection
You should change the code to use logical OR, i.e.
if (1!=player_ace_selection && 11!=player_ace_selection) {
...
}
In addition, you need to fix card1 == "A" comparison for card1.equals("A")
Instead of an If statement, try a while loop. A while loop ensures that your program waits for your user to pick the right answer. You also made a mistake with your logical operations. The correct way to use "OR" in this context is to compare your user input to both '1' and '11' separately using '||'.
String card1="A";
int total=0;
Scanner input_var=new Scanner(System.in);
if (card1.equals("A")){
System.out.println("Do you want a 1 or 11 for the Ace?: ");
int player_ace_selection=input_var.nextInt();
while(player_ace_selection != 1 && player_ace_selection != 11){
System.out.println("Do you want a 1 or 11 for the Ace?: ");
player_ace_selection = input_var.nextInt();
}
total += player_ace_selection;
}
System.out.println(total);
There are some problems in your code, please consider this example and compare it with yours.
String card1="A";
int total=0;
Scanner input_var=new Scanner(System.in);
if (card1.equals("A")){ // compare the content not the reference (==)
System.out.println("Do you want a 1 or 11 for the Ace?: ");
try{ // wrap with try-catch block
int player_ace_selection = Integer.parseInt(input_var.nextLine()); //read the entire line and parse the input
if ((player_ace_selection!=1)&&(player_ace_selection!=11)){
System.out.println("Please enter a 1 or 11: ");
try{
int new_selection = Integer.parseInt(input_var.nextLine()); //again read the entire line and parse the input
total=total + new_selection;
}catch(NumberFormatException e){
// do something to catch the error
}
}
else {
total=total + player_ace_selection;
}
}catch(NumberFormatException e){
// do something to catch the error
}
System.out.println(total);
}
Trying to design a simple lottery program. Everything works except checking if the numbers entered are between 1 to 59.
Exercise says the numbers must be stored in a String variable.
so
if(num<0 || num>59) //wont work for me
Tried making another variable
int numConverted = Integer.parseInt(num)
We haven't covered converting String to int in class though so I don't think this is what expected. Got confused trying that way anyway so probably this is wrong.
Here is the code I have currently.
{
Scanner scan = new Scanner(System.in);
String num=""; //num variable is empty untill user inputs numbers
for(int i =0; i<6; i++)
{
System.out.println("Enter your number between 1-59");
num = num +" "+ scan.nextLine();
}
System.out.println("Ticket printed £2. Your numbers are " + num);
}
In your posted code it's obvious that you want the User to supply 6 specific numerical values. These values are appended to the String variable named num (space delimited). You need to obviously do a few things here:
1) Make sure the value supplied by the user is indeed a numerical value;
2) Make sure the numerical values supplied fall within the minimum and maximum scope of the lottery itself (which you have stated is: 1 to 59);
3) Make sure the number entered by the User hasn't been supplied already.
You've been tasked to store the entered values into a String data type variable and that is all fine but at some point you want to carry out value comparisons to make sure that all the entered values actually play within the limits of the lottery.
When the User completes his/her entries, you end up with a space delimited string held in the num string variable. You now need to make sure that these values entered are indeed....numbers from 1 to 59 and none contain alpha characters.
In my opinion (and this is only because you need to store entered values into a String variable), it's best to use your String variable to gather User input, then test the input to make sure it is indeed a string representation of an actual integer number. Once this is established then we test to make sure if falls within the value min/max limits (1-59). Now we need to test to make sure the number entered hasn't already been entered before for this ticket.
Of course with each test described above, if one fails then the User should be prompted to re-enter a proper value. You can do this by utilizing a while loop. Plenty examples of this in StackOverflow but here's a quick example:
Scanner scan = new Scanner(System.in);
String ticketNumbers = "";
for(int i = 0; i < 6; i++) {
Boolean isOK = false;
while (!isOK) {
System.out.println("\nPlease enter your desired 6 ticket numbers:\n"
+ "(from 1 to 59 only)");
String num = scan.nextLine();
//Is the string entered an actual integer number?
//We use the String.matches() method for this with
//a regular expression.
if(!num.matches("\\d+")) {
System.out.println("You must supply a numerical value! "
+ "Try Again...");
continue;
}
if (ticketNumbers.contains(num + " ")) {
System.out.println("The number you supplied has already been chosen!"
+ " Try Again...");
continue;
}
if (Integer.parseInt(num) >= 1 && Integer.parseInt(num) <= 59) {
ticketNumbers+= num + " ";
isOK = true;
}
else {
System.out.println("The number you supply must be from "
+ "1 to 59! Try Again...");
}
}
}
System.out.println("Ticket printed £2. Your numbers are " + ticketNumbers);
How about -
if(Integer.parseInt(num) < 0 || Integer.parseInt(num) > 59)
This should work, place it after the input.
If it works, please mark this as correct, I need the rep!!!
Easy way would be add available numbers (suppose it wont grow more than 60. You can use a loop to add to this as well)
String numbers[] = {"1","2","3", "..."};
Then inside the loop
Arrays.asList(numbers).contains(num);
You can remove prefixing zero in order avoid conflicts with values like '02'
Here everything is String related.
If you don't want to explicitly convert to int, you could use a regular expression.
if (num.matches("[1-5]?[0-9]")) {
...
This checks whether the String consists of (1) maybe a digit from 1 to 5, followed by (2) definitely a digit from 0 to 9. That'll match any number in the range 0-59.
If you've got a whole series of numbers separated by spaces, you could expand this to cover a whole series like this.
if (num.matches("([1-5]?[0-9]\\s+)*[1-5]?[0-9]")) {
This matches any number of repetitions (including zero) of "a number followed by spaces", followed by a single repetition without a space. The "\\s" means "any whitespace character", the "+" after it means "one or more of what precedes", and the "*" means "zero more of what precedes" - which in this case is the term in parentheses.
Oh I see what you are trying to do
This is what you want
Scanner scan = new Scanner(System.in);
String allNums = "";
for(int i =0; i<6; i++)
{
System.out.println("Enter your number between 1-59");
int num = scan.nextInt();//Take the number in as an int
if(num >0 && num < 59)//Check if it is in range
{
allNums += num + " ";//if it is add it to a string
}
else
{
System.out.println("Number not in range");
i--;//go back one iteration if its not in range
}
}
System.out.println("Ticket printed £2. Your numbers are " + allNums);
So this is my code i dont know what to add if i want to display invalid message for the non numeric inputs please help ty
import java.util.Scanner;
public class Date
{
public static void main (String args [])
{
int x;
Scanner in = new Scanner (System.in);
System.out.print("Enter a date ");
x = in.nextInt();
while (x < 1520 || x > 3999)
{
System.out.println ("Invalid Gregorian Calendar date.");
System.out.print ("Please Input a valid Gregorian Calendar date: ");
x = in.nextInt();
}
System.out.println("Good");
Use a try catch block, and put x = in.nextInt(); inside it
I've changed your code a bit. I think this is what you were aiming for.
I'm not that good in explaining but I try to tell what I did.
First of all I got rid of your in.nextInt() since this is very restrictive. It does only accept an integer and will throw an exception if you type something else in. Normally this would be OK, but since you want the user to be able to correct the input, this will cause more troubles than it would solve.
I then put your code into an infinite loop while(true) which assures, you do not have to restart your application again once you've typed in a wrong value.
What is going on within the loop is quite simple. The console prints out what you want the user to do and reads the consoles input as a String, so you don't have to face any exceptions in the first place.
I then try to parse the given String into an integer value. I added trim() to kill leading spaces as well as trailing, so I won't have to deal with users being confused by typing in numbers with a space since they don't directly see whats wrong when getting their "not an integer" error. This would be thrown, if the input contains spaces.
Now I check whether or not the given integer-value fits your specifiation. I don't need a loop here, so I changed it to be a simple if-statement.
If the value is wrong (or lets say the if (x < 1520 || x > 3999) returns true) I'm going to print out your error message. Since we already passed casting the String input into the integer and we do not reach the else-branch we now return back to the beginning of our loop with printing out the request again before waiting for a new input to be made.
Now, as soon as the user typed in another value, e.g. 2011 (which is valid based on your specification) we will now reach the else-branch which prints the "Good" and leaves the loop by calling break. And since there is nothing left to do for the application it will stop running. If you want the user to be able to type in new values in the positive case, you simply have to remove the break-statement.
If the user types in a value which is not an integer, the cast will fail and throw a NumberFormatException. We catch this exception by surrounding the cast with the try-catch-block and print out the integer-error once we've reached the catch-block.
Then the application reacts the same way like if you typed in a wrong number and we will return to the beginning of the loop again.
The reason for putting a try-block around the Scanner is to handle closing.
import java.util.Scanner;
public class Date {
public static void main(String args[]) {
String input = "";
int x = 0;
try (Scanner in = new Scanner(System.in);) {
while (true) {
System.out.print("Please Input a valid Gregorian Calendar date: ");
input = in.nextLine();
try {
x = Integer.parseInt(input.trim());
if (x < 1520 || x > 3999) {
System.out.println("Invalid Gregorian Calendar date.");
}
else {
System.out.println("Good");
break;
}
} catch (NumberFormatException e) {
System.out.println("Given value \"" + input.trim() + "\" is not an integer.");
}
}
}
}
}
The Scanner class has a method for this
Scanner in = new Scanner(System.in);
int x;
if(in.hasNextInt()){
x = in.nextInt();
System.out.println("Valid number");
}else{
System.out.println("Not a number");
}
To keep prompting until a valid number is entered
int x;
System.out.println("Enter a number: ");
while(!in.hasNextInt()){
System.out.println("Invalid number, try again: ");
key.nextLine(); // Flush out invalid number
}
x = key.nextInt();