question on transferring codes, what method should I use? - java

Question explaination: as some of the comments suggested, I will try my best to make this question clearer. The inputs are from a file and the code is just one example. Supposedly the code should work for any inputs in the format. I understand that I need to use Scanner to read the file. The question would be what code do I use to get to the output.
Input Specification:
The first line of input contains the number N, which is the number of lines that follow. The next
N lines will contain at least one and at most 80 characters, none of which are spaces.
Output Specification:
Output will be N lines. Line i of the output will be the encoding of the line i + 1 of the input.
The encoding of a line will be a sequence of pairs, separated by a space, where each pair is an
integer (representing the number of times the character appears consecutively) followed by a space,
followed by the character.
Sample Input
4
+++===!!!!
777777......TTTTTTTTTTTT
(AABBC)
3.1415555
Output for Sample Input
3 + 3 = 4 !
6 7 6 . 12 T
1 ( 2 A 2 B 1 C 1 )
1 3 1 . 1 1 1 4 1 1 4 5
I have only posted two questions so far, and I don't quite understand the standard of a "good" question and a "bad" question? Can someone explain why this is a bad question? Appreciate it!

Complete working code here try it.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CharTask {
public static void main(String[] args) {
List<String> lines = null;
try {
File file = new File("inp.txt");
FileInputStream ins =new FileInputStream(file);
Scanner scanner = new Scanner(ins);
lines = new ArrayList<String>();
while(scanner.hasNext()) {
lines.add(scanner.nextLine());
}
List<String> output = processInput(lines);
for (int i=1;i<output.size(); i++) {
System.out.println(output.get(i));
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static List<String> processInput(List<String> lines){
List<String> output = new ArrayList<String>();
for (String line: lines) {
output.add(getProcessLine(line));
}
return output;
}
private static String getProcessLine(String line) {
if(line.length() == 0) {
return null;
}
String output = "";
char prev = line.charAt(0);
int count = 1;
for(int i=1;i<line.length();i++) {
char c = line.charAt(i);
if (c == prev) {
count = count +1;
}
else {
output = output + " "+count + " "+prev;
prev = c;
count = 1;
}
}
output = output + " "+count+" "+prev;
return output;
}
}
Input
(inp.txt)
4
+++===!!!!
777777......TTTTTTTTTTTT
(AABBC)
3.1415555
Output
3 + 3 = 4 !
6 7 6 . 12 T
1 ( 2 A 2 B 1 C 1 )
1 3 1 . 1 1 1 4 1 1 4 5

There are two different problems you need to address, and I think it is going to help you to address them separately. The first is to read in the input. It's not clear to me whether you are going to prompt for it and whether it is coming from the console or a file or what exactly. For that you will want to initialize a scanner, use nextInt to get the number of lines, call nextLine() to clear the rest of that line and then run a for loop from 0 up to the number of lines, reading the next line (using nextLine()) into a String variable. To make sure that is working well, I would suggest printing out the unaltered string and see if what is coming out is what is going in.
The other task is to convert a given input String into the desired output String. You can work on that independently, then pull things back together later. You will want a method that takes in a string and returns a string. You can test it by passing the sample Strings and seeing if it gives you back the desired output strings. Set the result="". Looping over the characters in the String using charAt, it will want variables for the currentCharacter and currentCount, and when the character changes or the end of the string is encountered, concatenate the number and character onto the string and reset the character count and current character as needed. Outside the loop, return the result.
Once the two tasks are solved, pull them together by printing out what the method returns for the input string as opposed to the input string itself.
I think that gives you direction on the method to use. It's not a full-blown solution, but that's not what you requested or needed.

Related

Why do I get NumberFormatException while converting String Array to int Array?

I do not get the Error when I run my code on IntelliJ. However, when I try to hand in my Code for the assignement Im working on, I get NFE for both test cases. I deleted all of my Code and let only the bellow code run through the test cases. Somewhere in here must be a NumberFormatException.
public class Search {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
int[] list = new int[n];
String [] tokens = sc.nextLine().trim().split(" ");
for (int i=0; i<tokens.length;i++){
list[i]=Integer.parseInt(tokens[i]);
}
}
}
I read about double spaces and checked this with: System.out.println(Arrays.asList(tokens).contains(""));
Output was false so this is not an option. As you can see I'm already using trim().
I'd appreciate your help.
Louis
Eddit:
Alright something is fishy here. I added
System.out.println(Arrays.asList(tokens).contains(""));
System.out.println(Arrays.toString(tokens));
To my Code and handed it in to the test cases. While IntelliJ would deliver false followed by an array of integers, the test case outputs:
true
[]
.
Therefore you all are right and I just falsely assumed that the input in my test cases would be similar to the example Input I was given in the assignment.
Edit2:
ALRIGHT!
I figured it out. The Input of the test cases was simply not the same format as the one in my test Input which looked a bit like this:
10
8 8 9 12 110 111 117 186 298 321
2
8 13
I assume that the sc.nextLine() that I included skipped integers that I needed to make my list.
So the actual problem was not that extra spaces or anything, it was simply that I advanced past the input I wanted through my usage of sc.nextLine().
The answer that gave me the hint I needed, even tho I dont think this was intended came from Andronicus.
Thanks to everybody else anyways.
If you know, that there is going to be an integer as an input and you're not worried about parsing, why not using this instead?
int input = sc.nextInt();
In your solution you would have to do:
Arrays.stream(sc.nextLine().trim().split(" ")).filter(s -> !s.matches("\\s")).toArray(String[]::new);
\\ or simplier
sc.nextLine().trim().split("\\s+")
There's a number of possible causes:
There's a non-number in tokens -- eg. 9 1! 3 x 3 ...
The tokens are split by more than one space -- eg 9 3
You should be able to tell by the text of the Number Format Exception. For example, in the case of multiple spaces, you'd get:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
And for non-numbers (eg "a"), you'd get:
Exception in thread "main" java.lang.NumberFormatException: For input string: "a"
There are, of course, numerous possible solutions depending on what you want to do when you run into invalid input (do you ignore it? throw a special exception? try to strip out non-numbers?)
When you know your inputs are separated by whitespace, but don't know how much white-space, you can use a regular expression to target multiple whitespaces in your split command:
str.split("\\s+"); // splits on one or more whitespace including tabs, newlines, etc.
Then, to handle non-digits in your token list, you can add a check in your for-loop:
for(int i = 0; i < tokens.length; i++) {
if(tokens[i].matches("\\d+")) {
list[i] = Integer.parseInt(tokens[i]);
} else {
// Handle error case for non-digit input
}
}
It is likely due to the extra bunch of spaces between the numbers.
For Example,
9 8 7 9 1
^^ ^^
*Note: You have more than one spaces here.
This is how your array will look after splitting,
tokens = {"9", "", "", "", "8", "7", "9", "", "", "", "1"}
Above will throw the NumberFormatException because of extra spaces.
You can try trimming the contents again,
int i = 0;
for (String token : tokens){
token = token.trim();
if (!"".equals(token)) {
list[i++] = Integer.parseInt(token);
}
}
Please modify your code to this :
public class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array : ");
int n = sc.nextInt();
sc.nextLine();
int[] list = new int[n];
System.out.println("Enter a string : ");
/** This regex will work for string having more than one space. */
String trimmedToken = sc.nextLine().replaceAll("\\s+", " ");
String[] tokens = trimmedToken.split(" ");
for (int i = 0; i < tokens.length; i++) {
list[i] = Integer.parseInt(tokens[i]);
System.out.println(list[i]);
}
sc.close();
}
}
Console Input :
Enter the size of the array :
5
Enter a string :
1 2 3 4 5
Output :
1
2
3
4
5

How do I read a single text file and have the values placed into a cookie cutter sentence format?

Here's the content of the text file:
1 2 3 4 5 6 7 8 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
I want it to read and print out like this
The number ____ was at 00:00.
The number ____ was at 01:00.
and so on...
Here is what I have so far. I have found a lot about reading a .txt file but not much with how to take the info and format it in such a way.
One part of the code is for solving another objective which is to find the avg, min,, and max value. I just need help with the printing out the list format.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class NumberThingy {
public static void main(String[] args) throws IOException {
// Create new Scanner object to read from the keyboard
Scanner in = new Scanner(System.in);
//Ask human for file name
System.out.println("Please enter the name of your data file with it's extension i.e Whatever.txt: ");
String fileName = in.next();
// Access the file provided
Scanner fileToRead = new Scanner(new File(fileName));
double Sum = 0;
int NumberOfEntries = -1;
double HighestValue = 0, LowestValue = 0;
boolean StillRecording = true;
double CurrentValue;
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble())
{
NumberOfEntries++;
CurrentValue = fileToRead.nextDouble();
if (StillRecording)
{
HighestValue = CurrentValue;
LowestValue = CurrentValue;
StillRecording = false;
}
else
{
HighestValue = Math.max(HighestValue,CurrentValue);
LowestValue = Math.min(LowestValue, CurrentValue);
}
Sum += CurrentValue;
}
else
{
fileToRead.next();
}
}
System.out.println("Here are your resutlts:");
System.out.println("Minimum Temp = " + LowestValue);
System.out.println("Maximum Temp = " + HighestValue);
System.out.println("Average Temp: " + Sum/NumberOfEntries);
System.out.println("There are " + NumberOfEntries + " temp recordings.");
System.out.println("It dipped down to 32 F " + FreezeCounter + " times.");
}
}
Thank you for your time and patience! I'm a student and love this community's enthusiasm.
It seems like you do have a lot of good things in place already, but as you are new to these concepts I'd recommend breaking this program into small working examples--little "aha" success moments.
For example, with the Scanner class, hard-code in the file location and simply get it to print the values from the file.
Scanner fileToRead = new Scanner(new File("c:\\hard-coded-file.txt"));
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble())
{
System.out.println(fileToRead.nextDouble());
}
else
{
fileToRead.next();
}
}
Once you can do that, then add in your analysis logic. As of right now, it appears that your highest and lowest values will likely turn out to be the same value.
Lastly, consider reviewing the class and variable naming conventions for Java (you should do this for every language you work in) as, for example, standard variable names are written in camelCasing rather than PascalCasing as you have done.
EDIT/UPDATE
In regards to the cookie cutter format, I think you are on the correct track. To achieve what you are wanting, you will likely have to add a println statement within the while loop and print as you go, or you could experiment with something like a list of strings
LinkedList<String> outputStrings = new LinkedList<String>();
and adding the strings
outputStrings.add("The number ___ was at 00:00"));
to that list. You could then loop through the list at the end to print it all at once. Note that you may consider looking into String.format() to get leading zeroes on numbers.
Do you know about printf? Here is a cheatsheet I used when I was learning java.
https://www.cs.colostate.edu/~cs160/.Summer16/resources/Java_printf_method_quick_reference.pdf
System.out.printf("Today's special is %s!", "tacos");
Basically the method will replace whatever %s %f you have in the first string with the variables listed after the first string. It prints "Today's special is tacos!" You have to match the types right: %s is for string, %f for floating points.
Its all in the link.

Counting numbers in a line

I'm reading my game map
FileHandle file = Gdx.files.internal("data/" + level + ".txt");
StringTokenizer tokens = new StringTokenizer(file.readString());
while(tokens.hasMoreTokens()){
String type = tokens.nextToken();
if(type.equals("Car")){
carLiist.add(new Car(Integer.parseInt(tokens.nextToken()), Integer.parseInt(tokens.nextToken()), Float.parseFloat(tokens.nextToken()), Float.parseFloat(tokens.nextToken())));
}
And here is my text file
Block 0 0
Block 64 0
Car 1 5 9 5
Car 1 5 2
Block 1
Car 7
Is it possible in java to count number in each line?
EDIT:
How I need to get whole line using stringtokenizer? Here what I'm trying to do, but I get only first word in each line
while(tokens.hasMoreTokens()){
String type = tokens.nextToken();
System.out.println(type);
if(type.equals("Block")){
//System.out.println(type);
list.add(new Brick(Integer.parseInt(tokens.nextToken()), Integer.parseInt(tokens.nextToken())));
Yes there is. Java provides a method to check whether a character is digit or not. Check the character and and increase count if its digit like this:
int digitCount = 0;
if(isDigit(characterToCheck)) {
digitCount++;
}
Method: boolean isDigit(char ch). See here for example

Printing and matching values in java

I have a program that will read a text file starting on line number 29. If the line contains the words "n.a" or "Total" the program will skip those lines.
The program will get the elements [2] and [6] from the array.
I need to get element [6] of the array and print it underneath its corresponding value.
Element[2] of the array is where all the analytes are and element[6] contains the amount of each analyte.
The files that the program will read look like this:
12 9-62-1
Sample Name: 9-62-1 Injection Volume: 25.0
Vial Number: 37 Channel: ECD_1
Sample Type: unknown Wavelength: n.a.
Control Program: Anions Run Bandwidth: n.a.
Quantif. Method: Anions Method Dilution Factor: 1.0000
Recording Time: 10/2/2013 19:55 Sample Weight: 1.0000
Run Time (min): 14.00 Sample Amount: 1.0000
No. Ret.Time Peak Name Height Area Rel.Area Amount Type
min µS µS*min % mG/L
1 2.99 Fluoride 7.341 1.989 0.87 10.458 BMB
2 3.88 Chloride 425.633 108.551 47.72 671.120 BMb
3 4.54 Nitrite 397.537 115.237 50.66 403.430 bMB
4 5.39 n.a. 0.470 0.140 0.06 n.a. BMB
5 11.22 Sulfate 4.232 1.564 0.69 13.064 BMB
Total: 835.213 227.482 100.00 1098.073
The program needs to read that type of files and stores the element[6] of the array under a heading in a separate file in a folder. That file will have a heading like this:
Fluoride,Chloride,Nitrite,Sulfate,
The amount of fluoride should go under fluoride, the amount of chloride should go under chloride and so on and if there isn`t Nitrite or any other analyte it should put a zero for each analyte.
I just need to know how to match that and then I know I have to make write to the file which I will do later, but for know I need help matching.
The final output should looe like this.
The first line will be written in the textfile and then the second line will be values that will be match under its corresponding analyte like this:
Sample#,Date,Time,Fluoride,Chloride,Nitrite,Sulfate,9-62-1,10/2/2013,19:55,10.458,671.120,403.430,13.064,
Also again if an analyte isnt present on the file or it is null it should put a 0.
Here is my code:
//Get the sample#, Date and time.
String line2;
while ((line2 = br2.readLine()) != null) {
if (--linesToSkip2 > 0) {
continue;
}
if (line2.isEmpty() || line2.trim().equals("") || line2.trim().equals("\n")) {
continue;
}
if (line2.contains("n.a.")) {
continue;
}
if (line2.contains("Total")) {
continue;
}
String[] values2 = line2.split("\t");
String v = values2[2];//Stored element 2 in a string.
String v2 = values2[6];//Stored element 6 in a string.
String analytes = "Fluoride,Chloride,Nitrite,Sulfate";//Stored the analytes into an array.
if (analytes.contains(v)) {
System.out.println(v2);
}
int index2 = 0;
for (String value2 : values2) {
/*System.out.println("values[" + index + "] = " + value);*/
index2++;
}
System.out.print(values2[6] + "\b,");
/*System.out.println(values[6]+"\b,");*/
br.close();
}
Thanks in advance!
So if i understand your task right and every element is in new line.
Where is a lot of ways how to solve this, but with your code simpliest way to solve it in my opinion would be with StringBuffer.
//In your code i saw you have to arrays one of them with element name
//other with element code or smth
StringBuffer firstLine = new StringBuffer();
StringBuffer secondLine = new StringBuffer();
public static void printResult(String[] Name, String[] Code){
//First we gona make first line
//Here we are adding data before Names
firstLine.append("Stuff before Names");
for(int i =0;i<name.length;i++){
//Here we gona add all names in the list which is good
//Dont forget spaces
firstLine.append(name[i]+ " ");
}
//And same goes for second line just change loop array and data added before loop.
//And in the end this should print out your result
System.out.println(firstLine+"\n" + secondLine);
}
Call this method after all file reading is done.
Hope it helps!

Storing input from text file

My question is quite simple, I want to read in a text file and store the first line from the file into an integer, and every other line of the file into a multi-dimensional array. The way of which I was thinking of doing this would be of creating an if-statement and another integer and when that integer is at 0 store the line into the integer variable. Although this seems stupid and there must be a more simple way.
For example, if the contents of the text file were:
4
1 2 3 4
4 3 2 1
2 4 1 3
3 1 4 2
The first line "4", would be stored in an integer, and every other line would go into the multi-dimensional array.
public void processFile(String fileName){
int temp = 0;
int firstLine;
int[][] array;
try{
BufferedReader input = new BufferedReader(new FileReader(fileName));
String inputLine = null;
while((inputLine = input.readLine()) != null){
if(temp == 0){
firstLine = Integer.parseInt(inputLine);
}else{
// Rest goes into array;
}
temp++;
}
}catch (IOException e){
System.out.print("Error: " + e);
}
}
I'm intentionally not answering this to do it for you. Try something with:
String.split
A line that says something like array[temp-1] = new int[firstLine];
An inner for loop with another Integer.parseInt line
That should be enough to get you the rest of the way
Instead, you could store the first line of the file as an integer, and then enter a for loop where you loop over the rest of the lines of the file, storing them in arrays. This doesn't require an if, because you know that the first case happens first, and the other cases (array) happen after.
I'm going to assume that you know how to use file IO.
I'm not extremely experienced, but this is how I would think about it:
while (inputFile.hasNext())
{
//Read the number
String number = inputFile.nextLine();
if(!number.equals(" ")){
//Do what you need to do with the character here (Ex: Store into an array)
}else{
//Continue on reading the document
}
}
Good Luck.

Categories

Resources