Counting the '1's in a binary number string - Java - java

This is part of my code, I was instructed to write a program that accepts a binary number as a string, and that will only show "Accepted" if the total number of 1's is 2. There is more to it, but getting to the point where it is counting the 1's is my problem at the moment. If anyone could point me in the direction of my error, it would be most appreciated.
import java.util.Scanner;
public class BinaryNumber
{
public static void main( String [] args )
{
Scanner scan = new Scanner(System.in);
String input;
int count = 0;
System.out.print( "Enter a binary number > ");
input = scan.nextLine( );
for ( int i = 0; i <= input.length()-1; i++)
{
char c = input.charAt(i);
if ((c == '1') && (c == '0'))
if (c == '1')
{count++;}
if (count == 2)
{System.out.println( "Accepted" );
}
if (count != 2)
{System.out.println( "Rejected" );
System.out.print( "Enter a binary number > ");
input = scan.nextLine( );
}

The problem is that if ((c == '1') && (c == '0')) will never be true.
You need to check if the character is 1 OR 0 and then check if it's a '1' to increment your counter.
int count;
Scanner scan = new Scanner(System.in);
String input;
boolean notValid = false; //to say if the number is valid
do {
count = 0;
System.out.print("Enter a binary number > ");
input = scan.nextLine();
for (int i = 0; i <= input.length()-1; i++){
char c = input.charAt(i);
if(c == '0' || c == '1'){
if (c == '1'){
count++;
if(count > 2){
notValid = true;
break; //<-- break the for loop, because the condition for the number of '1' is not satisfied
}
}
}
else {
notValid = true; // <-- the character is not 0 or 1 so it's not a binary number
break;
}
}
}while(notValid); //<-- while the condition is not reached, re-ask for user input
System.out.println("Done : " + input);

Related

Nothing seems to happen when I try to count vowels and consonants

I need to use while loop.
error: bad operand type for binary operator ||.
first type: boolean
secod type: char
Assume that the letters A, E, I, O and U are vowels; any thing else is
consonant. Write a program that prompts the user to enter a string
(that consists only of letters - no numbers), and displays the number
of vowels and consonants in the string. Use a while loop.
Here is my code:
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = input.nextLine();
s = s.toUpperCase().trim();
int vowels = 0;
int consonants = 0;
int i = 0;
while (i < s.length()){
char ch = s.charAt(i);
if(ch == 'A' || ch == 'E' || ch == 'I'|| ch = 'O' || ch == 'U')
{
++vowels;
}
else {
consonants++;
}
i++;
System.out.println("The number of vowels is " + vowels);
System.out.println("The number of consonants is " + consonants);
}
}
}
I found another solution for my program. Below you can see the new program. This one is running. No problems.
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = input.nextLine();
int vowels = 0;
int consonants = 0;
int i = 0;
while (i < s.length()){
if (Character.isLetter(s.charAt(i))) {
if (Character.toUpperCase(s.charAt(i)) == 'A' ||
Character.toUpperCase(s.charAt(i)) == 'E' ||
Character.toUpperCase(s.charAt(i)) == 'I' ||
Character.toUpperCase(s.charAt(i)) == 'O' ||
Character.toUpperCase(s.charAt(i)) == 'U')
vowels++;
}else{
consonants++;
}
i++;
}
System.out.println("The number of vowels is " + vowels);
System.out.println("The number of consonants is " + consonants);
OUTPUT:
run:
Enter a sentence: We need to plan the next summer
The number of vowels is 9
The number of consonants is 6
BUILD SUCCESSFUL (total time: 1 minute 0 seconds)

Do while loop for Try again program not working correctly (java)

I created a program that convert text to ASCII value and now when i press Y to try again and input a new string there will be a error that string is out of range etc.
I am new in this field, I will appreciate your help.
And here is the Error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index 17,length 17
at java.base/java.lang.String.checkIndex(String.java:3278)
at java.base/java.lang.AbstractStringBuilder.charAt(AbstractStringBuilder.java:307)
at java.base/java.lang.StringBuffer.charAt(StringBuffer.java:242)
at com.company.Main.main(Main.java:26)
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
boolean Flag; // The Boolean variable for the do while lopp
int n,l,j=0,m,i,ch;
char t;
StringBuffer data = new StringBuffer();
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter any string and it will convert into numbers:- ");
data.append(input.nextLine());
l = data.length();
m = l;
System.out.println(l);
for (i = 0; i < m; i++) {
t = data.charAt(j);
n = (int) t;
System.out.print(n);
System.out.print(",");
j++;
}
data.delete(0, m-1);
System.out.println("\nDo you want to try again? Y/N");
ch = input.nextInt();
//Those are the condition for that the program should be run again or not
if (ch == 'Y' && ch == 'y')
Flag = true;
else if (ch == 'N' && ch == 'n')
Flag = true;
else
Flag = false;
}
while(Flag=true);
System.out.println("Thanks, Come Again");
}
}
while(Flag=true);
this doesn't check whether the value of Flag is true, it sets it to true, and thus automatically returns true.
What you want is:
while(Flag==true);
or,
while(Flag);
for short.
You may also want to read up about naming conventions.
As for your Exception:
Y is not an int, change your
ch = input.nextInt();
to
ch = input.nextLine().charAt(0);
this will solve the initial problem, but still might lead to false results with unexpected input (or lack there of)
int n,l,j=0,m,i,ch;
This declaration is invalid. If all of these values are supposed to be
0, the declaration should look like:
int n, l, j, m, i, ch = 0
Also your logic in the nextInput section is incorrect.
if (ch == 'Y' && ch == 'y')
Flag = true;
else if (ch == 'N' && ch == 'n')
Flag = true;
else
Flag = false;
Instead of the AND ( && ) this should be an OR ( || ). If it's 'Y' OR it's 'y'. It will likely never be both Y and y. This should be fixed as follows:
if (ch == 'Y' || ch == 'y') {
Flag = true;
} else if (ch == 'N' || ch == 'n') {
Flag = false;
}
Also, as mentioned by #Stultuske, you'll want to change your while condition to:
while (Flag == true)
One thing that's niggling at me here is that ch is an integer, but you're asking it if that value is 'Y, y, N, n' those are characters and not integers. I'm guessing that's why you got the 'Input_Mismatch_Exception'. Hope this helps.
Edit: Formatting

How can I only accept integer input without try catch in Java

Scanner keyboard = new Scanner(System.in);
System.out.println("Enter number of bars(min 1 / max 6): ");
int barNumbers = keyboard.nextInt();
while (barNumbers <= 0 || barNumbers >= 7) {
System.out.println("Enter number of bars(min 1 / max 6): ");
barNumbers = keyboard.nextInt();
}
int barHeights[] = new int[barNumbers];
int countForBars = 1;
for (int i = 0; i <= barNumbers - 1; i++) {
System.out.println(
"Enter height of bar " + countForBars + " of " + barNumbers + "(min 1 / max 7): ");
barHeights[i] = keyboard.nextInt();
while (barHeights[i] <= 0 || barHeights[i] >= 8) {
System.out.println(
"Enter height of bar " + countForBars + " of " + barNumbers + "(min 1 / max 7): ");
barHeights[i] = keyboard.nextInt();
}
countForBars += 1;
}
Hi guys, I need some help which can be very easy for you because I'm a beginner of Java.
Anyway, I'm now trying to control a robot arm to convey stuff through Java.
The problem is that as you see there, I set some conditions to only get integer numbers between 1-6. So rest of inputs must be restricted especially string. So how can I restrict string input instead of using try catch stuff? If there is any helpful solution, I would appreciate of it. Cheers! And sorry for the code indication. I don't know how to make it like a code :(
May be you can try the following code:
public static boolean isInteger(String str) { //pass your "keyboard" string here.
if (str == null) { // if there is nothing entered in the String
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
}
for (i = 1; i < length; i++) {
char c = str.charAt(i);
if (c < '0' || c > '6') {
return false;
}
}
return true;
}

Input Validation for Java Program to check consecutive sequences

My Java program takes a sequence of numbers entered by a user, and should determine if the string is a series of up to 10 consecutive sequence numbers or if the number sequence contains the same number.
The numbers entered are separated by the dash character. The program should display “Correct consecutive sequence”, “Incorrect consecutive sequence”, “Pair of numbers found”, “Pair of numbers not found” and/or “Invalid Input”.
I am struggling with input validation. I have been working on the code for hours. The iterative loop still runs if I input "n" for it to stop running, when the only thing it should accept is "y" or "Y". Also, the code breaks if I attempt to input a "w" when it should say "invalid input".
Lastly, a pair is not detected if it is not entered first. For example 3-3-4-5 is detected as a sequence with a pair, but it does not also include that is it consecutive. If I enter 3-4-5-5-6, it will not detect the pair. I cannot figure out why it is doing this. Please Help. My code is shown below.
import java.util.Scanner;
public class JavaApplication12 {
/**
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char ch = 'y';
//LOOP TO CONTINUOUSLY TAKE INPUT
while(ch != 'n' || ch != 'N'){
System.out.println("Enter a sequence of numbers");
String num = sc.next();
// WE WILL TAKE STRING INPUT SO WE WILL SPLIT IT WITH DELIMITER
String arr[] = num.split("-");
if(arr.length < 10){
int arrint[] = new int[arr.length];
for(int i=0;i< arr.length;i++){
arrint[i] = Integer.parseInt(arr[i]);
}
// PRESCRIBED CONDITOIONS AND USE OF 2 FUNCTIONS
if(arrint[0] == arrint[1]){
System.out.println("Pair Found");
}else if(arrint[0] == (arrint[1] + 1)){
new func().decreasing(arrint);
}else if(arrint[0] == (arrint[1] - 1)){
new func().increasing(arrint);
}
}else{
System.out.println("Invalid Input");
}
//CODE THAT ASKS USER TO CONTINUE OR NOT
System.out.println("Want to enter more (Y/n)");
ch = sc.next().charAt(0);
}
}
}
// CLASS THAT CONTAINS LOGIC OF FUNCITONS
class func{
public void increasing(int[] arr){
int flag = 1;
for(int i=0;i<arr.length - 1;i++){
if(!(arr[i] == (arr[i+1] - 1))){
flag = 0;
break;
}else if(arr[i] == (arr[i+1])){
flag = 2;
break;
}
}
if(flag == 0){
System.out.println("Incorrect consecutive sequence");
}else if(flag == 1){
System.out.println("Correct consecutive sequence");
}else if(flag == 2){
System.out.println("Pair of numbers found");
}
}
public void decreasing(int[] arr){
int flag = 1;
for(int i=0;i<arr.length - 1;i++){
if(!(arr[i] == (arr[i+1] + 1))){
flag = 0;
break;
}else if(arr[i] == (arr[i+1])){
flag = 2;
break;
}
}
if(flag == 0){
System.out.println("Incorrect consecutive sequence");
}else if(flag == 1){
System.out.println("Correct consecutive sequence");
}else if(flag == 2){
System.out.println("Pair of numbers found");
}
}
}
The following statement will always be evaluated as true, how can a character equals to two different characters at the same time?
while (ch != 'n' || ch != 'N')
Change it to while (ch != 'n' && ch != 'N')

Java phrase guessing game

Wondering how to exit if total phrase is guessed and why my vowels, spaces and consonants are not counting? Most of progam runs great just cant figure out how to exit without saying "n" to question. I am returning values for counters, don't understand?
import java.util.Scanner;
public class Prog09
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
// Initializes all string variables
String sPhrase;
String answer;
// Initializes all int variables
int vowels = 0;
int consonants = 0;
int spaces = 0;
// Initializes all char variables
char cGuess = 0;
char vGuess = 0;
boolean valid = false;
// Asks user to enter if they want to play
System.out.print("Do you want to play a game? [y/n] ");
answer = stdIn.nextLine();
// Asks user to enter the phrase
System.out.print("Please enter the phrase to guess at : ");
sPhrase = stdIn.nextLine();
// Checks if user wants to play
while (answer.equalsIgnoreCase("y"))
{
char[] phrase = new char[sPhrase.length()];
char[] tmpArr = new char[sPhrase.length()];
for(int i = 0; i < sPhrase.length();i++)
{
tmpArr[i] = sPhrase.charAt(i);
phrase[i] = sPhrase.charAt(i);
}
// Runs methods and main body of program
initTemplateArray(sPhrase, tmpArr, spaces);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
while (answer.equalsIgnoreCase("y"))
{
//getConsonant(stdIn, cGuess);
cGuess = getConsonant(stdIn, cGuess);
vGuess = getVowel(stdIn, vGuess);
isVowel(vGuess, valid);
updateTemplateArray(tmpArr, sPhrase, cGuess, vGuess, consonants, vowels);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
stdIn.nextLine();
System.out.print("Do you want to try again? [y/n]: ");
answer = stdIn.next();
vGuess = 0;
cGuess = 0;
}
}
// Prints results
System.out.println("The common phrase contained: Spaces: " + spaces + " Consonants: " + consonants + " Vowels: " + vowels);
stdIn.close();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods for program
public static int initTemplateArray(String sPhrase, char [] tmpArr, int spaces)
{
for (int i = 0; i < sPhrase.length(); i++)
{
if (sPhrase.charAt(i) == ' ')
{
spaces++;
tmpArr[i] = ' ';
}
if (!(sPhrase.charAt(i) == ' '))
{
tmpArr[i] = '?';
}
}
return spaces;
}
public static void printTemplateArray(char [] tmpArr)
{
for (int i = 0; i < tmpArr.length; i++)
{
System.out.print(tmpArr[i]);
}
System.out.println();
}
public static boolean isVowel(char c, boolean valid)
{
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
return valid = true;
}
else
{
return valid = false;
}
}
public static char getConsonant(Scanner stdIn, char cGuess)
{
while(cGuess == 'a' || cGuess == 'e' || cGuess == 'i' || cGuess == 'o' || cGuess == 'u'|| cGuess == 0)
{
System.out.print("Enter a lowercase consonant guess : ");
String myGuess = stdIn.next();
cGuess = myGuess.charAt(0);
}
return cGuess;
}
public static char getVowel(Scanner stdIn, char vGuess)
{
while(!(vGuess == 'a' || vGuess == 'e' || vGuess == 'i' || vGuess == 'o' || vGuess == 'u'))
{
System.out.print("Enter a lowercase vowel guess : ");
String newGuess = stdIn.next();
vGuess = newGuess.charAt(0);
}
return vGuess;
}
public static int updateTemplateArray(char [] tmpArr, String sPhrase, char cGuess, char vGuess, int consonants, int vowels)
{
vowels = 0;
consonants = 0;
for (int i = 0; i < tmpArr.length; i++)
{
if (cGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
consonants++;
}
if (vGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
vowels++;
}
}
return consonants & vowels;
}
public static void printHeader()
{
System.out.println("");
System.out.println(" Common Phrase");
System.out.println("---------------");
}
}
Java passes Ints by value instead of by reference, this means that updateTemplateArray doesn't modify the values of main's vowels, consonants or spaces. To fix this you could:
Make these variables global by definining them outside the scope of the main method. You would have to change the name of the parameters in the updateTemplateArray method to prevent shadowing.
Break updateTemplateArray into separate functions to count each of the vowels, consonants or spaces, and have them return the count of each. You would then call something like: vowels = countVowels(sPhrase); to populate the variables.
With the current setup, it will exit whenever answer stops being equal to 'y' Changing the value of answer at any time will exit the loop.

Categories

Resources