Stack Overflow Asked by Aworeham on December 20, 2021
I am adding the number of ones in a binary number and have gotten the correct result. However, when I separate the number with spaces it tells me the number’s odd.
For example input of: 101 will return even. However, an input of 1 0 1, will return odd.
I would rather return "Not a valid input" if the input contains spaces but I don’t know how to do that either.
For some reason when I enter a name with spaces for example "D a n" the program automatically assigns "D" as the binary number and skips the rest.
//Get user input of Name
System.out.println( "Enter your first name > " );
String firstName = scan.next( );
System.out.print( "Enter a binary number > " );
String num = scan.next( );
//Remove special characters/spaces from String firstName
firstName = firstName.replaceAll("[^a-zA-Z0-9]", "");
firstName = firstName.replaceAll("\s", "");
//Extract first letter and capitalize
String firstNameStart = firstName.substring(0, 1);
firstNameStart = firstNameStart.toUpperCase( );
//Extract remainder of name
String firstNameRemainder = firstName.substring( 1 );
firstNameRemainder = firstNameRemainder.toLowerCase( );
//Concatenate name
firstName = firstNameStart + firstNameRemainder;
//Print name properly
System.out.println("n" + firstName);
//Analyze binary number
if (String.valueOf(num).matches("[0-1]+")){
// Sum of 1's in the binary number
int res = 0;
for (int i = 0; i < num.length(); i++)
{
if(num.charAt(i) == '1')
res = ++res;
}
{
if (res % 2 == 0)
System.out.println("Even.");
else
System.out.println("Odd.");
}
If not specifically set, Scanner
's next()
method will stop when it reaches the default delimiter, which is a blank space.
When you insert 1 0 1
it stops at the first blank space, and gives you the result (1
is odd).
When you insert the name with blank spaces, the first part will be assigned to the name, and the second next()
will just continue reading the first input string until the next blank space is found (assigning it to the binary number in your code).
If you want the delimiter to be n
, that is, when you push Enter
on your keyboard, you could call nextLine()
, which will instead read the line until n
is found.
In order to get the number correctly, and check wether it's even/odd, if there are blank spaces in the input, you should:
String line = scanner.nextLine().trim(); //removes whitespaces
int number = Integer.parseInt(line); //converts it to a number
//check if the integer is even/odd
if ((number & 1) == 0)
{
//it's even!
...
}
else
{
//it's odd!
....
}
Answered by aran on December 20, 2021
Use Scanner#nextLine
to read the entire line.
String firstName = scan.nextLine( );
System.out.print( "Enter a binary number > " );
String num = scan.nextLine( ).replaceAll("[^01]", "");
Answered by Unmitigated on December 20, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP