Character and String input in Java - java
I am new to Java and wrote a program for basic I/O operations of different data types. I want the program to input 1 a abcd and output them in in three different lines respectively. But when I input 1 a the program terminates and outputs 1 , a and an empty line in three different lines. I am not able to take a character input properly, which I think is the root of the problem.
Can someone please guide me as to where I got it wrong ?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
char c = ' ';
try {
c = (char)br.read();
}
catch (IOException e) {
e.printStackTrace();
}
return c;
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
char c = in.nextChar();
String s = in.nextLine();
out.println(n);
out.println(c);
out.println(s);
out.close();
}
}
Refactor the code like below.
char c = in.nextChar();//Keep this line as same
in.nextLine();//(only add this line after the above line)Place this line otherwise your String abcd can't insert
output:
1
a
abcd
you mean like follow:
input: 1 a abcd
out:
1
a
abcd
you reference this code:
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferedReader.readLine();
if (inputLine!=null && inputLine.length()>0) {
String[] splitInputLine = inputLine.split("\\ ");
for (String outLine : splitInputLine) {
System.out.println(outLine);
}
}
bufferedReader.close();
}
Related
Indexing through an array to return any specific value in java
So, I have created code which is reading a CSV file line by line, then splitting each line into their individual values then putting this into an array, but i am stuck on trying the index a value from this array I have created, I will attach the CSV file and also my code, and lets say for example how would I access the value at [3,4], which should be Andorra, and [6,6] which should be 17? CSV FILE: Date,iso3,Continent,CountryName,lat,lon,CumulativePositive,CumulativeDeceased,CumulativeRecovered,CurrentlyPositive,Hospitalized,IntensiveCare,NUTS 31/1/2021,AFG,AS,Afghanistan,33.930445,67.678945,55023,2400,,52623,,,AF 31/1/2021,ALB,EU,Albania,41.156986,20.181222,78127,1380,47424,29323,324,19,AL 31/1/2021,DZA,AF,Algeria,28.026875,1.65284,107122,2888,,104234,,,DZ 31/1/2021,AND,EU,Andorra,42.542268,1.596865,9937,101,,9836,44,,AD 31/1/2021,AGO,AF,Angola,-11.209451,17.880669,19782,464,,19318,,,AO 31/1/2021,AIA,NA,Anguilla,18.225119,-63.07213,17,0,,17,,,AI 31/1/2021,ATG,NA,Antigua and Barbuda,17.363183,-61.789423,218,7,,211,,,AG 31/1/2021,ARG,SA,Argentina,-38.421295,-63.587403,1915362,47775,,1867587,,,AR 31/1/2021,ARM,AS,Armenia,40.066181,45.111108,167026,3080,,163946,,,AM 31/1/2021,ABW,NA,Aruba,12.517713,-69.965112,6858,58,,6800,,,AW 31/1/2021,AUS,OC,Australia,-26.853388,133.275154,28806,909,,27897,,,AU 31/1/2021,AUT,EU,Austria,47.697542,13.349319,411921,7850,383158,21058,1387,297,AT 31/1/2021,AZE,AS,Azerbaijan,40.147396,47.572098,229935,3119,,226816,,,AZ 31/1/2021,BHS,NA,Bahamas,24.885993,-76.709892,8174,176,,7998,,,BS 31/1/2021,BHR,AS,Bahrain,26.039722,50.559306,102626,372,,102254,,,BH 31/1/2021,BGD,AS,Bangladesh,23.68764,90.351002,535139,8127,,527012,,,BD 31/1/2021,BRB,NA,Barbados,13.18355,-59.534649,1498,12,,1486,,,BB 31/1/2021,BLR,EU,Belarus,53.711111,27.973847,248336,1718,,246618,,,BY 31/1/2021,BEL,EU,Belgium,50.499527,4.475402,711417,21118,,690299,1788,315,BE 31/1/2021,BLZ,NA,Belize,17.192929,-88.5009,11877,301,,11576,,,BZ 31/1/2021,BEN,AF,Benin,9.322048,2.313138,3786,48,,3738,,,BJ 31/1/2021,BMU,NA,Bermuda,32.320236,-64.774022,691,12,,679,,,BM 31/1/2021,BTN,AS,Bhutan,27.515709,90.442455,859,1,,858,,,BT 31/1/2021,BWA,AF,Botswana,-22.344029,24.680158,21293,134,,21159,,,BW 31/1/2021,BRA,SA,Brazil,-14.242915,-53.189267,9118513,222666,,8895847,,,BR 31/1/2021,VGB,NA,British Virgin Islands,18.573601,-64.492065,141,1,,140,,,VG CODE: public static String readFile(String file) { FileInputStream fileStream = null; InputStreamReader isr; BufferedReader bufRdr; int lineNum; String line = null; try { fileStream = new FileInputStream(file); isr = new InputStreamReader(fileStream); bufRdr = new BufferedReader(isr); lineNum = 0; line = bufRdr.readLine(); while ((line != null) && lineNum < 27) { lineNum++; System.out.println(line); line = bufRdr.readLine(); } fileStream.close(); } catch (IOException e) { if (fileStream != null) { try { fileStream.close(); } catch (IOException ex2) { } } System.out.println("Error: " + e.getMessage()); } return line; } private static void processLine(String line) { String[] splitLine; splitLine = line.split(","); int lineLength = splitLine.length; for (int i = 0; i < lineLength; i++) { System.out.print(splitLine[i] + " "); } System.out.println(""); }
You need to create a 2D array in readFile. As the file is read, and and each line is split by processLine, insert the array into the 2D array. The method readFile at the end returns the 2D array. Make processLine to return a string array and have it return the result of the split. I marked where I made changes to your code. import java.io.*; public class Main { public static void main(String[] args){ String[][] data = readFile("data.txt"); System.out.println(data[3][4]); System.out.println(data[6][6]); } public static String[][] readFile(String file) { //<<< changed FileInputStream fileStream = null; InputStreamReader isr; BufferedReader bufRdr; int lineNum; String line = null; String[][] data = new String[28][]; //<<< added try { fileStream = new FileInputStream(file); isr = new InputStreamReader(fileStream); bufRdr = new BufferedReader(isr); lineNum = 0; line = bufRdr.readLine(); while (lineNum < 27) { // <<< changed System.out.println(line); line = bufRdr.readLine(); if (line == null) break; // <<< added data[lineNum++] = processLine(line); // <<< added } fileStream.close(); } catch (IOException e) { if (fileStream != null) { try { fileStream.close(); } catch (IOException ex2) { } } System.out.println("Error: " + e.getMessage()); } return data; //added } private static String[] processLine(String line) { //<< changed String[] splitLine; splitLine = line.split(","); int lineLength = splitLine.length; for (int i = 0; i < lineLength; i++) { System.out.print(splitLine[i] + " "); } System.out.println(""); return splitLine; // <<< added } }
You can do it quite simply using the stream API. import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Collectors; import java.util.stream.Stream; public class CsvTest0 { public static void main(String[] args) { Path path = Paths.get("geografy.csv"); try (Stream<String> lines = Files.lines(path)) { String[][] arr = lines.skip(1L) .limit(27L) .map(l -> l.split(",")) .collect(Collectors.toList()) .toArray(new String[][]{}); System.out.println(arr[3][3]); System.out.println(arr[5][6]); } catch (IOException xIo) { xIo.printStackTrace(); } } } However, regarding the code in your question, below is a fixed version followed by notes and explanations. import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CsvTest1 { public static String[][] readFile(String file) throws IOException { Path path = Paths.get(file); String[][] arr = new String[27][]; int lineNum; String line = null; try (BufferedReader bufRdr = Files.newBufferedReader(path)) { lineNum = 0; line = bufRdr.readLine(); // Ignore first line of file since it contains headings only. line = bufRdr.readLine(); while ((line != null) && lineNum < 27) { arr[lineNum++] = processLine(line); line = bufRdr.readLine(); } } return arr; } private static String[] processLine(String line) { return line.split(","); } public static void main(String[] args) { try { String[][] arr = readFile("geografy.csv"); System.out.println(arr[3][3]); System.out.println(arr[5][6]); } catch (IOException x) { x.printStackTrace(); } } } Note that the below is not in any particular order. I wrote them as they came to me. No need for FileInputStream and InputStreamReader in order to create BufferedReader. Use Files class instead. Close files in a finally block and not in a catch block. Hence use try-with-resources. I believe better to propagate the exception to the calling method, i.e. method main in this case. I also believe that, unless you can safely ignore the exception, it is always beneficial to print the stack trace. You don't want to process the first line of the file. You appear to have your array indexes mixed up. According to sample data, Andorra is row 3 and column 3 (not column 4). Also, 17 is at [5][6] and not [6][6]. Two-dimensional arrays in java can be declared with only one dimension indicated. Since you only want first 27 lines of file, you know how many rows will be in the 2D array.
How to read from inputFileStream and split each line
I have to read from input file txtfile that look like mark;1001;3;4 there is a ';' between each variable. I know how to read it if it's in separate lines, but I can't read it if its in the same line. This is how I start: import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.nio.Buffer; public class Try { public static void main(String[] args) { String Name; int ID; Double quiz1 , quiz2; try { FileInputStream fileIN = new FileInputStream("input.txt"); InputStreamReader inputST =new InputStreamReader(fileIN); BufferedReader bufferRe = new BufferedReader(inputST); String line; while ((line = bufferRe.readLine()) != null) { // I tried many things, but nothing worked for me. // How could I use split here? } } catch (IOException e) { System.out.println("input is not found "); } } }
Using split is the way to go... while ( ( line = bufferRe.readLine())!= null) { for (String splitVal : line.split(";") { //Do whatever you need to with the splitVal value. //In you example it iterate 4 times with the values mark 1001 3 4 } }
The simplest solution, which also works when you want things to work across newlines, is to use a Scanner with ; as its delimiter: Scanner s = new Scanner(bufferRe); s.useDelimiter(";"); while (s.hasNext()) { System.out.println(s.next()); } --> mark 1001 3 4 This also allows you to use Scanner methods to eg. easily parse integers.
Just use split method inside loop to get all your data in array. String[] splited = line.split(";");
while ((line = bufferRe.readLine()) != null) { for (String retval : line.split(";", 2)) { System.out.println(retval); } } Output: mark 1001;3;4
There is one more aproach using StreamTokenizer try { FileInputStream fis = new FileInputStream("input.txt"); Reader r = new BufferedReader(new InputStreamReader(fis)); StreamTokenizer st = new StreamTokenizer(r); List<String> words = new ArrayList<>(); List<Integer> numbers = new ArrayList<>(); // print the stream tokens boolean eof = false; do { int token = st.nextToken(); switch (token) { case StreamTokenizer.TT_EOF: System.out.println("End of File encountered."); eof = true; break; case StreamTokenizer.TT_EOL: System.out.println("End of Line encountered."); break; case StreamTokenizer.TT_WORD: words.add(st.sval); break; case StreamTokenizer.TT_NUMBER: numbers.add((int)st.nval); break; default: System.out.println((char) token + " encountered."); if (token == '!') { eof = true; } } } while (!eof); } catch (IOException e) { e.printStackTrace(); System.out.println("input is not found "); }
Reverse lines in ArrayList Java
I'm working on a Java program in which I must read the contents of a file and then print each lines reverse. For example the text: Public Class Helloprinter Public static void would print the following after running my reverse program: retnirPolleh ssalc cilbup diov citats cilbup Here's what I got so far: public static void main(String[] args) throws FileNotFoundException { // Prompt for the input and output file names ArrayList<String> list = new ArrayList<String>(); //String reverse = ""; Scanner console = new Scanner(System.in); System.out.print("Input file: "); String inputFileName = console.next(); System.out.print("Output file: "); String outputFileName = console.next(); // Construct the Scanner and PrintWriter objects for reading and writing File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); PrintWriter out = new PrintWriter(outputFileName); String aString = ""; while(in.hasNextLine()) { String line = in.nextLine(); list.add(line); } in.close(); for(int i = 0; i <list.size(); i++) { aString = list.get(i); aString = new StringBuffer(aString).reverse().toString(); out.printf("%s", " " + aString); } out.close(); } } EDIT: With Robert's posting it helped put me in the right direction. The problem is that with that is that it doesn't keep the lines. Public Class Helloprinter Public static void becomes after running my program: retnirPolleh ssalc cilbup diov citats cilbup it needs to keep the line layout the same. so it should be: retnirPolleh ssalc cilbup diov citats cilbup
Your problem is in the line out.printf("%s", " " + aString); This doesn't output a newline. I'm also not sure why you are sticking a space in there. It should be either: out.println( aString ); Or out.printf("%s%n", aString);
In your last loop why don't you just iterate through the list backwards? So: for(int i = 0; i <list.size(); i++) Becomes: for(int i = list.size() - 1; i >=0; i--)
It seems like you already know how to read a file, so then call this method for each line. Note, this is recursion and it's probably not the most efficient but it's simple and it does what you want. public String reverseString(final String s) { if (s.length() == 0) return s; // move chahctrachter at current position and then put it at the end of the string. return reverseString(s.substring(1)) + s.charAt(0); }
Just use a string builder. You were on the right trail. Probably just needed a little help. There is no "one way" to do anything, but you could try something like this: Note: Here is my output: retnirPolleh ssalc cilbup diov citats cilbup import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Scanner; public class Reverse { public static void main(String[] args) { ArrayList<String> myReverseList = null; System.out.println("Input file: \n"); Scanner input = new Scanner(System.in); String fileName = input.nextLine(); System.out.println("Output file: \n"); String outputFileName = input.nextLine(); BufferedReader br = null; try { br = new BufferedReader(new FileReader(fileName)); String text = null; myReverseList = new ArrayList<String>(); StringBuilder sb = null; try { while ((text = br.readLine()) != null) { sb = new StringBuilder(); for (int i = text.length() - 1; i >= 0; i--) { sb.append(text.charAt(i)); } myReverseList.add(sb.toString()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Writer writer = null; try { writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outputFileName), "utf-8")); for (String s : myReverseList) { writer.write("" + s + "\n"); } } catch (IOException ex) { // report } finally { try { writer.close(); } catch (Exception ex) { } } } }
Integer.parseint exceptions
The question was : Write a program that processes an input.txt file that contains data regarding ticket type followed by mileage covered and reports how many frequent-flier miles the person earns. 1 frequent flyer mile is earned for each mile traveled in coach. 2 frequent flyer miles are earned for each mile traveled in first class. 0 frequent flyer miles are earned on a discounted flight. For example, given the data in input.txt below, your method must return 15600 (2*5000 + 1500 + 100 + 2*2000). Input.txt: firstclass 5000 coach 1500 coach 100 firstclass 2000 discount 300 My code gives me a problem with the parseint method. Any help would be appreciated :) //InInteger class import java.lang.NumberFormatException; public class IsInteger { public static boolean IsaInteger (String s)throws NumberFormatException { try { Integer.parseInt(s);//converts the string into an integer return true; } catch (NumberFormatException e) { return false; } } } //main class import java.io.*; import java.util.StringTokenizer; public class LA5ex2 { public static void main(String[] args) throws FileNotFoundException { BufferedReader input= new BufferedReader (new InputStreamReader (new FileInputStream("C:/Users/user/workspace/LA5ex2/input.txt"))); String str; int TotalMiles=0; try { int mileage,lines=0; String check,copy=null; String word=null; boolean isString=false; while ((str = input.readLine()) != null) { lines++; StringTokenizer token = new StringTokenizer(str); while (token.hasMoreTokens()) { if ((lines>1) && (isString)) { //do nothing } else {word= token.nextToken(); copy=word;} if (token.hasMoreTokens()) mileage= Integer.parseInt(token.nextToken()); else { if (!(IsInteger.IsaInteger(word))) { copy=word; isString=true; } break; } if (copy.equals("firstclass")) TotalMiles+= (2*mileage); else if (copy.equals("coach")) TotalMiles+= (1*mileage); else if (copy.equals("discount")) TotalMiles+= (0*mileage); } } System.out.println("Frequent-flier miles the person earns: "+ TotalMiles); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
This is the stacktrace that I get when running your code: Exception in thread "main" java.lang.NumberFormatException: For input string: "firstclass" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:481) at java.lang.Integer.parseInt(Integer.java:514) at LA5ex2.main(LA5ex2.java:30) I assume this is the error that you mention in your comment. However, the NumberFormatException does not occur in your IsaInteger() method in the IsInteger class (where you try-catch it by returning true or false), but in the LA5ex2 class (where you also try-catch it, but if it crashes, only the stacktrace gets printed). The exception occurs when Integer.parseInt() tries to parse the string firstclass as an integer, which of course fails: if(token.hasMoreTokens()) mileage = Integer.parseInt(token.nextToken()); I rewrote your code in LA5ex2.java with two ArrayLists (to keep track of the various flier classes and the various mileages) using your IsaInteger method: import java.io.*; import java.util.ArrayList; import java.util.StringTokenizer; public class LA5ex2 { public static void main(String[] args) throws FileNotFoundException { BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); String str = null; String token = null; int totalMiles = 0; int lines = 0; ArrayList<String> flierClasses = new ArrayList<String>(); ArrayList<Integer> mileages = new ArrayList<Integer>(); try { while((str = input.readLine()) != null) { lines++; // Why are we counting the lines, anyway? StringTokenizer tokenizer = new StringTokenizer(str); while(tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); if(!(IsInteger.IsaInteger(token))) { flierClasses.add(token); // if it's not an int, we assume it's a flier class } else { mileages.add(Integer.parseInt(token)); // if it's an int, it's a mileage } } } } catch(NumberFormatException ex) { // TODO Auto-generated catch block ex.printStackTrace(); } catch(IOException ex) { // TODO Auto-generated catch block ex.printStackTrace(); } // Add everything up for(int i = 0; i < flierClasses.size(); i++) { totalMiles += calculateFlierMiles(flierClasses.get(i), mileages.get(i)); } System.out.println("Frequent-flier miles the person earns: " + totalMiles); } private static int calculateFlierMiles(final String flierClass, final int mileage) { if(flierClass.equals("firstclass")) return(2 * mileage); else if(flierClass.equals("coach")) return(1 * mileage); else if(flierClass.equals("discount")) return(0 * mileage); return 0; } } This code gives me the desired output: Frequent-flier miles the person earns: 15600
I'm assuming the problem is in IsaInteger (which should be stylized as isAnInteger). In that case, add a line that prints out the value of s before the try/catch and tell me what you get. Also, why are you using tokens when you could use a BufferedReader and its nextLine() method?
reading file StringTokenizer to int
I have create the following program and I am little stuck here. Here is the code: class ProductNameQuan{ public static void main(String[] args) { String fileName = "stockhouse.txt"; StringTokenizer line; String ProdName; String quantity; try { BufferedReader in = new BufferedReader(new FileReader(fileName)); line = in.readLine(); while (line != null) { ProdName = line.nextToken(); quantity = line.nextToken(); System.out.println(line); line = in.readLine(); } in.close(); } catch (IOException iox) { System.out.println("Problem reading " + fileName); } } } I am trying to find the way to read from the file the first 10 information's through the array (not arraylist)ProdName and the quantity." plus that I stack in the in.readLine(); propably is not compatible with the StringTokenizer. Now the other problem is that I need the quantity to be an integer instead of string. The file includes something like that: Ball 32 tennis 322 fireball 54 .. . . . . Any ideas?
I would place this in a helper function, maybe called parseString class ProductNameQuan { public static void main(String[] args) { ... try { BufferedReader in = ... line = in.readLine(); while (line != null) { ProductNameQuan.parseString(line); } } ... } public static void parseString(String someString) { StringTokenizer st = new StringTokenizer(someString); while (st.hasMoreTokens()) { String token = line.nextToken(); try { int quantity = Integer.parseInt(token) // process number } catch(NumberFormatException ex) { // process string token } } }