import java.util.*;
public class ConvertBinaryToInteger{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
final String EXIT="exit";
System.out.println("This program will convert a binary into an integer.");
System.out.println("Enter "+EXIT+" to exit program. Press enter to continue.");
String word=scan.nextLine();
while(!word.equals(EXIT)){
while(!word.equals(EXIT)){
boolean valid = false;
while (!valid) {
System.out.println("Enter a binary number: ");
String binary = scan.next();
boolean isBinary = true;//first convert the 'binary' string into a char array and check for each char whether it is zero or one
char[] bits = binary.toCharArray();
for(int j=0; j<bits.length; j++){//read the inputs
if( (bits[j] != '0') && (bits[j] != '1') ){//check the inputs
isBinary = false;
break;
}
}
if(!isBinary){//not binary
System.out.println("This is not a binary number.");
System.out.println("Please enter a number that contains only 1's and 0's.");
System.out.println("Enter "+EXIT+" to exit program. Press enter to continue.");
word=scan.nextLine();
}
else{//binary
int integer = 0;
int temp;
int i = 0;
temp = Integer.parseInt(binary);
while (temp != 0){
int r = temp % 10;
double value = r * Math.pow(2, i);
i++;
integer = (int) (integer + value);
temp /= 10;
}
System.out.println("Integer of " + binary + " is " + integer+".");
System.out.println("Enter "+EXIT+" to exit program. Press enter to continue.");
word=scan.nextLine();
}
System.out.println();
scan = new Scanner(System.in);
}
}
}System.out.println("Program ended.");
}
}
cannot exit after entered a correct binary. Please help me to change the program...
if you didn't exit in the first place, you cannot end the program..
while (!valid) {
valid is never updated. If they want to exit, set valid to true as well as updating the value of word.
As pointed out by #AnthonyGrist, removing the while(!valid) loop altogether will also fix this issue.
Check this code
it is up and running
PS: removing the !valid condition will also not lead to termination of the program on entering exit. i tried it.
The issue is you are displaying the message and also writing scan.nextline() immediately, which accepts a blank, this is neither = to exit and also valid whether set to true or not, will always be initialized to false, as it enters the word.equals(.. condition.
Related
must create a java application that will determine and display sum of numbers as entered by the user.The summation must take place so long the user wants to.when program ends the summation must be displayed as follows
e.g say the user enters 3 numbers
10 + 12+ 3=25
and you must use a while loop
Here's a function to do just that. Just call the function whenever you need.
Ex: System.out.println(parseSum("10 + 12+ 3")) → 25
public static int parseSum(String input) {
// Removes spaces
input = input.replace(" ", "");
int total = 0;
String num = "";
int letter = 0;
// Loop through each letter of input
while (letter < input.length()) {
// Checks if letter is a number
if (input.substring(letter, letter+1).matches(".*[0-9].*")) {
// Adds that character to String
num += input.charAt(letter);
} else {
// If the character is not a number, it turns the String to an integer and adds it to the total
total += Integer.valueOf(num);
num = "";
}
letter++;
}
total += Integer.valueOf(num);
return total;
}
The while loop is essentially a for loop though. Is there a specific reason why you needed it to be a while loop?
There is a lot of ways to achieve this. Here an example of code that could be improve (for example by catching an InputMismatchException if the user doesn't enter a number).
Please for the next time, post what you have tried and where you stuck on.
public static void main (String[] args) {
boolean playAgain = true;
while(playAgain) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the first number : ");
int nb1 = sc.nextInt();
System.out.println("Ok! I got it! Please enter the second number : ");
int nb2 = sc.nextInt();
System.out.println("Great! Please enter the third and last number : ");
int nb3 = sc.nextInt();
int sum = nb1+nb2+nb3;
System.out.println("result==>"+nb1+"+"+nb2+"+"+nb3+"="+sum);
boolean validResponse = false;
while(!validResponse) {
System.out.println("Do you want to continue ? y/n");
String response = sc.next();
if(response.equals("n")) {
System.out.println("Thank you! see you next time :)");
playAgain = false;
validResponse = true;
} else if(response.equals("y")) {
playAgain = true;
validResponse = true;
} else {
System.out.println("Sorry, I didn't get it!");
}
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("\nThe sum of the numbers is: " + getSumOfInput());
}
public static int getSumOfInput () {
int counter = 0;
int sumOfNums = 0;
Scanner userInput = new Scanner(System.in);
while(counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
boolean checkValidity = userInput.hasNextInt();
if(checkValidity) {
int userNum = userInput.nextInt();
userInput.nextLine();
System.out.println("Number " + userNum + " added to the total sum.");
sumOfNums += userNum;
counter++;
} else {
System.out.println("Invalid input. Please, enter a number.");
}
}
userInput.close();
return sumOfNums;
}
}
Hello everybody!
I just started java and I learned about control flow and now I moved on to user input, so I don't know much. The problem is this code. Works just fine if you enter valid input as I tested, nothing to get worried about. The problem is that I want to check for wrong input from user, for example when they enter a string like "asdew". I want to display the error from else statement and to move on back to asking the user for another input, but after such an input the program will enter in an infinite loop displaying "Enter the number X: Invalid input. Please, enter a number.".
Can you tell me what's wrong? Please, mind the fact that I have few notions when it comes to what java can offer, so your range of solutions it's a little bit limited.
Call userInput.nextLine(); just after while:
...
while(counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
userInput.nextLine();
...
The issue is, that once you enter intput, which can not be interpreted as an int, userInput.hasNextInt() will return false (as expected). But this call will not clear the input, so for every loop iteration the condition doesn't change. So you get an infinite loop.
From Scanner#hasNextInt():
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
The fix is to clear the input if you came across invalid input. For example:
} else {
System.out.println("Invalid input. Please, enter a number.");
userInput.nextLine();
}
Another approach you could take, which requires less input reads from the scanner, is to always take the next line regardless and then handle the incorrect input while parsing.
public static int getSumOfInput() {
int counter = 0;
int sumOfNums = 0;
Scanner userInput = new Scanner(System.in);
while (counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
String input = userInput.nextLine();
try {
int convertedInput = Integer.parseInt(input);
System.out.println("Number " + convertedInput + " added to the total sum.");
sumOfNums += convertedInput;
counter++;
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please, enter a number.");
}
}
return sumOfNums;
}
New to Java and learning how to use While loops and random generator. This prints a multiplication question. Every time the user answers a question wrong, it should print the same question. Instead, it exits the program. What should I do?
while (true) {
Random multiply = new Random();
int num1 = multiply.nextInt(15);
int num2 = multiply.nextInt(15);
int output = num1 * num2;
System.out.println("What is the answer to " + num1 + " * " + num2);
Scanner input = new Scanner(System.in);
int answer = input.nextInt();
if (answer == output) {
if (answer != -1)
System.out.println("Very good!");
} else {
System.out.println("That is incorrect, please try again.");
}
}
If you want to repeat the same question when the user gets the answer wrong, you should use another while inside your main loop.
This inner loop continues to ask as long as you give a wrong answer.
I also replaced nextInt with nextLine, which reads in a whole line of text. This consumes the "Enter" key and is a safer approach at reading from the console. Since the result is now a String you need to use Integer.parseInt to convert it to an int. This throws an exception if you enter anything but a whole number so I wrapped it into a try-catch block.
If you want, you can add an additional check for validating user input. So in case the user wants to stop playing they only need to input "exit" and the whole outer loop will exit.
boolean running = true; // This flag tracks if the program should be running.
while (running) {
Random multiply = new Random();
int num1 = multiply.nextInt(15);
int num2 = multiply.nextInt(15);
int output = num1 * num2;
boolean isCorrect = false; // This flag tracks, if the answer is correct
while (!isCorrect) {
System.out.println("What is the answer to " + num1 + " * " + num2);
Scanner input = new Scanner(System.in);
try {
String userInput = input.nextLine(); // Better use nextLine to consume the "Enter" key.
// If the user wants to stop
if (userInput.equals("exit")) {
running = false; // Don't run program any more
break;
}
int answer = Integer.parseInt(userInput);
if (answer == output) {
if (answer != -1) {
System.out.println("Very good!");
isCorrect = true; // Set the flag to true, to break out of the inner loop
}
} else {
System.out.println("That is incorrect, please try again.");
}
}
catch(NumberFormatException e) {
System.out.println("Please enter only whole numbers");
}
}
}
Avoid while true. Declare a variable to true, pass the variable to the condición loop and set it to false when the answer is incorrect. You can use break too, but is easier to read the code when you use a exit condition in the while. Also read more about loops https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
I'm using a while statement in my code, where, inside the while statement, the user inputs a number. To stop the program from looping, the user must input the word "stop". However, once I enter in a number, the output skips to another line without printing the statement I want it to print, and I have to enter my desired input again for the program to start looping.
The only time this problem DOES NOT occur is when the user inputs "stop" FIRST, then the code works fine.
This is to find the max, min, and mean of any amount of user-inputted numbers. I've tried changing the order of the else/if statements and the parameters for the said else/if statements, but nothing seems to work.
boolean stopped = false;
int numberAmount = 0;
int invalidAmount = 0;
double max = Integer.MIN_VALUE;
double min = Integer.MAX_VALUE;
double mean = 0;
while(stopped == false)
{
System.out.print("Enter a number (type "+"\""+"stop"+"\""+" to stop): ");
String originalInput = userInput.nextLine();
if(originalInput.equals("stop"))
{
stopped = true;
invalidAmount ++;
System.out.println(numberAmount+" numbers were entered with "+invalidAmount+" invalid inputs.");
}
else if(userInput.hasNextDouble())
{
double currentValue = Double.parseDouble(originalInput);
max = Math.max(max, currentValue);
min = Math.min(min, currentValue);
mean = currentValue;
numberAmount ++;
}
else if(originalInput.equals("stop") == false)
{
System.out.println("Not a number...");
invalidAmount ++;
}
}
System.out.println("The maximum is "+max+".");
System.out.println("The minimum is "+min+".");
System.out.println("The mean is "+(mean / numberAmount)+".");
userInput.close();
}
}
For example, I expect the output after inputting 7 to be
"Enter a number (type "stop" to stop):" on the next line(since the program loops to keep prompting for number input), where the user could then keep inputting numbers as they like.
Instead, the actual output is a blank line under the original prompt for user input, where the user must input their desired input AGAIN for the program to start looping.
You didn't specify in your code example what userInput is, but from the usage it looks to be an instance of Scanner. If you have a Scanner declared and then call hasNextDouble(), you will get a boolean result which fits with your usage – you have that as the condition in your if statement.
Scanner userInput = new Scanner(System.in);
boolean b = userInput.hasNextDouble();
What's missing from the picture is how hasNextDouble() works. Looking at the Javadoc for Scanner:
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.
In order to answer true/false for whether the next input is a double or not, the scanner has to wait for input from the user before it can proceed.
All of this to say: your code looks like it's behaving normally. If you don't want to wait for user input, you need to write your code to reflect that.
I think you should invert the logic of the code, assuming you are using the Scanner, try something like this:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
boolean stopped = false;
int numberAmount = 0;
int invalidAmount = 0;
double max = Integer.MIN_VALUE;
double min = Integer.MAX_VALUE;
double mean = 0;
while (stopped == false) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter a number (type " + "\"" + "stop" + "\"" + " to stop): ");
if (userInput.hasNextDouble()) {
double currentValue = userInput.nextDouble();
max = Math.max(max, currentValue);
min = Math.min(min, currentValue);
mean = currentValue;
numberAmount++;
} else {
String originalInput = userInput.nextLine();
if (originalInput.equals("stop")) {
stopped = true;
invalidAmount++;
System.out.println(numberAmount + " numbers were entered with " + invalidAmount + " invalid inputs.");
} else {
System.out.println("Not a number...");
invalidAmount++;
}
}
}
System.out.println("The maximum is " + max + ".");
System.out.println("The minimum is " + min + ".");
System.out.println("The mean is " + (mean / numberAmount) + ".");
// userInput.close();
}
}
Basically you are checking first the input type, and only after you are collecting the value from the console. Doing it the way you have right now, you will always ask for the second input.
I don't really know the API, but I expect hasNextDouble reads another line. Check if originalInput is a double, don't read another line.
I need to user to enter an int between 1 and 301.
I have this simple loop here to check for user input.
I just want a single number from the user, and if the user enters anything other than an int between 1 and 301, I want to display the print line and prompt the users to try again until they enter a valid input.
while (!sc.hasNextInt()) {
System.out.print("Invalid Input. Please enter a valid number between 1 and 301: ");
sc.next();
}
int numToCheck = sc.nextInt();
// do stuff with numToCheck
This checks that the input is an int, but I can't seem to find a way to give the int input a bound. I tried to assign the user input to a variable and then check the conditions input < 1 or input > 301, but I get InputMismatchException if user enters a letter. How should I store the user input? (I want to store it as an int to check the conditions, but can't do that since I don't know what the user will enter).
Perhaps there is a better design to accomplish all this. Those are welcomed too.
Thanks in advance.
You're not saving the value of the of the input. So your program is waiting on the user to enter a number each time it see "sc.nextInt()" Assign the input to a variable, and then check the condition.
EDIT: okay, I'll go the extra mile for you. See if this works.
***Accounted for the case where the user might enter a character instead of a number.
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int input;
while (true){
if (sc.hasNextInt()){
input = sc.nextInt(); // Assign the next integer to a variable
if (input <= 301 && input >= 1){ // Check if integer meets condition
break; // Condition met, break out of loop
}
}else{
sc.next();
}
System.out.println("Invalid Input. Please enter a valid number between 1 and 301: ");
}
}
}
I ran this code, to see if it would show a better performance than yours.
Scanner sc = new Scanner(System.in);
boolean valid = true;
do {
if (!valid) {
System.out.print("Invalid Input. ");
}
System.out.print("Please enter a valid number between 1 and 301: ");
String input = sc.next();
try {
int value = Integer.parseInt(input);
valid = (value >= 1 && value <= 301);
} catch (NumberFormatException nfex) {
valid = false;
}
} while (!valid);
When the conversion to integer fails, the JVM hangs a little. I believe your problem has more to do with the try / catch mecanism that Scanner performs under the hood, than with design.
Assuming you want only 1 input from the user, try following simple code, which takes input from the user until user enters a valid input.
Scanner in = new Scanner(System.in);
int flag = 0,x=0;
while(flag == 0){
x = in.nextInt();
if(x<1 || x>301){
flag = 0;
System.out.println("Invalid Input.");
}
else{
flag = 1;
}
}
And if you want user to input more than 1 inputs (i.e 3 here), than set a counter that increases with every valid input of the user, as following:
Scanner in = new Scanner(System.in);
int flag = 0,x=0,count = 1;
while(flag == 0){
x = in.nextInt();
if(x<1 || x>301){
flag = 0;
System.out.println("Invalid Input.");
}
else{
//executes when input is valid
if(count == 3){
flag = 1;
}
count++;
}
}
Edit:
If you also want to check whether the input is Integer or not, than you have to add one extra condition in above code. And as you said you want only one input from user rather than 3, you have to change exit condition. Change code as following:
Scanner in = new Scanner(System.in);
int flag = 0,count = 1,x=0,flag1 = 0;
String y;
while(flag == 0){
y = in.next();
flag1 = 0;
try{
x = Integer.parseInt(y);
}
catch(NumberFormatException e){
flag1 = 1;
System.out.println("Invalid Input.");
}
if((x<1 || x>301)&&flag1 == 0){
flag = 0;
System.out.println("Invalid Input.");
}
else if(flag1 == 0){
//executes when input is valid
if(count == 1){ // put count == 3 if you want 3 inputs from user.
flag = 1;
}
count++;
}
}
Here we are taking the input as a String and than converting the String into the Integer by using Integer.parseInt(). If the String is not Integer, than it will throw the exception and we will continue the loop till the valid input is entered by the user.
Use DO WHILE for result
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
OK ?