I have tried various techniques to check the values of user input in this method. The user should only be able to enter a '1' or a '0'. If any other input is used there should be an error message and the program exits. Any ideas? I got it to work for the first digit but not the second through the tenth.
System.out.println("Enter a ten digit binary number. Press 'Enter' after each digit. Only use one or zero. :");
binary[0] = keyboard.nextInt();
for (index = 1; index < 10; index++)
binary[index] = keyboard.nextInt();// fill array with 10 binary
// digits from user. User
// must press 'Enter' after
// each digit.
Try this:
Scanner scanner = new Scanner(System.in);
if (scanner.hasNext())
{
final String input = scanner.next();
try
{
int num = Integer.parseInt(input, 2);
}
catch (NumberFormatException error)
{
System.out.println(input + " is not a binary number.");
//OR You may exit here, if you don't want to continue
}
}
Try this code part :
import java.util.Scanner;
public class InputTest
{
public static void main(String... args) throws Exception
{
Scanner scan = new Scanner(System.in);
int[] binary = new int[10];
for (int index = 0; index < 10; index++)
{
int number = scan.nextInt();
if (number == 0 || number == 1)
{
binary[index] = number;
System.out.println("Index : " + index);
}
else
System.exit(0);
}
}
}
Related
I'm new to java, got an assignment about converting binary to decimal.
here's my code
public static void main(String[] args) {
int num, decimal = 0, i=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter a Binary Number");
String binary = in.nextLine();
num = Integer.parseInt(binary);
while(num != 0){
decimal += (num%10)*Math.pow(2, i);
num = num /10;
i++;
}
System.out.println("Decimal Number : "+ decimal);
}
It's already done but the teacher request "Use scanner class inside a while loop for users to enter the binary number one by one. A “-1” would stop the loop."
Does anyone know how to change my code?
Use another while loop and keep iterating until the user inputs -1.If user inputs -1 use break to come out of while loop
public static void main(String[] args) {
int num, decimal = 0, i=0;
Scanner in = new Scanner(System.in);
while(true) {
System.out.println("Enter a Binary Number");
String binary = in.nextLine();
num = Integer.parseInt(binary);
if(num ==-1){
break;
}
while(num != 0){
decimal += (num%10)*Math.pow(2, i);
num = num /10;
i++;
}
System.out.println("Decimal Number : "+ decimal);
}
}
Your task consists of two parts: iterated input-check-process cycle and the process itself.
The former is simply solved with a loop:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
// input
System.out.println("Enter a Binary Number");
String inputStr = in.nextLine();
// check
if (inputStr.equals("-1")) {
break;
}
// process
// TODO
}
}
This repeats asking for input data, reading it, testing for a special 'terminate' value and exits eventually if one is found.
The second part can be solved as follows: scan input digits one by one; each new digit found becomes a new least-significant bit of a number being constructed, while all preceding digits become one position more significant than they were.
That means, whenever you find a new digit, the number gets doubled and the value of a new digit gets added:
// process
int result = 0;
int position;
for (position = 0; position < inputStr.length(); ++position) {
char digit = inputStr.charAt(position);
int val = Character.digit(digit, 2);
result = 2*result + val;
}
System.out.println("Decimal Number : "+ result);
Together they make:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
// input
System.out.println("Enter a Binary Number");
String inputStr = in.nextLine();
// check
if (inputStr.equals("-1")) {
break;
}
// process
int result = 0;
int position;
for (position = 0; position < inputStr.length(); ++position) {
char digit = inputStr.charAt(position);
int val = Character.digit(digit, 2);
result = 2*result + val;
}
System.out.println("Decimal Number : "+ result);
}
}
Of course, for a real-life program we should also validate input, ie. test if it consists of digits 0 and 1 only, whether it's not empty or not too long (so that the result of conversion fits the values range of type int).
I'm trying to ask the user for two two-digit numbers and then perform a length check and a type check on both of the numbers, then I want to output the sum of the numbers. Here's what I have so far:
package codething;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner number = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a two digit number (10-99) ");
int n = number.nextInt();
if(number.hasNextInt()) {
} else {
System.out.println("Error");
}
int m;
int length = String.valueOf(number).length();
if (length == 2) {
} else {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
Scanner number1 = new Scanner(System.in);
System.out.println("Enter another two digit number (10-99) ");
m = number.nextInt();
if(number1.hasNextInt()) {
m = number1.nextInt();
} else {
System.out.println("Error");
}
int sum = n + m;
System.out.println(sum);
}
}
At the moment my program won't even ask me for my second input. Not sure what to do :/
So several things:
-Don't construct more than one Scanner objects to read from System.in. It just causes problems.
-You're using String.valueOf() to convert an int to a String. It is better to simply check to make sure it is between 10 and 99.
-You check to make sure that the Scanner has a next int after you call nextInt which won't help. You need to make sure that there is a next int.
-A lot of your if statements have an empty if block and then you do something in the else. You can just do the opposite in the if and omit the else (Instead of if(length ==2) {} you can do if(length != 2) {//code}
Scanner number = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a two digit number (10-99) ");
int n = 0;
if(number.hasNextInt()) {
n = number.nextInt();
} else {
number.next(); //Clear bad input
System.out.println("Invalid");
}
int m = 0;
if ( n< 10 || n > 99) {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
System.out.println("Enter another two digit number (10-99) ");
if(number.hasNextInt()) {
m = number.nextInt();
} else {
number.next();
System.out.println("Invalid");
}
if (n< 10 || n > 99) {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
int sum = n + m;
System.out.println(sum);
How to check in this code that the entered input is integer or not if not then ignore the non-integer values and display the rest numbers.
I have done the full coding but for checking the input is integer or not and then printing the value. How should I do it?
import java.util.Scanner;
class ques2
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int i,j;
System.out.print("how many number you want to enter= ");
i=sc.nextInt();
int input[]=new int[i];
System.out.println("Numbers should be great then 3");
for(j=0;j<i;j++)
{
input[j]=sc.nextInt();
}
System.out.println("Number entered are:");
for(j=0;j < i;j++)
{
System.out.println(input[j]);
}
System.out.println("Odd numbers are:");
for(j=0;j < i;j++)
{
if(input[j] % 2 != 0)
{
System.out.println(input[j]);
}
}
System.out.println("Palindrome numbers are:");
for(j=0;j < i;j++)
{
int rev=0,n,num;
n=input[j];
while(input[j] > 0)
{
num=input[j] % 10;
rev=num+(rev*10);
input[j]=input[j]/10;
}
if(n == rev)
{
System.out.println(n);
}
}
}
}
You could take a helper function:
public static boolean checkMe(String s) {
boolean amIValid = false;
try {
Integer.parseInt(s);
// s is a valid integer!
amIValid = true;
} catch (NumberFormatException e) {
//not an integer but you could continue with the rest numbers
}
return invalid;
}
You can check it by comparing the ASCII value whether it lies between 91 to 100.
If yes then it will be an Integer.
You can try to use String in lieu of int. Then, you can go ahead with again int using Integer.parseInt(x) because it's already been verified as being valid integer after do-while
String num;
String regex = "[0-9]+"; // to check the string only is made up of digits
Scanner input = new Scanner(System.in);
do {
System.out.println("Please input an integer");
num = input.next();
} while (!num.matches(regex));
int validNumber = Integer.parseInt(num);
/* .
.
. *\
You're already using sc.nextIn() which internally perform a regex-check as in #snr's post and a Integer.parseInt as in charly1212's post.
The only thing you should add is wrap it in a
try {
int i = sc.nextInt();
} catch(InputMismatchException e) {
//skip or repeat?
}
To deal with all cases, where the input is not an int (which includes values > Integer.MAX_VALUE and < Integer.MIN_VALUE)
The solution could look like this method, encapsulating all the input reading
private static int[] readNumbers() {
Scanner sc = new Scanner(System.in);
int i = -1;
while(i < 0){
try {
System.out.print("how many number you want to enter? ");
i=sc.nextInt();
} catch (InputMismatchException e){
System.out.println(sc.next() + " is not a number, try again");
}
}
List<Integer> numbers = new ArrayList<>();
System.out.println("Numbers should be greater then 3");
for(int j = 0; j < i; j++){
try {
numbers.add(sc.nextInt());
} catch (InputMismatchException e){
System.out.println("Skipping input " + sc.next());
}
}
return numbers.stream().mapToInt(Integer::intValue).toArray();
}
...
int input[] = readNumbers();
Please not, that the exception blocks invoke sc.next() to read the current line (which is not integer) and proceed with the next line (the new input), otherwise the scanner would not proceed its position.
I have a HOMEWORK assignment that involves users inputs.
I want to ask the user for three integer inputs in the range 1-7 and store them in an array.
What I have so far seems to validate properly if all inputs are over 7 and rules out strings etc inputs and but still allows for a single input to be over 7.
Any help is appreciated.
Scanner in = new Scanner(System.in);
boolean valid = false;
int[] inputRange = new int[3];
while(!valid)
{
System.out.println("enter three numbers: ");
if(in.hasNextInt())
{
for(int i = 0; i< inputRange.length; i++)
{
inputRange[i] = in.nextInt();
if(inputRange[i] >= 1 && inputRange[i] <= 9){
valid = true;
}
}
}else{
in.next();
}
}
Your logic is fine, but you need to restart valid to false again each time user is going to enter a new digit.
Here's how you can validate user input to be between 1-9 with a do-while using your same logic just a little bit different.
Also next time be sure to post a valid MCVE and not just "snippets" (it should include a main method and imports)
import java.util.Scanner;
public class ValidationOfNumbers {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean valid = false;
int[] inputRange = new int[3];
int counter = 0;
int number = 0;
System.out.println("Enter 3 digits between 1-9"); //Ask for digits, numbers can have multiple digits, while digits are numbers from 0-9
for (int i = 0; i < inputRange.length; i++) {
valid = false; //Restart "valid" variable for each new user input
do {
number = in.nextInt();
if (number >= 1 && number <= 9) {
valid = true; //If valid, it will exit do-while
} else {
System.out.println("Enter a valid digit between 1-9");
}
} while (!valid);
inputRange[i] = number; //We know it's valid because it went out of do-while, so we can now store it in the array
}
for (int i = 0; i < inputRange.length; i++) {
System.out.println(inputRange[i]);
}
}
}
Here is the code
Scanner in = new Scanner(System.in);
int count = 0;
int data[] = new int[3];
while(count < 3) {
if(in.hasNextInt()) {
int val = in.nextInt();
if(val>=1 && val <=7) {
data[count] = val;
count++;
}
}
else {
in.next();
}
}
I want the user to enter integers into an array. I have this loop I wrote which has a try and catch in it, in case a user inserts a non integer. There's a boolean variable which keeps the loop going if is true. This way the user will be prompted and prompted again.
Except, when I run it, it gets stuck in a loop where it repeats "Please enter # " and "An Integer is required" without letting the user input a new number. I reset that number if an exception is caught. I don't understand.
import java.util.*;
public class herp
{
//The main accesses the methods and uses them.
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Hello and welcome!\n");
System.out.print("This program stores values into an array"+" and prints them.\n");
System.out.println("Please enter how many numbers would like to store:\n");
int arraysize = scan.nextInt();
int[] mainarray = new int[arraysize+1];
int checkint = 0;
boolean notint = true;
int prompt = 1;
while (prompt < mainarray.length)
{
// Not into will turn true and keep the loop going if the user puts in a
// non integer. But why is it not asking the user to put it a new checkint?
while(notint)
{
try
{
notint = false;
System.out.println("Please enter #"+ prompt);
checkint = scan.nextInt();
}
catch(Exception ex)
{
System.out.println("An integer is required." +
"\n Input an integer please");
notint = true;
checkint = 1;
//See, here it returns true and checkint is reset.
}
}
mainarray[prompt] = checkint;
System.out.println("Number has been added\n");
prompt++;
notint = true;
}
}
}
Once the scanner has thrown an InputMismatchException it cannot continue to be used. If your input is not reliable, instead of using scanner.nextInt() use scanner.next() to obtain a String then convert the string to an int.
Replace:
checkint = scan.nextInt();
With:
String s = scan.next();
checkint = Integer.parseInt(s);
I have corrected it like below. I don't rely on exception, but check if the next Scanner input is int (using hasNextInt()). If not int, just consume Scanner token and wait for the next user input.
Looks like it is working, apart from 0 being inserted as a first array element, because you started indexing prompt from 1.
public class Herp {
//The main accesses the methods and uses them.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Hello and welcome!\n");
System.out.print("This program stores values into an array" + " and prints them.\n");
System.out.println("Please enter how many numbers would like to store:\n");
int arraysize = scan.nextInt();
int[] mainarray = new int[arraysize + 1];
int checkint = 0;
boolean notint = true;
int prompt = 1;
while (prompt < mainarray.length) {
while (notint) {
notint = false;
System.out.println("Please enter #" + prompt);
// check if int waits for us in Scanner
if (scan.hasNextInt()) {
checkint = scan.nextInt();
} else {
// if not, consume Scanner token
scan.next();
System.out.println("An integer is required."
+ "\n Input an integer please");
notint = true;
}
}
mainarray[prompt] = checkint;
System.out.println("Number has been added\n");
prompt++;
notint = true;
}
for (int i : mainarray) {
System.out.print(i + " ");
}
}
}