How can user input a sequence of numbers into array// Java - java

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.

Related

How to divide a string into equal groups of n characters padded with blank spaces in Java?

How to create a method that will take imput of a String and an integer n and output the String divided into parts consisting of n characters and separated by a blank space? For example, imput String: "THISISFUN", integer:3, result: "THI SIS FUN".
When you answer, can you please really try to explain what each part of the code does? I really want to understand it.
I tried using StringBuilder and the split() method but the problem is that I don't understand how all of that works. Therefore, I ended up kind of thoughtlessly pasting parts of codes from different online articles which doesn't work the best if you want to actually learn something, especially if you simply cannot find any posts about a specific issue. I could only find things like: "how to divide the String into n parts" and "how to ad a space after a specific char" which are sort of similar issues but not the same.
Here is one way to do it:
public static void splitString(String str, int groupSize){
char[] arr = str.toCharArray(); // Split the string into character array ①
// Iterate over array and print the characters
for(int i=0; i<arr.length; i++){
// If 'i' is a multiple of 'groupSize' ②
if(i > 0 && i % groupSize == 0){ ③
System.out.print(" ");
}
System.out.print(arr[i]);
}
}
① Split the string into a character array (so that you can access the characters individually). You can also do it using the charAt() method without splitting the string into an array. Read the Javadoc for more details.
② Check if the loop counter i is a multiple of groupSize
③ Note the use of System.out.print() as we do not want to print a newline. Here you can use a StringBuilder too and print the contents at the end instead of printing the characters inside the loop.

Java - getting and using the integers from an array (0-how ever many the user inputted)

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.

How can I assign numbers to characters in a string numerically without an array in Java?

So we haven't learned arrays yet in class, but we have an assignment that requires us to assign numerical values to letters. At least, we aren't told we need this, but that's the only way I can think of doing it. (Encrypting a string through shifting characters a specific way). I don't mean assign the same value for the same letter, I mean in like a "abba" string, it changes to "0123".
Thanks
Your best option then would be to use a loop. For example:
String str = "abba";
String numbers = "";
for (int i=0; i<str.length(); i++){
numbers = numbers + Integer.toString(i);
}
This way you will go through each character in str and you will create a new string of numbers with the index of each character in str. The result for numbers will be "0123" just as you requested.

Find the letter that occur most times from user with using tables [duplicate]

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.

Checking if all digits appears in another array

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.

Categories