Why does my program keep looking for inputs? - java

This code is in Java. It allows me to enter the first input fine, but after the second is inputted it keeps looking for more strings, none of the rest of my code follows. Idealy the code will find if 2 strings are anagrams, but I have not been able to test this due to this annoying problem.
import java.util.*;
public class Anagram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a word");
String first = scan.nextLine();
System.out.println("Please enter a second word");
String second = scan.next();
first = first.toLowerCase();
second = second.toLowerCase();
int lengthF = first.length();
int lengthS = first.length();
int x = 0;
int y = 0;
int placeF=0;
int placeS=0;
char g = 97;
int count =0;
if(lengthF != lengthS)
{
System.out.println("The words are not anagrams");
x=1;
}
while(x == y||g<123)
{
x=0;
y=0;
for(int i = 0;i<lengthF;i++)
{
if(first.charAt(i)==g)
{
x++;
}
}
for(int i = 0;i<lengthS;i++)
{
if(second.charAt(i)==g)
{
y++;
}
}
count++;
g++;
}
if(count==23)
System.out.println("Anagram");
else
System.out.println("Not Anagram");
}
}

I've spotted three bugs in your code, which you can easily find by yourself if you always follow these general rules for programming:
Never use numbers obscurely. Write them in a way that explains where that value comes from: Instead of:
char g=97;
... let it be:
char g='a';
And the same goes for every single "special" number in your program: 97, 123 and 23 (In this way you'll see 23 is wrong).
Indexed loops should be always for, with its initial value, its ongoing condition and its increment operation. Ongoing condition must be the index interval condition, plus optional secondary conditions combined by AND operators.
And the third bug... Well, right now I cannot think of any general rule to avoid it. It must have been a copy-and-paste issue: The variable lengthS is wrongly initialized.
Also, I recommend you not to code the same algorithm more than once: Take it out to an individual function and reuse it. So you can do with the loop that counts the number of occurrences of a certain char within a certain string. You could define it like this:
private static int countOccurrencesOfChar(String s, char c) {...}

Related

Show Characters shared between two strings

For a Java exercise I'm writing a program where the user enters two strings. The program then checks to see if the two strings share any similar characters and outputs them to the screen.
For example is Terrarium and Terraform are the two strings it should print t e r r a r. However when I run my program it always simply outputs all the characters in the first string. (In this case T e r r a f o r m.)
I suspect I'm creating a logical error based on a limited understanding of loops. But when I search for answers people seem to always use a similar method to my own.
Here is the code for your viewing:
import java.util.Scanner;
public class CountMatches
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println(" Please enter a String >> ");
String stringA = keyboard.nextLine();
System.out.println(" Please enter another String >> ");
String stringB = keyboard.nextLine();
for(int counter = 0; counter < stringA.length(); counter++ )
{
char compareA = stringA.charAt(counter);
char compareB = stringB.charAt(counter);
//System.out.println(compareA);
//System.out.println(compareB);
//System.out.println("");
if(compareA != compareB)
{
System.out.println("");
}
else if(compareA == compareB);
{
System.out.println(compareA);
System.out.println("");
}
}
}
}
else if(compareA == compareB);
Get rid of the semicolon on this line and it should work. I would also get rid of the first if statement just keep the second one.
You have two problems with this code.
First,
for(int counter = 0; counter < stringA.length(); counter++ )
If the two string are of different length, you could get an exception by going off the end of the other string. So, do this:
int len = stringA.length();
if (len > stringB.lengh()) len = stringB.length();
Next, the reason you code fails is because you have a ; at the end of your else. Your code should be:
if(compareA != compareB)
{
System.out.println("");
}
else // Don't need the == here
{
System.out.println(compareA);
System.out.println("");
}
Good luck with this.

How to use for loop to input 10 numbers and print only the positives?

I'm trying to make a "for" loop in which it asks the user to input 10 numbers and then only print the positives.
Having trouble controlling the amount of inputs. I keep getting infinite inputs until I add a negative number.
import java.util.Scanner;
public class ej1 {
public static void main(String args[]) {
int x;
for (x = 1; x >= 0; ) {
Scanner input = new Scanner(System.in);
System.out.print("Type a number: ");
x = input.nextInt();
}
}
}
From a syntax point of view, you've got several problems with this code.
The statement for (x = 1; x >= 0; ) will always loop, since x will always be larger than 0, specifically because you're not introducing any kind of condition in which you decrement x.
You're redeclaring the scanner over and over again. You should only declare it once, outside of the loop. You can reuse it as many times as you need.
You're going to want to use nextLine() after nextInt() to avoid some weird issues with the scanner.
Alternatively, you could use nextLine() and parse the line with Integer.parseInt.
That said, there are several ways to control this. Using a for loop is one approach, but things get finicky if you want to be sure that you only ever print out ten positive numbers, regardless of how many negative numbers are entered. With that, I propose using a while loop instead:
int i = 0;
Scanner scanner = new Scanner(System.in);
while(i < 10) {
System.out.print("Enter a value: ");
int value = scanner.nextInt();
scanner.nextLine();
if (value > 0) {
System.out.println("\nPositive value: " + value);
i++;
}
}
If you need to only enter in ten values, then move the increment statement outside of the if statement.
i++;
if (value > 0) {
System.out.println("\nPositive value: " + value);
}
As a hint: if you wanted to store the positive values for later reference, then you would have to use some sort of data structure to hold them in - like an array.
int[] positiveValues = new int[10];
You'd only ever add values to this particular array if the value read in was positive, and you could print them at the end all at once:
// at the top, import java.util.Arrays
System.out.println(Arrays.toString(positiveValues));
...or with a loop:
for(int i = 0; i < positiveValues.length; i++) {
System.out.println(positiveValues[i]);
}
Scanner scan = new Scanner(System.in);
int input=-1;
for(int i=0;i<10;i++)
{
input = sc.nextInt();
if(input>0)
System.out.println(input);
}

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.

Find occurrence of a digit in a number

I am writing a program in which user will enter a digit a and find the number of times a will occur in another number b entered by the user.
import java.util.Scanner;
class Number
{
public static void main(String args[])
{
System.out.println("Enter the digit to match");
Scanner s=new Scanner(System.in);
int a=s.nextInt(); //Digit whose occurrence is to find
System.out.println("Enter the number to match");
int b=s.nextInt(); //Number in which occurrence is to find
int ctr=0;
int ctr1=0;
while(b!=0) //Number of digits in the entered number
{
b/=10;
ctr++;
}
int arr[]=new int[ctr];
for(int i=0;i<ctr;i++) //Breaking the number into array of digits
{
arr[i]=b%10;
b/=10;
if(arr[i]==a)
{
ctr1++;
}
}
System.out.println("Number of occurrences are " +ctr1);
}
}
Each and every time the output is 0. Where I am wrong?
after executing this cycle
while(b!=0) //Number of digits in the entered number
{
b/=10;
ctr++;
}
b becomes 0 and thus it contains no digit but 0.
You need to store the value of b in some variable and re-initialize it after this cycle and before iterating over the digits. Alternatively use only a single cycle of the first type - you don't actually use the number of digits anywhere.
EDIT: another approach would be to convert the number to string and then use lastIndexOf on it to find where the given digit is found. The performance will be a bit worse, but the code will be easier to understand(and shorter).
Something in the lines of:
int count=0;
char a = (char)(47 + s.nextInt());
char[] b = s.nextInt().ToString().ToCharArray();
for(int i=0; i < b.lenght(); i++)
{
if(b[i]==a)
{
count++;
}
}
One basic error that I can find is that you have modified b to get the number of digits and so you can not get the individual bits from that now.
Try copying it into a separate variable before modifying the value of b.
When this is executed, b is always 0.
arr[i]=b%10;

Fibonacci Riddle almost right in need of a quick fix and an easy solve

Help I have a puzzle that needs solved!
I made a Fibonacci series but I forgot to include the 0
Who can help me solve this riddle?
If the input is five in the sequence the output should be 0,1,1,2,3
What should I change to clean up the code and get the desired result without completely starting from scratch?
//Class Assignment 9 little Fibonacci series based on what input
//the user provides
import java.util.Scanner;
public class LittleFibonacci {
int number;// This declares an int variable
public static void main(String[] args){
//itnu is the new object
LittleFibonacci itnu = new LittleFibonacci ();
itnu.GetNumberInput();
}
public void GetNumberInput()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a number and that number will be a" +
" \nrepresentitive of the length of a sequence in the Fibonocci series.");
number = input.nextInt();
int f1, f2=0, f3=1;
for(int i = 1 ; i <= number ; i++ )
{
System.out.print(" "+f3+" ");
f1 = f2;
f2 = f3;
f3 = f1 + f2;
}
input.close();
}
}
Just start your loop at zero instead of one, and change the initializations of {f1,f2,f3} accordingly (left as an exercise for the reader).
The other solutions here that tell you to output zero first are basically cheating. You might as well just hard-code all the Fibonacci numbers. You won't get any marks for doing that.
Add
System.out.print(" "+f2+" ");
before the for loop. Change the for loop terminating condition to <.
I guess to be really completist we should also check that the user does not enter 0 (or a negative number) and not even print f2 in that case.
This may seem slightly "unclean" but the fibonacci sequence has two starting numbers, they are special and need special treatment.
the approach I would take, is to print your base cases first, and then reset them after each iteration
int fPrev = 0, fCur = 1;
System.out.print(fPrev+" "+fCur);
for(int i = 2 ; i <= number ; i++ )
{
int fNew = fPrev + fCur
System.out.print(" "+fNew);
fPrev = fCur;
fCur = fNew;
}

Categories