Printing error for every character read in the string - java

I'm looking not only how to do it, but also how to do it and produce an error message for a character that I don't want. So what I mean is I have the user put in input, then I want to produce an error message if the input the user put didn't have a 0 or a 1. So a 1121 would produce an error, but a 1101 would be fine.
I have this so far and in the shell it prints "error" after every character, even if it's correct.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n;
System.out.print("Please enter a sequence of 1's and 0's");
String binInput = scan.nextLine();
System.out.println(binaryToDecimal(binInput));
char c;
for (int j = 0; j < binInput.length(); j++) {
c = binInput.charAt(j);
if (c<0 || c>1){
System.out.print("Error");}
}
public static int binaryToDecimal(String binString) {
int size = binString.length();
if (size == 1) {
return Integer.parseInt(binString);
} else {
return binaryToDecimal(binString.substring(1, size)) + Integer.parseInt(binString.substring(0, 1)) * (int) Math.pow(2, size - 1);
}
}
Any help would be appreciated

Change the if statement like this
if (!(c == '0' || c == '1')){//...
It means
if c isn't character 0 or chararcter 1

c is defined as a char and java allows chars to utilize relational and equivalent operators. The charAt(int) method pulls the specific char out. In this case you should change your if statement to something like this:
if(c != '0' && c != '1')

O.K. let's see if this code will give you an error. (Please, be sure that you'r input didn't include any 'white spaces'
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n;
System.out.print("Please enter a sequence of 1's and 0's");
String binInput = scan.nextLine();
// System.out.println(binaryToDecimal(binInput));
char c;
for (int j = 0; j < binInput.length(); j++) {
c = binInput.charAt(j);
if (!(c == '0' || c == '1')) {
System.out.print("Error");
}
}
I commented out one statement - it isn't relevant...

Related

How to check where the input word lies in terms of word range?

How to check whether input word lies "before", "inside", or "after" a given "word range"? For each input word, we just need to output "before", "inside" or "after"..
To determine the order, character precedence rule is: '' < 'A' < 'a' < 'B' < 'b' .. 'Z' < 'z'.
Format of input is:
1) <start word> <end word>
2) A sequence of N words
For example:
Input:
============
Apple Pear
Aa
Aq
App
Apple
Output:
============
before // as Aa < Apple
inside // as Aq > Apple && Aq < Pear
before // as App < Apple
inside // as Apple == Apple && Apple < Pear
Below is what I have got but it gives wrong output so my comparison logic is wrong looks like.
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
String startWord = sc.next(); // this will give "Apple"
String endWord = sc.next(); // this will give "Pear"
while (sc.hasNext()) {
// below will give "Aa", or "Aq", or "App" or "Apple" one by one
String queryWord = sc.next();
if(queryWord.compareTo(startWord) < 0 && queryWord.compareTo(endWord) < 0) {
System.out.println("before");
} else if(queryWord.compareTo(startWord) > 0 && queryWord.compareTo(endWord) > 0) {
System.out.println("after");
} else if(queryWord.compareTo(startWord) == 0 && queryWord.compareTo(endWord) == 0) {
System.out.println("inside");
}
}
sc.close();
}
Update:
So logic will be this?
while (sc.hasNext()) {
String queryWord = sc.next();
int qValue = 0;
for(char c : queryWord.toCharArray()) {
qValue += map.get(c);
}
if(qValue > sValue && qValue < eValue) {
System.out.println("inside");
} else if(qValue > sValue && qValue > eValue) {
System.out.println("before");
} else {
System.out.println("after");
}
}
Before posting a solution, let's take a look at the input range.
each letter of the word will be anything inside of [A,Z] or [a-z].
Now below is the logic that I would like to use in order to calculate whether a given input is - before, inside or outside.
1. Let's initialize two variables - startWord and endWord.
2. Take input for the above two variables.
3. Now, I create a map which stores value for each letter constant. As per the question, my values will look something like this:-
A - 1
a - 2
B - 3
b - 4
.
.
Z = 51
z = 52.
4. Now I will calculate value of each word, so for example, value of Apple will be = A+p+p+l+e = 1+32+32+24+10 = 99.
5. Similarly I will do for Pear.
6. Now for each user input value, for example Aa. I will make this calculation again, so for Aa its = A+a = 1+2 = 3. And 3 is less then 99.
7. Now it all comes to Maths, if this value is within the range of startWord and endWord, then I print inside, if its less then answer is before otherwise after.
Hope this helps!
let us assume it as a number line in which firstword is at point X and and secondword is at y.
As per the question we need to state that the input word lies below x, in between x and y or its beyond y.
Now, the question arises that how the comparison will happen for different words ?
seeing the above example, we can conclude that if the any character of the first string if bigger than the character at the same position of the other string, then we can say that first string is bigger than than other.
For example:
Aa < Apple - because the 2nd 'A' in 'AA' will lie below 2nd 'p' in
'Apple' in a number line .
Aq > Apple - because the 2nd 'q' in 'Aq' will lie beyond 2nd 'p' in
'Apple' in a number line.
App < Apple - because 'App' is equal to 'App' in 'Apple' but it has
extra 2 more characters 'le' after 'App'.
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String startWord = sc.next(); // this will give "Apple"
String endWord = sc.next(); // this will give "Pear"
while (sc.hasNext()) {
String queryWord = sc.next();
if (compare_str(queryWord, startWord) < 0 && compare_str(queryWord, endWord) < 0) {
System.out.println("before");
} else if (compare_str(queryWord, startWord) > 0 && compare_str(queryWord, endWord) > 0) {
System.out.println("after");
} else if (compare_str(queryWord, startWord) >= 0 && compare_str(queryWord, endWord) <= 0) {
System.out.println("inside");
}
}
sc.close();
}
I designed a custom compare function which compare the string and returns the status on as 1,0,-1.
public static int compare_str(String a, String b) {
int len = Math.min(a.length(), b.length());
for (int i = 0; i < len; i++) {
if (a.charAt(i) == b.charAt(i))
continue;
if ((a.charAt(i) > b.charAt(i)))
return 1;
else
return -1;
}
if (b.length() > a.length())
return -1;
if (b.length() < a.length())
return 1;
return 0;
}
I hope this piece of code will be usefull.

Check each position in the input entry and return the number of times a character occurs

I wrote the following code but I can't seem to convert the string to a char and then search the input entry string. My code is below. Any helpful tips would be greatly appreciated. I'm supposed to use a while loop but felt like for was easier to start with.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String inputEntry;
String inputCharacter;
int length;
int i;
int counter = 0;
System.out.println("Enter a string: ");
inputEntry = in.next();
System.out.println("Enter a letter: ");
inputCharacter = in.next();
length = inputCharacter.length();
if (length == 1) {
for(i = 0; i <= inputEntry.length(); i++){
char c = inputCharacter.charAt(0);
if (inputEntry.charAt(i) == c){
counter++;
}
}
}
else {
System.out.println("The input letter was not a single letter.");
}
}
}
It looks like the only problem in your code is that you are using <= instead of < within your loop. <= is incorrect because it passes string length as an index, but first character resides at charAt(0), and last character resides at charAt(inputEntry.length() - 1)
Replacing your loop declaration with the following will do the trick:
for(i = 0; i < inputEntry.length(); i++){
Then you also need to System.out.println(counter); after the for loop.

How to find all consecutive letters with count from string provided by user?

I am trying to write a code in Java which will find all the consecutive letters in string provided by user and also provide its count.
For example:
User has provided string: "aaastt rr".
I am expecting the result as below:
a - 3
t - 2
r - 2
I have written below code as per my understanding but not getting the result as expected.
import java.util.Scanner;
public class ConsecutiveCharacters {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter string: ");
char s[] = sc.nextLine().toCharArray();
int count = 1;
for(int i =0;i<s.length-1;i++){
if(s[i]==s[i+1]){
count++;
System.out.println(s[i] + "-" + count);
}
}
}
}
I am getting result:
a-2
a-3
t-4
r-5
which is not I am expecting.
Please have a look, and let me know where I am missing.
Many Thanks in advance.
You are never resetting your counter when you run into a new character within the array.
Use the starting character and increment as you go and change the character whenever a new one is found and only print the previous char and count if the count is greater than 1. Note the edge case where the last of the characters are consecutive.
Scanner sc = new Scanner(System.in);
System.out.println("Enter string: ");
char s[] = sc.nextLine().toCharArray();
HashMap<Character, Integer> charsFound = new HashMap<>();
int count = 1;
char c = s[0];
for(int i = 1;i < s.length; i++)
{
//check the edge case where the last of the array is consecutive chars
if(c==s[i] && count >= 1 && s.length - 1 == i)
{
if(!charsFound.containsKey(c))
charsFound.put(c, ++count);
else if(charsFound.get(c) < ++count)
charsFound.put(c, count);
}
//increment the count if the character is the same one
else if(c==s[i])
{
count++;
}
//consecutive chain is broken, reset the count and our current character
else
{
if(count > 1)
{
if(!charsFound.containsKey(c))
charsFound.put(c, count);
else if(charsFound.get(c) < count)
charsFound.put(c, count);
}
//reset your variables for a new character
c = s[i];
count = 1;
}
}
for (char knownCharacters : charsFound.keySet())
if (charsFound.get(knownCharacters) > 1)
System.out.println(knownCharacters + "-" + charsFound.get(knownCharacters));
Output
Enter string:
aabbbt s.r r rr
a-2
b-3
r-2
Enter string:
aaastt rr
a-3
t-2
r-2
Enter string:
aayy t t t.t ty ll fffff
a-2
y-2
l-2
f-5
Enter string:
aa b aa c aaaaa
a-5

Digit Frequency In A String

I am supposed to do this :
For an input number print frequency of each number in the order of its occurrence.For eg :
Input:56464
Output:
Number-Frequency
5 -1
6 -2
4 -2
I cannot use any other libraries except java.lang and Scanner to input
So I tried this :
package practice2;
import java.util.Scanner;
public class DigitFrequency2
{
private static Scanner sc;
public static void main(String[] args)
{
sc = new Scanner(System.in);
System.out.println("Enter an integer number");
String sb = sc.nextLine();
System.out.println("Number\tFrequency");
int i,x,c = 0;
for(i=0;i<sb.length();i++)
{
c = 0;
for(x = i+1;x<sb.length();x++)
{
if(sb.charAt(i) == sb.charAt(x) && sb.charAt(i) != '*' && sb.charAt(x) != '*')
{
c++;
sb.replace(sb.charAt(x),'*');
}
}
if(c>0)
{
System.out.println(sb.charAt(i)+" \t"+c);
}
}
}
}
Number Frequency
6 1
4 1
Where am I going wrong please help.
Simple way is this. Won't bother commenting as it is clear whats going on.
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("Input String: ");
String line = in.nextLine();
while (!line.isEmpty()) {
char c = line.charAt(0);
int length = line.length();
line = line.replace(String.valueOf(c), "");
System.out.println(c + " " + (length - line.length()));
}
}
There are few problems with sb.replace(sb.charAt(x),'*');:
replace replaces all characters, not just first one which is why your c can't be grater than 1.
Strings are immutable so since replace can't edit original string, it returns new one with replaced characters which you can store back in sb reference.
Anyway if you would be able to use other Java resources beside java.lang.* or java.util.Scanner simple approach would be using Map which will map character with number of its occurrences. Very helpful here is merge method added in Java 8 allows us to pass key initialValue combination of old and new value
So your code can look like:
String sb = ...
Map<Character, Integer> map = new TreeMap<>();
for (char ch : sb.toCharArray()) {
map.merge(ch, 1, Integer::sum);
}
map.forEach((k, v) -> System.out.println(k + "\t" + v));
Problem is that as mentioned, String is immutable, so String.replace() just returns a new string and it does not (cannot) modify the original. Either you should use StringBuilder, or store the returned value (e.g. sb = sb.replace(sb.charAt(x),'*');).
Going further, since you initialize c with 0, it will stay 0 if there is no other occurrence of the character in question (sb.charAt(i)), so your algorithm won't detect and print digits that occur only once (because later you only print if c > 0).
Counting occurrences (frequency) of characters or digits in a string is a simple operation, it does not require to create new strings and it can be done by looping over the characters only once.
Here is a more efficient solution (one of the fastest). Since digits are in the range '0'..'9', you can create an array in which you count the occurrences, and by looping over the characters only once. No need to replace anything. Order of occurrence is "remembered" in another order char array.
char[] order = new char[10];
int[] counts = new int[10];
for (int i = 0, j = 0; i < sb.length(); i++)
if (counts[sb.charAt(i) - '0']++ == 0)
order[j++] = sb.charAt(i); // First occurrence of the digit
And print in order, until the order array is filled:
System.out.println("Number\tFrequency");
for (int i = 0; order[i] != 0; i++)
System.out.println(order[i] + "\t" + counts[order[i] - '0']);
Example output:
Enter an integer number
56464
Number Frequency
5 1
6 2
4 2
For completeness here's the complete main() method:
public static void main(String[] args) {
System.out.println("Enter an integer number");
String sb = new Scanner(System.in).nextLine();
char[] order = new char[10];
int[] counts = new int[10];
for (int i = 0, j = 0; i < sb.length(); i++)
if (counts[sb.charAt(i) - '0']++ == 0)
order[j++] = sb.charAt(i); // First occurrence of the digit
System.out.println("Number\tFrequency");
for (int i = 0; order[i] != 0; i++)
System.out.println(order[i] + "\t" + counts[order[i] - '0']);
}
Note:
If you would want to make your code safe against invalid inputs (that may contain non-digits), you could use Character.isDigit(). Here is only the for loop which is safe against any input:
for (int i = 0, j = 0; i < sb.length(); i++) {
char ch = sb.charAt(i);
if (Character.isDigit(ch)) {
if (counts[ch - '0']++ == 0)
order[j++] = ch; // First occurrence of ch
}
}
This should be a good code to print frequency using user input:
public static void main(String args[])
{
System.out.println("Please enter numbers ");
String time = in.nextLine(); //USER INPUT
time = time.replace(":", "");
char digit[] = {time.charAt(0), time.charAt(1), time.charAt(2), time.charAt(3)};
int[] count = new int[digit.length];
Arrays.sort(digit);
for (int i = 0; i < digit.length; i++)
{
count[i]++;
if (i + 1 < digit.length)
{
if (digit[i] == digit[i + 1])
{
count[i]++;
i++;
}
}
}
for (int i = 0; i < digit.length; i++)
{
if (count[i] > 0)
{
System.out.println(digit[i] + " appears " + count[i]+" time(s)");
}
}
}

How to implement Java "Scanner" in C++?

Please have a look at the following java code
import java.util.Scanner;
public class Main
{
static int mul=1;
static String convert;
static char[] convertChar ;
static StringBuffer buffer = new StringBuffer("");
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
int number=0;
int loopValue = scan.nextInt();
//System.out.println("print: "+loopValue);
for(int i=0;i<loopValue;i++)
{
number = scan.nextInt();
// System.out.println("print: "+number);
for(int a=1;a<=number/2;a++)
{
if(number%a==0)
{
//System.out.println(a);
mul = mul*a;
//System.out.println(mul);
}
}
convert = String.valueOf(mul);
convertChar = convert.toCharArray();
if(convertChar.length>4)
{
/*System.out.print(convertChar[convertChar.length-4]);
System.out.print(convertChar[convertChar.length-3]);
System.out.print(convertChar[convertChar.length-2]);
System.out.print(convertChar[convertChar.length-1]);
System.out.println();*/
buffer.append(convertChar[convertChar.length-4]);
buffer.append(convertChar[convertChar.length-3]);
buffer.append(convertChar[convertChar.length-2]);
buffer.append(convertChar[convertChar.length-1]);
System.out.println(buffer);
}
else
{
System.out.println(mul);
}
//System.out.println(mul);
mul = 1;
}
}
}
This code is built to compute the product of positive divisors of a given number. I have used scanner here because I don't know how many inputs will be entered. That is why I can't go something like
int a, b;
cin >> a >> b
in C++. All the inputs will be inserted by a test engine, into one single like like following
6 2 4 7 8 90 3456
How can I implement the Java "Scanner" using C++ ? Is there a header file for that? Please help!
You seem to be using Scanner to read one integer at a time from the standard input stream. This is easily accomplished with the extraction operator, operator>>.
Replace this code:
Scanner scan = new Scanner(System.in);
int number=0;
int loopValue = scan.nextInt();
//System.out.println("print: "+loopValue);
for(int i=0;i<loopValue;i++)
{
number = scan.nextInt();
// System.out.println("print: "+number);
With this:
int number=0;
int loopvalue=0;
std::cin >> loopvalue;
for(int i = 0; i < loopValue; i++)
{
std::cin >> number;
You should check the value of std::cin after the >> operations to ensure that they succeeded.
Refs:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt
If you use std::cin >> value; to read the value then you can only process the entire line once a new-line has been detected.
If you want to process each number as it is typed then you could use a function like:
int nextInt()
{
std::stringstream s;
while (true)
{
int c = getch();
if (c == EOF) break;
putch(c); // remove if you don't want echo
if ((c >= '0' && c <= '9') || (c == '-' && s.str().length() == 0))
s << (char)c;
else if (s.str().length() > 0)
break;
}
int value;
s >> value;
return value;
}
OK, there are probably more efficient ways to write that but it will read the input character by character until a number is encountered and will return whatever number is read when anything other than a number is encountered.
E.g. 1 2 3 4 would return 1 on the first call, 2 on the second etc.

Categories