An error with for loop - java

I am working on problem of string manipulation.Following is my code snippet.
I am really not sure why my code control is not going inside IF loop.
public class test{
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int searchVariable = scan.nextInt();
int numberOfValues = scan.nextInt();
scan.nextLine();
while (numberOfValues-- != 0) {
String strg = scan.nextLine();
String[] arrayInt = strg.split(" ");
for (int i = 0; i < arrayInt.length; i++) {
// System.out.println("test 1===");
// System.out.println("i value" + i);
// System.out.println("i " + strg.charAt(i));
// System.out.println(searchVariable);
if (searchVariable==strg.charAt(i)) {
System.out.println("===>");
System.out.println("index " + i);
return;
}
}
}
}
}
Input
4
6
1 4 5 7 9 12
Output
output should be 4.
As i am writing this code for finding integer 4 in the third line of input.
Problem
Program control is not going inside the loop if (searchVariable==strg.charAt(i))
.Please help!!

The is problem in your logic: What you actually want is
if (searchVariable==Integer.parseInt(arrayInt[i]))...

When java compares different objects, it checks different aspects, one of them is their type.
For example, the char '1' is different from the integer 1 and therefore '1'==1 will return false.
char c = '1';
System.out.println(c==1); //false
When comparing char to integer you should use parsing or the method Character.getNumericValue(c):
System.out.println(Character.getNumericValue(c)==1); //true
Also note that when java compares char to integer it uses the ascii value of the char, therefore ,char 'a' equals to the integer 97 and '1' equals integer value of 49: (and so on..)
System.out.println(c==49); //true

Related

frequency of a letter in a string using arrays

In this program I have been having trouble to get the terminal window I suspect it might be a runtime error .I am using blue J btw. Also I dont understand why the code used this
f[ch-'A']++;
Please help out with a tracing for this program.
This is the code:
import java.util.*;
public class frequency
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int f[]= new int[26];
System.out.println("enter a string");
String input = sc.nextLine();
input= input.toUpperCase();
for(int i=0; i<input.length();i++)
{
char ch=input.charAt(i);
if (Character.isLetter(ch))
f[ch-'A']++;
}
System.out.println("Characters Frequency");
for(int i=0;i<26;i++)
{
if( f[i]!=0)
{
System.out.println((char) (i+'A') + "\t\t" + f[i]);
}
}
}
}
Because it is converting the text to uppercase
input= input.toUpperCase();
each char can have the ascii value of A subtracted (see https://www.asciitable.com/) to obtain an index into the array.
'B' - 'A' == 1 etc
test
enter a string
stupid sod
Characters Frequency
D 2
I 1
O 1
P 1
S 2
T 1
U 1

How can I get many outputs using only one input?

I want to change decimal to binary, octagonal, hexadecimal, By setting only one input(decimal) int i, I want to get 3 output: binary, octal, hexadecimal.
But my problem is that when I write 'while' once to change to binary using int i, I can't get proper answer about next 'while' to change to octagonal using int i.
I thought my code about octal was wrong, but when I set another int o, it worked properly...I think the result of first 'while' is used as input in next 'while'.
I wonder if I use 'while' once using int i, then can't I use that original int i in next 'while'?
I want to know how to get 3 output using only one input.
For example,
input
output
2017
b 11111100001
o 3741
h 7e1
It's my first time studying coding, so my question can be weird. Sorry:(
Code below is I made using two input.
import java.util.Scanner;
public class LA {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int i = scn.nextInt();
String ab = "";
while (i > 0) {
ab = (i % 2) + ab;
i /= 2;
}
System.out.println("b " + ab);
int o = scn.nextInt();
String cd = "";
while (o > 0) {
cd = (o % 8) + cd;
o /=8;
}
System.out.println( "o " + cd);
}
}
You first while loop changes the value of i. At the end of this while loop i=0 so the next while loop will fail immediat.
Just keep the input in a separate variable which you don't change and copy it to i before each while loop:
int input = scn.nextInt();
int i= input;
while () {}
i=input;
while(i>0) { }
As far as I see and according to documentation.
https://www.tutorialspoint.com/java/util/scanner_nextint.htm
You are calling scn.nextInt() 2 times and should be only called 1 time.
Because scn.nextInt() expect input from keyboard.
Save original input in another variable.
Here is the code:
import java.util.Scanner;
public class LA {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int originalInput = scn.nextInt();
int i = originalInput; // copy by value, not by reference.
String ab = "";
while (i > 0) {
ab = (i % 2) + ab;
i /= 2;
}
System.out.println("b " + ab);
int o = originalInput; // again copy original input here.
String cd = "";
while (o > 0) {
cd = (o % 8) + cd;
o /=8;
}
System.out.println( "o " + cd);
}
}
I'm not sure if you're trying to do it the hard way on purpose, but you can also use System.out.printf() for octal and hex, and Integer.toBinaryString(anInt) for binary.

Flipping binary numbers using recursion

I am working on a project that the user enters an odd binary number ex: 10101 and I am supposed to have a recursive method that will flip the 1's and 0's ex: 101 = 010. For some reason my code is getting rid of the leading zero making the number an even number which crashes the program. Any and all help is appreciated, below is my Recursive class that is supposed to do the work of flipping the binary digits.
public class Recursive2 {
// int digit;
String temp;
public Recursive2(int d){
//digit = d;
temp = recursive(Integer.toString(d));
//System.out.print(recursive(temp));
}
public String toString(){
return temp;
}
public String recursive(String a){
String tempStr = "";
if(a.length() % 2 == 0){
System.out.println("Even number");
return "";
}
else if(a.length() == 1){
if(a.equals("1")){
tempStr = "0";
// tempStr += d;
}
else if(a.equals("0")){
tempStr= "1";
}
//System.out.println("Flipped d to" + tempStr);
}
else{
tempStr += new Recursive2(Integer.parseInt(a.substring(0,1))).toString();
tempStr += new Recursive2(Integer.parseInt(a.substring(1, a.length() - 1))).toString();
tempStr += new Recursive2(Integer.parseInt(a.substring(a.length()-1, a.length()))).toString();
}
return tempStr;
}
Here is my main class that tests the recursion.
public static void main(String[] args){
String num;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a Binary number with an odd amount of digits: ");
num = in.nextLine();
System.out.println(num);
int num2 = Integer.parseInt(num);
System.out.println(num2);
Recursive2 test = new Recursive2(num2);
System.out.println(test);
}
You made several mistakes:
Deciding if the number is odd or even should be done before calling recursive method. Currently, your code will stop after at most one invocation, because you check the number of bits.
There is no need to parse int and making it String again. The entire process can be done entirely with strings.
Constructing the result should consist of appending the result of recursive invocation without the last bit to the string representing the inverse of the last bit.
The base case should be a situation when the string is empty, not when the string has exactly one digit.
Fixing these mistakes will produce a correct implementation.
The current algorithm is beyond repair.
Here's a recursive algorithm that's very simple and that will work:
if the string is empty, return it
if the first char is 0, return "1" + recurse(s.substring(1))
otherwise (the first char is 1), return "0" + recurse(s.substring(1))
Leading zeros are ignored because you're converting the input binary number to integer. For an integer leading zeros don't mean anything. You should be working with String only.
Also Integer.parseInt(num); would assume that you want to parse a decimal number not binary. If you do want to parse a binary number then you'll have to use another overloaded method Integer.parseInt(String s, int radix)
However as I said, because of the leading zeros you should work only with the Strings.
Integer.parseInt(i) converts the String to its Integer value.
However the Integer value of 010 is 10, leading 0's are dropped.
Work with the input as a String to avoid this.
Use StringBuilder to avoid creating new String or you can use char array
public static void main(String[] args) {
int no = 1234; // some no
String in = Integer.toBinaryString(no);
System.out.println("Original " + in);
System.out.println("Flipped " + flipBits(in));
}
public static String flipBits(String in) {
if (in.length() % 2 == 0)
return "even length";
return new String(flipBits(in.toCharArray(), in.length() - 1));
}
private static char[] flipBits(char[] ch, int index) {
if (index < 0) {
return ch;
} else {
ch[index] = Character.forDigit(49 - ch[index], 2); //flip
return flipBits(ch, index - 1);
}
}
output
Original 10011010010
Flipped 01100101101
The problem is that you are converting to integer values, which will throw away leading zeros. Just deal with strings:
public static void main(String[] args){
String num;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a Binary number with an odd amount of digits: ");
num = in.nextLine();
System.out.println(num);
String flipped;
if (num.length() % 2 == 0) {
flipped = "Even number";
else {
flipped = Recursive2.recursive(num);
}
System.out.println(flipped);
}
And the Recursive2 class can just have static methods:
public class Recursive2 {
private static String flip(char c) {
if (c == '0') return "1";
return "0"; // assumes characters are all 0 or 1
}
public static String recursive(String a) {
STring tempStr;
if (a.length() == 0) {
tempStr = "";
} else {
tempStr = flip(a.charAt(0)) + recursive(a.substring(1));
}
return tempStr;
}
}
You might want to throw an exception if you detect a character other than 0 or 1.
EDIT: Based on your comment, the recursive method can be written as:
public static String recursive(String a) {
String tempStr = flip(a.charAt(0));
final int len = a.length();
if (len > 1) {
tempStr += recursive(a.substring(1, len - 1)) + flip(a.charAt(len - 1));
}
return tempStr;
}
This assumes that the argument is an odd-length string. That check should be done outside the recursive method, since if it is true once, it is true at every subsequent recursion.
I'd advise you to instead, remove one digit from the String that the user has imputed, and convert it (from the 1 to 0 vise versa), then use sub-string as the pass for the recursive function with one less.
Hint-> the base case would be a.length() == 0; because if you remove one digit of the string you will eventually have the length be 0.
Good Luck!

Changing single chars to upper or lower case depending on user input in Java

I have tried to find guidance on this, but I keep getting solutions on an entire string, or a single character. I am in my 4th week of Java, and have hit a roadblock.
I have to ask a user to input three letters ("Enter three letters: abc"). Depending on which case they type, I have to write a program that swaps upper with lower and visa versa. For example, if the user types "aBc", my output will be "AbC".
This is what I have so far. If my code is horrible, I'm sorry. I'm learning as I go.
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
for (int i = 0; i < letters.length(); i++) {
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.println(Character.toLowerCase(letter1));
else {
System.out.println(Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.println(Character.toLowerCase(letter2));
else {
System.out.println(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.println(Character.toLowerCase(letter3));
else {
System.out.println(Character.toUpperCase(letter3));
}
}
}
}
When I typed "abc" for the input, the output was:
A
B
C
A
B
C
A
B
C
The format of the output is supposed to be "Result: ABC". I can work on that later. I'm just trying to figure out how to get this to execute correctly. My hunch is that I'm definitely going wrong on my if/else statements. I do not know how to print the changed chars all in a row (abc, AbC, ABC, etc). I thought I did it correctly at the beginning with the indexing of the string (0,1,2).
By the way, it's not showing my output correctly this forum. It is supposed to be one letter per line, not "ABCABCABC", if I made sense with that.
The reasoning for this is because it's inside of a for loop, which is essentially worthless, because you are never using the integer 'i'. If you remove the for loop, it should only execute once, thus for outputting "ABC", instead of "A B C A B C A B C". To print the chars in a row, you can simply append each character to a string, and then output that.
The biggest issue I see is that you've got a loop going over the length of the string but you're not using the loop index i to reference the individual characters. In short, you're trying too hard and overlooking the obvious.
Wouldn't this do the trick?
for (int i = 0; i < letters.length(); i++) {
char letter1 = letters.charAt(0);
if (Character.isUpperCase(letter1)) {
System.out.println(Character.toLowerCase(letter1));
} else {
System.out.println(Character.toUpperCase(letter1));
}
}
The reason why you get a redundant printing 'coz you loop the three variables which already contain all characters.
To solve your problem. just remove the for loop. 'coz you already
store each character to the three variables.
You code will look like this now:
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.println(Character.toLowerCase(letter1));
else {
System.out.println(Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.println(Character.toLowerCase(letter2));
else {
System.out.println(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.println(Character.toLowerCase(letter3));
else {
System.out.println(Character.toUpperCase(letter3));
}
}
}
Ok, here is my new code. It compiled with no errors and the output was just as it was supposed to be:
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.print("Result: " + Character.toLowerCase(letter1));
else {
System.out.print("Result: " + Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.print(Character.toLowerCase(letter2));
else {
System.out.print(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.print(Character.toLowerCase(letter3));
else {
System.out.print(Character.toUpperCase(letter3));
}
}
}
The problem is that you have a loop then do each letter individually. So get rid of the loop. It would look better if you re-wrote it with a loop but only had one if/else statement inside the loop based on i not 0,1&2.
Replace your for loop with:
System.out.println(letters.toUpperCase());

Trying to write a simple compiler in java (I am using notepad++)

My question is how would I write a simple compiler ,that is like the compilers used in fax machines, that would convert something like aaaavvvvvddddddddddd to 4a5vBd.
Also, I get to "Assume" that any string entered will not contain uppercase letters and no numbers, and that any string will contain less than 61 of any type of character so, I get to assume no one will put in 64 continues a's in my program.
This is as far as I gotten
import java.util.*;
public class Program4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n;
char cn;
String word;
String numChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
System.out.println("Hello, please enter a string");
word = scan.nextln();
if(n <= 61)
{
int n = ?;
cn = numChars.charAt(n);
}
}
}
I assume I need to use a loop, but I don't know what I should use to count the repeating letters and then tell how many letters of that type are in a row. Now I am only asking for advice and not so much for code, because I want to do it but, as a beginner my Java "Vocabulary" isn't very big right now.
Any advice/ tips would be greatly appreciated.
Sincerely,
Mr.Trips
Well I am back and it appears my code here likes to only print out 147. No matter what I type in I will always get 147. I have tried to hand trace all my variables, but when I do it I get exactly what I want, and I must have some error in my logic. Any thoughts?
import java.util.*;
public class Program4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = 0;
int s = 0;
char a;
char b;
char c;
String word;
String numChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
System.out.println("Please enter a string");
word = scan.nextLine();
while (n < word.length())
{
a = word.charAt(n);
b = a;
n = n ++;
a = word.charAt(n);
if (a == b)
{
s = (s + 1) ;
}
else if (a != b);
{
c = numChars.charAt(s);
System.out.print(b + c);
s = 0;
c = 0;
break;
}
}
}
}
Thank you again!
Since you don't want code this is logically how to do it. You are right you should loop through the string for each char. Store the last char in a variable and keep a counter variable. Compare current char to last char if it is equal then increment the counter. As soon as it is not equal to the last char then add counter + last char to result string and reset counter variable. Each iteration update last char variable.

Categories