I'm creating a program for my gui number converter. I want my program to ask user a binary string and if he does not enter a binary number, the program will show him error message and will ask him to enter again. The problem is that I can add restriction to alphabets but when it comes to numbers then it fails or it keeps showing the error message.
import java.util.*;
public class test {
Scanner key = new Scanner(System.in);
String in;
int b;
public test(){
do{
System.out.println("Enter the binary string of 5 numbers");
in = key.nextLine();
int i,j;
char ch;
for (i=0 ; i<=5 ; i++){
b = 0;
ch = in.charAt(i);
j = ch;
if (Character.isDigit(ch) && ch<=0 && ch>=1)
b = 1;
else
System.out.println("Please enter a binary number (1 , 0)");
break;
//b = 1;
}
}while(b != 1);
int c;
c = Integer.parseInt(in);
System.out.println("your number is: " + c );
}
public static void main (String args[]){
test obj = new test();
}
}
ch<=0 && ch>=1 does not do what you think it does. The character codes for "0" and "1" are 48 and 49, so you should check for those instead. Also, your >= comparators are backwards, but that's not really the clearest way to write this code. And since you're comparing for just those two values, Character.isDigit(ch) is redundant.
Try one of these:
ch == 48 || ch == 49
ch == '0' || ch == '1'
Scanner has an overloaded nextInt method that uses a radix
int binaryNumber = scanner.nextInt(2);
1) First logic error here for (i=0 ; i<=5 ; i++) replace i<=5 to i<5
2) change the if else condition like below
if (Character.isDigit(ch) && (ch == '0' || ch == '1'))
{
b = 1;
}
else
{
System.out.println("Please enter a binary number (1 , 0)");
break;
}
Related
i am having a bit of trouble in implementing charAt with an array. I am a beginner in Java (and this is my only coding experience i suppose).
The objective: To create a program that the user inputs any string, and the total number of vowels are recorded in the output (case sensitive)
example:
Input: charActer
Output:
a = 1
A = 1
e = 1
import java.util.Scanner;
public class HW5 {
public static void main(String[] args) {
String [] alphabets =
{"aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ"};
String vowels = "aAeEiIoOuU";
int found = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: ");
String inputStr = sc.nextLine();
for(int i=0;i<alphabets.length;i++)
{
if(alphabets.charAt[i] == vowels)
*Note: Program is not complete.
You need to check each character of inputStr (dunno what alphabets is about in your code) and see if it can be found in the vowels string.
String vowels = "aAeEiIoOuU";
int found = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: ");
String inputStr = sc.nextLine();
for (int i = 0; i < inputStr.length(); i++) {
if (vowels.indexOf(inputStr.charAt(i)) >= 0) {
found += 1;
}
}
The documentation is helpful if you're having trouble understanding a method or class.
Having said that, there are lots of ways to count vowels in a String.
Your output indicates that you need the counts per vowel per case, and not just the count of all vowels. To do this you will need a map in order to keep track.
Consider something like
String input = "A string with vowels in it";
Map<Character, Integer> counts = new HashMap<≥();
for (int i = 0; i < input.length; i++) {
char c = input.chart(i);
if (c == 'a') {
int tmp = counts.getOrDefault('a', 0);
tmp++;
counts.put('a', tmp);
} else if (c == 'A') {
// same logic as above for uppercase A
} // other else if statements for e, E, i, I, o, O, u, U
}
// the map has all counts per vowel / case
After the map has all counts you can iterate its entry set to print the output you need
for (Map.Entry<Character, Integer> e : counts. entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}
If you only need the number of values without breaking it down into which vowels, consider something like (not tested)
String vowels = "AaEeIiOoUu";
String input = "Hello World!";
int numVowels = 0;
for (int i = 0; i < input.length; i++) {
char c = input.charAt(i);
if (vowels.indexOf(c) >= 0) {
numVowels++;
}
}
// do something with numVowels
--
Break the problem into simple steps
Define the vowels to look for
Initialize your counter variable (numVowels)
Loop through the input string and check each character against the ones defined in 1 (vowels).
For each vowel you find, increment your counter variable.
public class Vowels {
public static void main(String[] args) {
Map<Character, Integer> vowels = new HashMap<>();
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: "); //"charActer";
String str = sc.nextLine();
for (int i = 0; i < str.length(); i++) {
Character c = str.charAt(i);
if (c == 'a'
|| c == 'A'
|| c == 'e'
|| c == 'E'
|| c == 'i'
|| c == 'I'
|| c == 'o'
|| c == 'O'
|| c == 'u'
|| c == 'U') {
if (vowels.containsKey(c)) {
vowels.put(c, vowels.get(c) + 1);
} else {
vowels.put(c, 1);
}
}
}
for (Map.Entry<Character, Integer> entry : vowels.entrySet()) {
System.out.print(entry.getKey() + "=" + entry.getValue() + " ");
}
}}
Input : charActer
Output : a=1 A=1 e=1
i tried to make a simple program,which check if the input number from the user is a binary number and that number is in correct binary format -> without leading zeros. That below is my code,but it doesn't work. I would appreciate if someone could help.
public class CheckNumberBinary {
public static void main(String args[]) {
int r = 0, c = 0, num, b;
Scanner sl = new Scanner(System.in);
num = sl.nextInt();
int firstDigit = Integer.parseInt(Integer.toString(num).substring(0, 1));// i want to get the first digit from the input
if (firstDigit>0||firstDigit==1 ){
while (num > 0) {
if ((num % 10 == 0) || (num % 10 == 1))
c++;
r++;
num = num / 10;
}
if (c == r) {
System.out.println(true);
} else
System.out.println(false);
} else System.out.printf("WARNING: The number starts with 0");
}
}
There are a better solution, you can check if your input contain only 0 and 1 and the input great then 0 then valide number, so instead you can use String for example :
String num;
Scanner sl = new Scanner(System.in);
num = sl.next();
if (num.matches("[01]+") && !num.startsWith("0")) {
System.out.println("Correct number :" + num);
}else{
System.out.println("Not Correct number!");
}
num.matches("[01]+") will check if your input contain only 0 and 1.
!num.startsWith("0") this to answer this part without leading zeros
Test:
10010 -> Correct number :10010
00001 -> Not Correct number!
11101 -> Correct number :01101
98888 -> Not Correct number!
You can try something like this:
public static void main(String args[]) {
boolean binary=true; // boolean for final decision
String input;
int counter=0; // to count how many leading zeros there are in the input
int target = 5; // specify how many leading zeros allowed!!
Scanner in = new Scanner(System.in);
input = in.nextLine(); // take the entire line as a String
//first loop through the whole input to check for any illegal entry (i.e. non digits)
for(char digit : input.toCharArray()){
if(!Character.isDigit(digit)){ // catch any non-digit !
System.out.println("Illegal Input Found!"); // inform user and exit
System.exit(0);
}
if(digit!='0' && digit!='1'){ // check if it's not 1 and not 0
binary = false;
}
}
// now if there are no illegal inputs, check if it starts with leading zeros
if(input.charAt(0)=='0'){ // potential leading zeros, check the rest
while(input.charAt(counter)=='0'){ // while there are followed zeros
counter++;
if(counter>target && binary){ // leading zeros only in case it's a binary
System.out.println("Illegal Leading Zeros!");
System.exit(0);
}
}
}
// now if your program reach this point that means the input is valid and doesn't contain leading zeros in case it's a binary
if(binary){
System.out.println("It is a binary number");
}
else{
System.out.println("It is NOT a binary number");
}
}
Test:
01010101 -> It is a binary number
01010105 -> It is NOT a binary number
0000001 -> Illegal Leading Zeros!
0000005 -> It is NOT a binary number
000000A -> Illegal Input Found!
Why not simply use the standard library methods?
static boolean isValidBinary(final int input) {
final String binary = String.valueOf(input);
return binary.replaceAll("[01]", "").isEmpty() && !binary.startsWith("0");
}
you should not use sl.nextInt(); it will transfer '011' to 11, so when user input '011', the variable 'num' get the int value 11.
You should simply use sl.next() to get the input of user.
I think you need to check your "if" condition before the while, because you don't want that the number starts with 0, right? so... just ask for it, I have tryied and worded fine to me:
public class CheckNumberBinary {
public static void main(String args[]) {
int r = 0, c = 0, num, b;
Scanner sl = new Scanner(System.in);
String input = sl.next();
num = Integer.parseInt(input);
String firstDigit = (input.length() > 0 ? input.substring(0, 1) : "" );
if (firstDigit.equals("0")) {
System.out.printf("WARNING: The number starts with 0");
} else {
while (num > 0) {
if ((num % 10 == 0) || (num % 10 == 1))
c++;
r++;
num = num / 10;
}
if (c == r) {
System.out.println(true);
} else
System.out.println(false);
}
}
}
The rest of your code Fulfills its mission! It tells you if the number is binary or not, and now plus tells you if your code begins with useless zeros
import java.util.*;
public class BinaryTest {
public static void main(String [] args){
Scanner input=new Scanner(System.in);
int count=0;
boolean check=true;
System.out.print("Enter a number: ");
int num=input.nextInt();
for(int i=0; i<=num; i++){
count=num%10;
if(count>1) {
check=false;
break;
}
else {
check=true;
}
num=num/10;
}
if(check)
System.out.println("Binary");
else
System.out.println("Not Binary");
}
}
Whenever I try to run the code, it gives me an error after I input how many tickets I would like to buy. This is for a lottery program. Here is the code
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
//local data
String guess;
int numTickets;
int counter;
Scanner in = new Scanner(System.in);
//output
System.out.println("How many tickets would you like to buy?");
numTickets = in.nextInt();
for (counter = 0; counter < numTickets; counter++) {
System.out.println("Please enter your three numbers (e.g. 123): ");
guess = in.nextLine();
int randNum = (int) (Math.random() * 1000);
String randNumb;
randNumb = Integer.toString(randNum);
char ch1 = randNumb.charAt(0);
char ch2 = randNumb.charAt(1);
char ch3 = randNumb.charAt(2);
if (ch1 == guess.charAt(0) && ch2 == guess.charAt(1) && ch3 == guess.charAt(2)) {
System.out.print("Winner: " + randNumb);
System.out.print("Congratulations, both pairs matched. /n");
} else if (ch3 == guess.charAt(2) && ch2 == guess.charAt(1)) {
System.out.print("Winner: " + randNumb);
System.out.print("Congratulations, the end pair matched.");
} else if (ch1 == guess.charAt(0) && ch2 == guess.charAt(1)) {
System.out.print("Winner: " + randNumb);
System.out.print("Congratulations, the first pair matched.");
} else {
System.out.print("The Correct Number: " + randNumb);
}
System.out.println("\t Sorry, no matches, You only had");
System.out.println("\t one chance out of 100 to win anyway.");
}
}
}
Exception:
Exception in thread \"main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 0 at
java.lang.String.charAt(String.java:658) at
lottery.Lottery.main(Lottery.java:32)
C:\Users\Ben\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53:
Java returned: 1
This is the exception error displayed when I try to run the program.
Help would be much appreciated!
The error is caused by the behaviour of nextInt method of the Scanner. In addition, your code has other errors as well.
The nextInt method only reads the next integer and nothing else. This means that the new line character (\n or \r or \r\n depending on the OS) is not read. This is fine until you call nextLine. nextLine reads every character until it encounters a new line character. So nextLine sees this unread new line character and stops reading any further and it returns an empty string, which is then put into your guess variable. When you try to access the first character of guess using charAt(0), it crashes because guess does not have any characters.
I suggest you use Integer.parseInt(in.nextLine()) to read an integer from the user.
I've fixed the code for you:
String guess;
int numTickets;
int counter;
Scanner in = new Scanner(System.in);
//output
System.out.println("How many tickets would you like to buy?");
numTickets = Integer.parseInt(in.nextLine());
Random rand = new Random();
for (counter = 0; counter < numTickets; counter++) {
System.out.println("Please enter your three numbers (e.g. 123): ");
guess = in.nextLine();
int randNum = rand.nextInt(1000);
String randNumb = String.format("%03d", randNum);
char ch1 = randNumb.charAt(0);
char ch2 = randNumb.charAt(1);
char ch3 = randNumb.charAt(2);
if (ch1 == guess.charAt(0) && ch2 == guess.charAt(1) && ch3 == guess.charAt(2)) {
System.out.print("Winner: " + randNumb);
System.out.print("Congratulations, both pairs matched. /n");
} else if (ch3 == guess.charAt(2) && ch2 == guess.charAt(1)) {
System.out.print("Winner: " + randNumb);
System.out.print("Congratulations, the end pair matched.");
} else if (ch1 == guess.charAt(0) && ch2 == guess.charAt(1)) {
System.out.print("Winner: " + randNumb);
System.out.print("Congratulations, the first pair matched.");
} else {
System.out.print("The Correct Number: " + randNumb);
}
System.out.println("\t Sorry, no matches, You only had");
System.out.println("\t one chance out of 100 to win anyway.");
}
As you can see, I made other improvements. Firstly, Math.random() * 1000 can return non three digit numbers so I changed it so that it uses a Random object. Using rand.nextInt(900) + 100 only generates three digit numbers.
Secondly, I used String.valueOf(randNum) as XtremeBaumer has said in the comments.
The problem code is below, if you need the entire main method to help me, please ask. The code complies but does not run as expected. I am trying to make the code report back an exclamation mark if the number is out of bounds/larger than the last position of the source text, which is a string the user inputs, so the length cannot be predefined. Exception is 'StringIndexOutOfBoundsException'
TDLR num is an int, sourcetext is a string, both are inputs. Exception: when code should output an '!' instead.
import java.util.Scanner;
public class Temp {
public static void main(String[] args) {
Scanner sc;
int result, num= 0, end = -2, temp, infolost, count;
String word, sourcetext, answer, space= " ";
String sourcetext2, temp2;
char input, result2, chalost;
sc = new Scanner(System.in);
System.out.println("please enter sourcetext");
sourcetext = sc.nextLine(); // user inputs source text
sourcetext = sourcetext.toLowerCase(); // converts sourcetext into lowercase
System.out.print("Would you like to 1 encrypt, or 2 decrypt?");
answer = sc.next(); // user inputs choice
if (answer.equals("1")||(answer.equals("encrypt"))) {
System.out.println("Please enter at least one word to encrypt");
word = sc.next(); // user inputs one word
for (int i= 0; i < word.length(); i++) {
temp = sourcetext.indexOf(word.charAt(i)); // uses index to convert char positions int num
System.out.print(space + temp + space);
}
System.out.print(space + end);
}
else if (answer.equals("2")||(answer.equals("decrypt"))) {
System.out.println("Please enter digits, with one space between each. End with -2");
while (num > -2) {
num = sc.nextInt(); // num to decrypt
if (num > -2) {
result2 = sourcetext.charAt(num); // num converted into characters
System.out.print(result2);
} else if (num > sourcetext.length()) {
System.out.print("!");
} else if (num<0) {
System.out.print("end");
}
}
}
}
}
Try it like this:
int stringLength = sourcetext.length();
if (num > stringLength) {
System.out.print("!");
}
else if (num<0) {
System.out.print("end");
}
This could lead to an IndexOutOfBoundsException - since -1 is greater than -2 - but still out of bounds...
if (num > -2){
result2 = sourcetext.charAt(num); // num converted into characters
System.out.print(sourcetext.indexOf(num));
}
Edit: Unless the users input is -2 - the first if-Statement will always run... You probably need to re-work the logic there.
Edit2: If num is -1 sourcetext.charAt(num); leads to an IndexOutOfBounds. Do something like
if(num == -2) {
System.out.print("end");
} else if (num >= 0 && num < sourcetext.lenght()) {
// index ok
result2 = sourcetext.charAt(num); // num converted into characters
System.out.print(result2);
} else {
// index out of bounds
System.out.print("!");
}
I have the user entering a single character into the program and it is stored as a string. I would like to know how I could check to see if the character that was entered is a letter or a digit. I have an if statement, so if its a letter its prints that it's a letter, and the same for a digit. The code I have so far doesn't work but I feel like I'm close. Any help you can offer is appreciated.
System.out.println("Please enter a single character: ");
String character = in.next();
System.out.println(character);
if (character.isLetter()){
System.out.println("The character entered is a letter.");
}
else (character.isDigit()){
Syste.out.println("The character entered is a digit.");
You could use:
if (Character.isLetter(character.charAt(0))){
....
You could use the existing methods from the Character class. Take a look at the docs:
http://download.java.net/jdk7/archive/b123/docs/api/java/lang/Character.html#isDigit(char)
So, you could do something like this...
String character = in.next();
char c = character.charAt(0);
...
if (Character.isDigit(c)) {
...
} else if (Character.isLetter(c)) {
...
}
...
If you ever want to know exactly how this is implemented, you could always look at the Java source code.
Ummm, you guys are forgetting the Character.isLetterOrDigit method:
boolean x;
String character = in.next();
char c = character.charAt(0);
if(Character.isLetterOrDigit(charAt(c)))
{
x = true;
}
This is a little tricky, the value you enter at keyboard, is a String value, so you have to pitch the first character with method line.chartAt(0) where, 0 is the index of the first character, and store this value in a char variable as in char c= line.charAt(0)
now with the use of method isDigit() and isLetter() from class Character you can differentiate between a Digit and Letter.
here is a code for your program:
import java.util.Scanner;
class Practice
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Input a letter");
String line = in.nextLine();
char c = line.charAt(0);
if( Character.isDigit(c))
System.out.println(c +" Is a digit");
else if (Character.isLetter(c))
System.out.println(c +" Is a Letter");
}
}
By using regular expressions:
boolean isChar = character.matches("[a-zA-z]{1}");
boolean isDigit = character.matches("\\d{1}");
char charInt=character.charAt(0);
if(charInt>=48 && charInt<=57){
System.out.println("not character");
}
else
System.out.println("Character");
Look for ASCII table to see how the int value are hardcoded .
This is the way how to check whether a given character is alphabet or not
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char c = sc.next().charAt(0);
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
System.out.println(c + " is an alphabet.");
else
System.out.println(c + " is not an alphabet.");
}
char temp = yourString.charAt(0);
if(Character.isDigit(temp))
{
..........
}else if (Character.isLetter(temp))
{
......
}else
{
....
}
import java.util.*;
public class String_char
{
public static void main(String arg[]){
Scanner in = new Scanner(System.in);
System.out.println("Enter the value");
String data;
data = in.next();
int len = data.length();
for (int i = 0 ; i < len ; i++){
char ch = data.charAt(i);
if ((ch >= '0' && ch <= '9')){
System.out.println("Number ");
}
else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
System.out.println("Character");
}
else{
System.out.println("Symbol");
}
}
}
}
You need to convert your string into character..
String character = in.next();
char myChar = character.charAt(0);
if (Character.isDigit(myChar)) {
// print true
}
Check Character for other methods..
You could do this by Regular Expression as follows
you could use this code
EditText et = (EditText) findViewById(R.id.editText);
String NumberPattern = "[0-9]+";
String Number = et.getText().toString();
if (Number.matches(NumberPattern) && s.length() > 0)
{
//code for number
}
else
{
//code for incorrect number pattern
}
I have coded a sample program that checks if a string contains a number in it! I guess it will serve for this purpose as well.
public class test {
public static void main(String[] args) {
String c;
boolean b;
System.out.println("Enter the value");
Scanner s = new Scanner(System.in);
c = s.next();
b = containsNumber(c);
try {
if (b == true) {
throw new CharacterFormatException();
} else {
System.out.println("Valid String \t" + c);
}
} catch (CharacterFormatException ex) {
System.out.println("Exception Raised-Contains Number");
}
}
static boolean containsNumber(String c) {
char[] ch = new char[10];
ch = c.toCharArray();
for (int i = 0; i < ch.length; i++) {
if ((ch[i] >= 48) && (ch[i] <= 57)) {
return true;
}
}
return false;
}
}
CharacterFormatException is a user defined Exception. Suggest me if any changes can be made.