I was trying this code snippet-
import java.io.*;
class demo
{
public static void main(String args[]) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int c;
do
{
c= (char)br.read();
System.out.println(c);
}while(c!='q');
}
}
Now when I give input-22
output is- 50
50
13
10
I understand the output 50, 50 but why the the compiler is printing 13 and 10 ?
Kindly help.
Thanks!
I think 13 and 10 are CR/LF: the end of the line.
your input is
22<enter>
so your ascii for 2 is 50 hence 22 50 50
Pressing Enter causes Windows to store a carriage return code (ASCII 13) followed by a new-line code (ASCII 10) in the key buffer and hence you see 13 and 10 in the output.
You could also refer a good blog here http://www.javaworld.com/article/2075069/core-java/the-ins-and-outs-of-standard-input-output.html
Related
So i was solving a question in competitive programming where i had to take these numbers as input...
3
40 40 100
45 45 90
180 1 1
and here's my code:
package CP;
import java.io.*;
import java.util.*;
class Test {
public static void main(String[] args)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
while(t-->0){
StringTokenizer s=new StringTokenizer(br.readLine());
int a=Integer.parseInt(s.nextToken());
int b=Integer.parseInt(s.nextToken());
int c=Integer.parseInt(s.nextToken());
if(a+b+c==180) System.out.println("YES");
else System.out.println("NO");
}
br.close();
}
}
so this code works fine when i take inputs line by line. but when i take all the lines as input at a time it shows [Exception in thread "main" java.lang.NumberFormatException: For input string: "3"] in line 7. why is this happening?
There is a space after the 3 in the input. This causes the Integer.parseInt(String) to fail. Trimming the line of input should suffice to solve your issue.
int t = Integer.parseInt(br.readLine().trim());
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.
A lot of this code is already written but the code that I have added was to include ^ and %. It is the code to evaluate an expression in the right order using stacks. What I'm having trouble with this is the main method and adding a way to take user input and print out the result of the problem. I'm just including that part of the code
16 import java.util.Stack;
17 import java.util.Scanner;
18
19 public class EvaluateExpression {
20 public static void main(String[] args) {
21
22 Scanner input = new Scanner(System.in);
23 System.out.println("Enter the expression to be evaluated: ");
24 String expression = input.nextLine();
25
26 //Check number of arguments passed
27 if (args.length != 1) {
28 System.out.println("Usage: java EvaluateExpression \"expression\"");
29 System.exit(1);
30 }
31 try {
32 System.out.println(expression + " = " +
33 evaluateExpression(expression));
34 }
35 catch (Exception ex) {
36 ex.printStackTrace();
37 System.out.println("Wrong expression: " + expression);
38 }
39
40 }
Expected results: it is printing the expression to be evaluated along with the results.
But here is what I am getting with this when I try to enter a random expression:
Enter the expression to be evaluated:
6+9*8-7
Usage: java EvaluateExpression "expression"
It simply means that args.length is different than 1.
Your program is reading from standard input. Don't need to check args count. Args is program arguments that direct input of your program. Like
ls *.txt
or
java -cp . EvaluateExpression <myvalue>
Hope this helps.
I have been running through this array of objects trying to figure out what I am doing wrong and I can't see the error. This program runs through the first iteration bringing in Austria and all its subsequent information but will not move onto the second part of the array. I thought it might be that it's somehow taking each variable from the countries class and making it its own spot in the array but that can't be it because I have increased the array size to 64 and it still stops at the end of Austria. I have been able to get it to go a bit further by placing print statements after each item is added and it seems to be adding an unaccounted for blank line in it for some reason and I'm not sure why. any help that could be given would be greatly appreciated.
This is my test code with the data list:
import java.util.Scanner;
import java.io.*;
public class Test {
public static void main (String [] args) throws IOException {
final String INPUT_FILE = "CountriesInfo2.txt";
FileReader inputDataFile = new FileReader (INPUT_FILE);
Scanner read = new Scanner (inputDataFile);
Countries[] c = new Countries[8];
for (int i = 0; i < c.length; i++) {
c[i] = new Countries();
c[i].countryName = read.nextLine();
c[i].latitude = read.nextLine();
c[i].longitude = read.nextLine();
c[i].countryArea = read.nextInt();
c[i].countryPopulation = read.nextInt();
c[i].countryGDP = read.nextDouble();
c[i].countryYear = read.nextInt();
sop ("" + c[i].countryName + "\n" + c[i].latitude+"\n"+c[i].longitude+"\n"+c[i].countryArea+"\n"+
c[i].countryPopulation+"\n"+c[i].countryGDP+"\n"+c[i].countryYear);
}// end for
} // End Main
public static void sop (String s) {
System.out.println(s);
} // End sop
} // end class
Austria
47 20 N
13 20 E
83871 8754513 417.2 2016
Belgium
50 50 N
04 00 E
30528 11491346 509.5 2016
Czech Republic
49 45 N
15 30 E
7886
10674723
350.7
2016
France
46 00 N
02 00 E
643801
67106161
2734.0
2016
This list is supposed to be one line for each bit of information with lat-long having 2 sets of double digits and a letter each.
nextLine() automatically moves the scanner down after returning the current line. Rather I would advise you do as following
read each line using String data = scanner.nextLine();
split the data using space separator String[] pieces =
data.split("\\s+");
set the pieces to Country attributes by converting them in to
their appropriate type.
eg. c[i].countryName = pieces[0];
`c[i].latitude = piece[1];`
I'm trying to check if the text file contains "Circle" or "Square" and if so to read the rest of the line. I have tried using scan.next()=="Circle" but that doesn't seem to work.
EDIT: The numbers refer to x and y coordinates which will be implemented into an instance of a class. In this case, Square and Circle.
Text File:
Circle 50 60 40 50 50
Square 250 260 45 -50 -50
If you are reading from a text file try using a BufferedReader and then using readLine and then using .equals() instead of ==
An example:
BufferedReader reader = new BufferedReader(new FileReader(myTextFile));
String lineOne = reader.readLine();
if(lineOne.equals("circle"))
{
//do something
}
In Java, the “==” operator is used to compare 2 objects. It checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.
So you should make use of equals. But in your case, if a line starts with circle or square you have to read the line from the given file.
Can you use the following condition and check if it works with scanner itself?
String line = sc.next();
if (line.startsWith("Circle") || line.startsWith("Square")){
//Your logic
}
Try this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FileReader {
public FileReader() {
Scanner scanner;
List<String> list;
try {
list = new ArrayList<>();
scanner = new Scanner(new File("file.txt"));
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
if (!s.startsWith("Circle") && !s.startsWith("Square")) {
break;
}
System.out.println(s);
list.add(s);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new FileReader();
}
The file is called file.txt:
Circle 50 60 40 50 50
Square 250 260 45 -50 -50
False 50 60 40 50 50
If you compare Strings, always use equals not ==. Check this out