writing and reading numbers from text file using java - java

Basically I'm trying to write a program that will write 6 numbers at a time, keep adding to this file each time I save the numbers. After that I would like to read the text file, pick the numbers that come up more then a say 5 times or more (whatever I specify).
Question is this I guess, if I read in each line as a string, will I still be able to step through each number to figure out which ones have been entered more then 5 or more times or would I have to read them one at a time as a char?

You can read lines as string and then covert that string to char array.
Here is example:
String line = "12345";
char[] charArray = line.toCharArray();
for(char ch : charArray)
{
int nummber = (int)ch;
}

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.

How can user input a sequence of numbers into array// 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.

Getting integers seperatly from a string and giving directions to a robot

I am working on a project which involves making a "worker" in java which receives instructions from an input string. In the input string normally should be first four numbers and then afterwards a number and a letter right after being N,S,W, or E. The first 2 numbers in the list are used to determine the size of the area this worker can walk. the next two numbers are the starting point for the worker. The number with the letter determines what direction the worker walks and how many paces. The problem I am having is I don't understand how to get the first four digits out of the string and separate them into what they each should be.
import java.util.*;
import java.io.*;
public class Worker {
private int height;
public void readInstructions(String inputFileName, String outputFileName) throws InvalidWorkerInstructionException{
try{
Scanner in = new Scanner(inputFileName);
PrintWriter wrt;
wrt = new PrintWriter(outputFileName);
if(inputFileName.startsWith("i")){
System.out.println("Input file not found.");
//wrt.println("Input file not found.");
}
while(in.hasNext()){
String s = in.nextLine();
if(Integer.parseInt(s)<= 9){
}
}
}catch(InvalidWorkerInstructionException e){
}catch(FileNotFoundException e){
}
While I would love to ask for a straight up answer, this is a project so I would prefer nobody gives me a fixed code. Please if you can give me advice for what I am doing wrong and where I should be going to solve the problem.
Ok I realized one other thing because I tried the advice given. So I am receiving a string that gives me the name of an input txt. Inside that input txt is the numbers and directions. How can i access this text file? Also how do I determine if it can be opened?
Okay, so you already know how to read the file using a Scanner. All you need to do next is split the String and extract the first four inputs out of it.
Here is the code snippet:
String s = in.nextLine();
int i = 0, digits[] = new int[4];
for(String inp : s.splits(" ")) {
if(i == 4) break;
digits[i++] = Integer.parseInt(inp);
}
Note: I'm assuming that the inputs in your file is space separated. If not then you can replace the space in the split() with the correct delimiter.
If input format is fixed than you can use substring method to get different parts of string. Refer documentation for more detail:
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)
Example code:
String s = "12345E";
s.substring(0, 2); /* 12 */
s.substring(2, 4); /* 34 */
s.substring(4, 5); /* 5 */
s.substring(5, 6); /* E */
You can use the method .getChars() to accomplish this. Here is what the javadoc says about this method:
public void getChars(int srcBegin,
int srcEnd,
char[] dst,
int dstBegin)
Copies characters from this string into the destination character array.
The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1 (thus the total number of characters to be copied is srcEnd-srcBegin). The characters are copied into the subarray of dst starting at index dstBegin and ending at index:
dstbegin + (srcEnd-srcBegin) - 1
Parameters:
srcBegin - index of the first character in the string to copy.
srcEnd - index after the last character in the string to copy.
dst - the destination array.
dstBegin - the start offset in the destination array.
Throws:
IndexOutOfBoundsException - If any of the following is true:
srcBegin is negative.
srcBegin is greater than srcEnd
srcEnd is greater than the length of this string
dstBegin is negative
dstBegin+(srcEnd-srcBegin) is larger than dst.lengt....
Here is what you could do...
You read in the string - grab its length (You want to make sure that it has all the chars you need)
Read in to a separate array discarding any extraneous chars that are not needed for this functionality..
You can make your own pseudo code to work out the problem once the string is split into an array. Very easy to work with since you know what each location of the array is supposed to do.
This is not a hard problem to solve at all..
Good luck on your project.

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.

string index out of range exception

I'm looking for help correcting an exception error for 'string index out of range'. My code is supposed to take two strings as input from the user(string1 and string2) and create new strings that are parts of the originals.
So far I have the following:
modString1 = string1.substring(string1.length() -3, string1.length());
modString2 = string2.substring(0,3);
The above code is supposed to take the last 3 characters of string1 and the first 3 characters of string2. The problem I am having comes when the user inputs a string that is shorter than 3 characters.
I'm wondering if there is a way to check the input and add a character (x for example) if the string is too short?
For example, if the user enters 'A' for the first string it will change the string to 'xxA' and if 'A' is entered for the second string it will change that to 'Axx'?
Put an if statement before your code, checking the length of the string before you process it.
For example:
if(string1.length() < 3) {
// Add characters to the string
}
I'm wondering if there is a way to check the input and add a character (x for example) if the string is too short?
What you are looking for is called padding.
It can be done in a number of ways. The simplest is probably to use an external library such as Apache's StringUtils. You could also write a padding method yourself using a StringBuilder.
Related:
How can I pad a String in Java?
put the validation like below and add the string.
For ex.
if(string1.length()<3){
String op = 'xx';
string1 += op;
}

Categories