I made this piece of code that should ask the user enter the length of first arrays that will contain how much numbers that he want, than recieving every number untill the amount is done.
after that he need to ask for the length of digits array, and than recieving the digits.
than, I need to check if all the numbers contain all the digits, if its true, print it, if not, print false.
In this code I already replace the int[] with string arrays, Because I think this is the way it whould work.
when I tried to make an Int arrays, with only single digit numbers, It works great, The problem comes when you want number like 22 with 2 digits, the checking breaks and not working.
String numInNumbersArray,
digitInDigitsArray;
int counterNumbers=0;
System.out.println("Please enter the length of the numbers array: ");
int numbersLength=s.nextInt();
String[] numbersArray=new String [numbersLength];
System.out.printf("Please enter %d numbers: ",numbersLength);
for(int i=0;i<numbersArray.length;i++){
numInNumbersArray=s.next();
numbersArray[i]=numInNumbersArray;
}
System.out.println("Please enter the length of the digits array: ");
int digitsLength=s.nextInt();
String[] digitsArray=new String [digitsLength];
System.out.printf("Please enter %d digits between 0 - 9 and - if you want: ",digitsLength);
for(int i=0;i<digitsArray.length;i++){
digitInDigitsArray=s.next();
digitsArray[i]=digitInDigitsArray;
}
for(int i=0;i<digitsArray.length;i++){
for(int j=0;j<numbersArray.length;j++){
if(numbersArray[j].equals(digitsArray[i])){
counterNumbers++;
}
}
}
if(counterNumbers==numbersArray.length){
System.out.println("true\n");
}else{
System.out.println("false\n");
}
So I obviously need a String array, But I have no idea how to continue from here to check every digit from a number. ( I cannot use advanced methods, Only simple checks).
Your help or tuning would be great. thanks.
EDIT: It must be string because it also maight contain '-' (negetive numbers)
to make it more clealry to understand I will add examples:
digits arrays for example : (1,2,-,3)
and numbers array : (1,-2,3)
this should return true.
and digits: (1,2,3)
numbers: (12,-3,123)
should return false.
You problem lies within your check to see if the arrays are equals.
Imagine if numbersArray = {"2", "2"} and digitsArray = {"2", "2"} like you stated above.
This loop:
for(int i=0;i<digitsArray.length;i++){
for(int j=0;j<numbersArray.length;j++){
if(numbersArray[j].equals(digitsArray[i])){
counterNumbers++;
}
}
}
will compare the first "2" - numbersArray[0] with digitsArray[0] AND digitsArray[1], making counterNumbers = 2. Then, the first for loop will process to i=1, where it will come the second "2" - numbersArray[1] with digitsArray[0] AND digitsArray[1] making counterNumbers = 4.
Do you see your fault here?
Here is a hint, you should be comparing each array "digit-by-digit" rather than comparing the first "digit" in numbersArray to all of the "digits" in digitsArray. NOTE: This hint is only useful if you have each array (numbersArray and digitsArray) in the same order. You should look into sorting them to ensure that.
Since this seems like a homework assignment i'll stop here and let you try to fix it yourself.
Related
so i've been trying to do this one thing which is letting user input his sequence number into array. I mean f.e. if he wanted to input 9901229976 and 9 would be Array[0], another 9 would be array[1], 0 would be array [2] and so on and so on, i've tried many things and didin't come up with the answer, i'm totally stuck with that, if the answer is so obvious i'm really, but i need answer as it is my project:(
This is how you would do it:
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
int[] array = new int[input.length()];
for(int i = 0; i < input.length(); i++){
array[i] = Integer.parseInt(Character.toString(input.charAt(i)));
}
String.charAt(int position) gets the Character located at a
certain position in the String.
Character.toString(Characters ch)
converts a Character to a String.
Integer.parseInt(String s) converts a String to an Integer.
So, what the code does is it goes through each character in the string, converts that character to a String, and then uses the Integer.parseInt() method in order to get that original character as a number.
array is now an array of the digits of the number that the user inputted. This should answer your question.
My program requires an input of as many integers as the user wishes on a SINGLE line. My program must then, take the first integer the user entered decide if it is in the range or not. If NOT output error, If YES then do specified conversion. THEN move to the SECOND integer entered by the user (if there is one).
The way I have tackled this so far is this...
System.out.print("Enter a digit(s). ");
//Gets input numbers and stores them as a whole string
//e.g if enters 1 2 3 input will = "1 2 3"
String input = kbd.nextLine();
//Splits the input at every space and stores them in an array
//e.g If input = "1 2 3", numbers {"1", "2", "3"}
String[] numbersString = input.split(" ");
//Creates an array the same length as our String array
//How we will store each number as an integer instead of a string
int[] numbers = new int[numbersString.length];
//a loop that goes through the array as a string
for ( int i = 0; i < numbersString.length; i++ )
{
// Turns every value in the numbersString array into an integer
// and puts it into the numbers array.
numbers[i] = Integer.parseInt(numbersString[i]);
}
My problem is that I don't know how to GET the first integer entered and then on to the second and so on... (I DONT UNDERSTAND HOW to access the array of integers ive obtained from the user and manipulate them from 1 - how ever many entered.
You access the array in a similar way to how you built it. For example, to print out the array, you can do this:
for ( int i = 0; i < numbers.length; i++ )
{
System.out.println(numbers[i]);
}
Note how the for loop is nearly identical to the last for loop in the code you posted. The only difference is numbers.length since you want to iterate over the numbers array.
You should also take the time to learn about the enhanced for loop which makes iterating over an array much easier.
What about something like this:
for(int number : numbers) //iterates through each number in the array of numbers
{
if(number > 4 && number < 10) //or whatever range you wanted
{
number *= 2; //or whatever conversion you wanted
System.out.println(number);
}
}
This uses an enhanced for loop as mentioned in comment above. The variable number (singular) is each int in your array of numbers.
I am currently a early CS student and have begun to start projects outside of class just to gain more experience. I thought I would try and design a calculator.
However, instead of using prompts like "Input a number" etc. I wanted to design one that would take an input of for example "1+2+3" and then output the answer.
I have made some progress, but I am stuck on how to make the calculator more flexible.
Scanner userInput = new Scanner(System.in);
String tempString = userInput.nextLine();
String calcString[] = tempString.split("");
Here, I take the user's input, 1+2+3 as a String that is then stored in tempString. I then split it and put it into the calcString array.
This works out fine, I get "1+2+3" when printing out all elements of calcString[].
for (i = 0; i <= calcString.length; i += 2) {
calcIntegers[i] = Integer.parseInt(calcString[i]);
}
I then convert the integer parts of calcString[] to actual integers by putting them into a integer array.
This gives me "1 0 2 0 3", where the zeroes are where the operators should eventually be.
if (calcString[1].equals("+") && calcString[3].equals("+")) {
int retVal = calcIntegers[0] + calcIntegers[2] + calcIntegers[4];
System.out.print(retVal);
}
This is where I am kind of stuck. This works out fine, but obviously isn't very flexible, as it doesn't account for multiple operators at the same like 1 / 2 * 3 - 4.
Furthermore, I'm not sure how to expand the calculator to take in longer lines. I have noticed a pattern where the even elements will contain numbers, and then odd elements contain the operators. However, I'm not sure how to implement this so that it will convert all even elements to their integer counterparts, and all the odd elements to their actual operators, then combine the two.
Hopefully you guys can throw me some tips or hints to help me with this! Thanks for your time, sorry for the somewhat long question.
Create the string to hold the expression :
String expr = "1 + 2 / 3 * 4"; //or something else
Use the String method .split() :
String tokens = expr.split(" ");
for loop through the tokens array and if you encounter a number add it to a stack. If you encounter an operator AND there are two numbers on the stack, pop them off and operate on them and then push back to the stack. Keep looping until no more tokens are available. At the end, there will only be one number left on the stack and that is the answer.
The "stack" in java can be represented by an ArrayList and you can add() to push items onto the stack and then you can use list.get(list.size()-1); list.remove(list.size()-1) as the pop.
You are taking input from user and it can be 2 digit number too.
so
for (i = 0; i <= calcString.length; i += 2) {
calcIntegers[i] = Integer.parseInt(calcString[i]);
}
will not work for 2 digit number as your modification is i+=2.
Better way to check for range of number for each char present in string. You can use condition based ASCII values.
Since you have separated your entire input into strings, what you should do is check where the operations appear in your calcString array.
You can use this regex to check if any particular String is an operation:
Pattern.matches("[+-[*/]]",operation )
where operation is a String value in calcString
Use this check to seperate values and operations, by first checking if any elements qualify this check. Then club together the values that do not qualify.
For example,
If user inputs
4*51/6-3
You should find that calcString[1],calcString[4] and calcString[6] are operations.
Then you should find the values you need to perform operations on by consolidating neighboring digits that are not separated by operations. In the above example, you must consolidate calcString[2] and calcString[3]
To consolidate such digits you can use a function like the following:
public int consolidate(int startPosition, int endPosition, ArrayList list)
{
int number = list.get(endPosition);
int power = 10;
for(int i=endPosition-1; i>=startPosition; i--)
{
number = number + (power*(list.get(i)));
power*=10;
}
return number;
}
where startPosition is the position where you encounter the first digit in the list, or immediately following an operation,
and endPosition is the last position in the list till which you have not encountered another operation.
Your ArrayList containing user input must also be passed as an input here!
In the example above you can consolidate calcString[2] and calcString[3] by calling:
consolidate(2,3,calcString)
Remember to verify that only integers exist between the mentioned positions in calcString!
REMEMBER!
You should account for a situation where the user enters multiple operations consecutively.
You need a priority processing algorithm based on the BODMAS (Bracket of, Division, Multiplication, Addition and Subtraction) or other mathematical rule of your preference.
Remember to specify that your program handles only +, -, * and /. And not power, root, etc. functions.
Take care of the data structures you are using according to the range of inputs you are expecting. A Java int will handle values in the range of +/- 2,147,483,647!
This question already has answers here:
Java program to find the character that appears the most number of times in a String?
(8 answers)
Closed 6 years ago.
I got a task from my university today:
Write a program that reads a ( short ) text from the user and prints the so called max letter (most common character in string) , that the letter which the greatest number of occurrences of the given text .
Here it is enough to look at English letters (A- Z) , and not differentiate between uppercase and lowercase letters in the count of the number of occurrences .
For example, if : text = " Ada bada " so should the print show the most common character, this example it would be a.
This is an introductory course, so in this submission we do not need to use the " scanner - class" . We have not gone through this so much.
The program will use the show message input two get the text from user .
Info: The program shall not use while loop ( true / false ) , "return " statement / "break " statement .
I've been struggling with how I can get char values into a table.. am I correct I need to use array to search for most common character? I think I need to use the binarySearch, but that only supports int not char.
I'll be happy for any answers. hint's and solutions. etc.. if you're very kind a full working program, but again please don't use the things I have written down in the "info" section above.
My code:
String text = showInputDialog("Write a short text: ");
//format string to char
String a = text;
char c = a.charAt(4);
/*with this layout it collects number 4 character in the text and print out.
* I could as always go with many char c... but that wouldn't be a clean program * code.. I think I need to make it into a for-loop.. I have only worked with * *for-loops with numbers, not char (letters).. Help? :)
*/
out.print( text + "\n" + c)
//each letter into 1 char, into table
//search for most used letter
Here's the common logic:
split your string into chars
loop over the chars
store the occurrences in a hash, putting the letter as key and occurrences as value
return the highest value in the hash
As how to split string into chars, etc., you can use Google. :)
Here's a similar question.
There's a common program asked to write in schools to calculate the frequency of a letter in a given String. The only thing you gotta do here is find which letter has the maximum frequency. Here's a code that illustrates it:
String s <--- value entered by user
char max_alpha=' '; int max_freq=0, ct=0;
char c;
for(int i=0;i<s.length();i++){
c=s.charAt(i);
if((c>='a'&&c<='z')||(c>='A'&&c<='Z')){
for(int j=0;j<s.length();j++){
if(s.charAt(j)==c)
ct++;
} //for j
}
if(ct>max_freq){
max_freq=ct;
max_alpha=c;
}
ct=0;
s=s.replace(c,'*');
}
System.out.println("Letter appearing maximum times is "+max_alpha);
System.out.println(max_alpha+" appears "+max_freq+" times");
NOTE: This program presumes that all characters in the string are in the same case, i.e., uppercase or lowercase. You can convert the string to a particular case just after getting the input.
I guess this is not a good assigment, if you are unsure about how to start. I wish you for having better teachers!
So you have a text, as:
String text = showInputDialog("Write a short text: ");
The next thing is to have a loop which goes trough each letter of this text, and gets each char of it:
for (int i=0;i<text.length();i++) {
char c=text.charAt(i);
}
Then comes the calculation. The easiest thing is to use a hashMap. I am unsure if this is a good topic for a beginners course, so I guess a more beginner friendly solution would be a better fit.
Make an array of integers - this is the "table" you are referring to.
Each item in the array will correspond to the occurrance of one letter, e.g. histogram[0] will count how many "A", histogram[1] will count how many "B" you have found.
int[] histogram = new int[26]; // assume English alphabet only
for (int i=0;i<histogram.length;i++) {
histogram[i]=0;
}
for (int i=0;i<text.length();i++) {
char c=Character.toUppercase(text.charAt(i));
if ((c>=65) && (c<=90)) {
// it is a letter, histogram[0] contains occurrences of "A", etc.
histogram[c-65]=histogram[c-65]+1;
}
}
Then finally find the biggest occurrence with a for loop...
int candidate=0;
int max=0;
for (int i=0;i<histogram.length;i++) {
if (histogram[i]>max) {
// this has higher occurrence than our previous candidate
max=histogram[i];
candidate=i; // this is the index of char, i.e. 0 if A has the max occurrence
}
}
And print the result:
System.out.println(Character.toString((char)(candidate+65));
Note how messy this all comes as we use ASCII codes, and only letters... Not to mention that this solution does not work at all for non-English texts.
If you have the power of generics and hashmaps, and know some more string functions, this mess can be simplified as:
String text = showInputDialog("Write a short text: ");
Map<Char,Integer> histogram=new HashMap<Char,Integer>();
for (int i=0;i<text.length();i++) {
char c=text.toUppercase().charAt(i));
if (histogram.containsKey(c)) {
// we know this letter, increment its occurrence
int occurrence=histogram.get(c);
histogram.put(c,occurrence+1);
}
else {
// we dunno this letter yet, it is the first occurrence
histogram.put(c,1);
}
}
char candidate=' ';
int max=0;
for (Char c:histogram.keySet()) {
if (histogram.get(c)>max) {
// this has higher occurrence than our previous candidate
max=histogram.get(c);
candidate=c; // this is the char itself
}
}
System.out.println(c);
small print: i didn't run this code but it shall be ok.
I'm working on a program for a class and was wondering if someone could point me in the right direction. I've worked with Java before, but it's been a while and I'm really rusty. The purpose of this program is to prompt a user to enter a phone number represented by letters (for example CALL HOME would be 225-5466), the program is then to display the phone number based on the letters entered.
We are supposed to store the letters entered by the user into an array and then convert those letters into the actual phone number. Here's what I'm getting stuck on at the moment, I've only worked with arrays consisting of numbers so am not sure how to set this one up. I'm assuming that each index would be one letter, but how would I break the string entered by the user down into individual char characters?
I'm still in the process of thinking through how this program should work and putting it on paper so haven't actually started coding yet, so I apologize for not having any code to share. But this is what I'm thinking would need to happen once the letter representation of the phone numbers were placed in the array:
Declare variables for each letter, like
int a = 1
int b = 1
int c = 1
int d = 2
etc. Or is there a more efficient way to do that? Then use if statements for each index like,
if [0] == a || b || c
[0] = 1
if [0] == d || e || f
[0] = 2
and so on. Like I said, I'm really rusty and am just trying to think my way through this right now before just throwing code at the screen haha. Any pointers would be much appreciated.
Just use String#toCharArray:
char[] characters = string.toCharArray();
You can then get the individual characters from a string.
You could use a series of if statements to see what characters map to what number. But there are more-elegant approaches. I am not sure if you have used Map<K, V>, but you could set up a Map<String, Integer> that maps a letter to its integer representation. Then you'd simply have to iterate over the characters in the string and look up their value.
Since this is homework, this is about as much information that I think is appropriate. Using what I have given you, you should be able to come up with an algorithm. Just start writing the code even if you don't know what the end result will look like. This will give you the following advantages:
Give you a clearer idea of the problem.
Will familiarize you with the problem-space.
Will help you visualize and understand your problem and the algorithm.
What you can do is to create a 2 dimensional array and methods to check the input against it. For example you can do the following:
Create an array numbers of length 10. Each index corresponds to a number you have to call.
Now each entry of the numbers array is an array of chars. So in the end you have something like this :
numbers = [['w/e you want for 0'],['a','b','c'],['d','e','f'], ['g','h','i'], ... etc ]
When you parse the input string you compare each character with a method like this:
private int letterToNumber(char c){
for(i = 0; i < numbers.length; i++)
if(contains(numbers[i], c) return i;
}
and your contains() method should be something like that
private boolean contains(char[] chars, char c){
for(char x : chars)
return(x == c)? true; false;
}