This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
user have to write an email in multiple lines and stop the input when ".." (two dots) are entered by the user. then the email should be saved to the variable but the variable saves the last input which are the two dots.
this is my code
any changes?
BufferedReader inl = new BufferedReader(new InputStreamReader(System.in));
String email_data;
System.out.println("Data: ");
do{
email_data = inl.readLine();
} while(email_data != "..");
Append the input to your variable instead of overriding it.
Also, don't use '!=' or '==' on Strings - use the .equals() method instead.
BufferedReader inl = new BufferedReader(new InputStreamReader(System.in));
String email_data = "";
String input;
System.out.println("Data: ");
do{
input = inl.readLine();
if (!input.equals("..")) {
email_data += input;
}
} while(!input.equals(".."));
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
BufferedReader is skipping every other line when reading my file in java
(3 answers)
Closed 2 years ago.
I am trying to make a function that will count how many lines starts with & in given file.
So far i came up with following function
public int CountNumberOfTexts(String filename) {
try{
File file = new File(filename);
if(file.exists()){
FileReader fr = new FileReader(file);
LineNumberReader lnr = new LineNumberReader(fr);
int linenumber = 0;
while (lnr.readLine() != null){
if (lnr.readLine().substring(0,1) == "&") {
linenumber++;
}
}
Log.d("Count", "NUMBER OF LINES: " + linenumber);
lnr.close();
return linenumber;
}else{
System.out.println("File does not exists: " + filename);
}
}catch(IOException e){
e.printStackTrace();
}
return 0;
}
Current Function error is: Not recognizing lines starting with & character.
You are facing two problems:
You are reading in two lines, but only evaluating every second:
while (lnr.readLine() != null){ <- first consumption
if (lnr.readLine().substring(0,1) == "&") { <- second
You are comparing strings with == operator instead of equals method. Or in your case you can even use startsWith method which is created precisely for scenarios like yours.
This will do the trick:
String line;
while ((line = lnr.readLine()) != null){
if (line.startsWith("&")) {
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I am a beginner-moderate java writer, and I have a problem that I just cannot understand, not even the cause.
I have some stuff in a class, a filewriter and -reader object, a scanner(system.in), and some strings, longs and ints. The idea is to easily write an .html document, and I nailed it already, but I created a for () loop around a bit of code containing scan.nextInt();, and it just skipped it when running in the console.
A tiny part of the code:
int amlinks = scan.nextImt();
for (int i = 0; i < amlinks; i++) {
//refer file link1
//link1, ln12
System.out.print("[htmlbuilder.process]: text1 = ");
String link1= new String(scan.nextLine());
//refer text link1
//text1, line12, ln12
System.out.print("[htmlbuilder.process]: text2 = ");
String text1 = new String(scan.nextLine());
String link = new String(" <p><a href='" + link1 + ".html'>" + text1 + "</a>");
writer.write(link);
}
Some handy facts:
The class is called htmlbuilder;
amlinks is just a variable for the for () loop;
link1 and text1 variables are the required Strings for the links;
link variable will eventually be written in the file,
writer:
Writer writer = null;
write = writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileID + ".html"), "utf-8"));
with fileID as the name of the file;
the //info before says what is inside the next piece of code.
I hope you understand what I am doing, I do know I have quite an own way of coding...
Thanks for help!
PS: Just ask some questions if you don't understand anything
when you both use nextInt() and nextLine() of the one,please add
Object.nextLine();
Like that
somthing=scan.nextInt();
somthing=scan.nextInt();
...
scan.nextLine();
somthing=scan.nextLine();
somthing=scan.nextLine();
...
to make sure that your input items are read by the real next line, nextInt() methods means your cursor is still in the current line.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
**
I want to get text from the user and find the number of words in the text according to the word searched. BufferedReader sets the readLine method to get all rows with while, but the program gives a null pointer exception error
.
The program worked fine when I used a single readline.
I think the problem is in the while loop but I do not understand the problem.**
Please Write Path : C:\Users\Soul Collector\Desktop\yazi okuma
Please Write the Name of Text : buffer
Text File :
hi hello my name is suat
hello there
Hello
Write the key word :
hi
Exception in thread "main" java.lang.NullPointerException
at project2.Count.SingleWord(Count.java:83)
at project2.Project2.main(Project2.java:45)
C:\Users\Soul Collector\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 18 seconds)
if(press == 2 )
{
System.out.print("Please Write Path : ");
scan.nextLine();
path = scan.nextLine();
System.out.print("Please Write the Name of Text : ");
txtname = "\\"+ scan.nextLine() + ".txt";
finalpath = path + txtname;
File dosya = new File(finalpath);
FileReader fr = new FileReader(dosya);
BufferedReader br = new BufferedReader(fr);
String dizi;
while((dizi = br.readLine()) != null){
System.out.println(dizi);
}
br.close();
/* StringTokenizer st = new StringTokenizer(dizi);
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}*/
String search=null;
System.out.println("Write the key word : ");
search = scan.nextLine();
Scanner s = new Scanner(dizi.toLowerCase());
while (s.hasNext()) {
toplamkelime++;
if (s.next().equals(search))
kelime ++;
}
System.out.println("Key Word : " + search);
System.out.println("Count of key word : " + kelime);
System.out.println("\n\n\n Total Count of Words : " + toplamkelime );
}
You are assigning value to 'dizi' within while conditions, so it was overwritten everytime. When there is something to read, 'dizi' has a value and get printed inside the while loop.
When nothing else to read 'dizi' is then has null value. So when you call 'dizi.toLowerCase()' later down the line, you get null pointer exception.
To fix the issue you need to keep track of all read dizi by using List or append them to another String.
This question already has answers here:
Java: How to get input from System.console()
(9 answers)
Closed 8 years ago.
What is a Java equivalent for this C++ code snippet:
string str ;
while(cin>>str){
//code
}
Something like this
String str ;
while((str = System.in.readLine()) != null){
//code
}
Scanner scanner = new Scanner(System.in);
String sentence = scanner.nextLine();
Scanner scanner = new Scanner(System.in);
boolean flag = true;
while(flag)
{
String str = scanner.nextLine();
// Add any condition to set flag = false to exit from while loop
}
you can do it either with a GUI style .
import javax.swing.JOptionPane;
String Input=JOptionPane.showInputDialog("Title","Message");
This question already has answers here:
How can I use hasNextInt() to catch an exception? I need Int but if input is character, that is bad
(3 answers)
Closed 9 years ago.
Basically I am taking a string input that represents a file. That file can contain integers, doubles or random strings. I am trying to iterate through the file adding all the integers and then taking the average of all of them. The issue I'm stuck on is when I get something other than an integer. I don't know how I am supposed to catch and deal with the error and then iterate onto the next part of the file. I can't use if statements and I'm thoroughly stuck.
String storeVariables = null;
FileReader fileReader;
BufferedReader bufferedReader;
Scanner scanner = null;
int total = 0;
int itterate = 0;
try{
fileReader = new FileReader(filename);
bufferedReader = new BufferedReader(fileReader);
scanner = new Scanner(bufferedReader);
while(scanner.hasNextInt()){
total += scanner.nextInt();
itterate++;
}
}
catch(Exception e){
}
return total/itterate;
}
Scanner#nextInt may throws
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
Try this -
while(scanner.hasNextInt()){
try{
total += scanner.nextInt();
itterate++;
}catach(RuntimeException nfe){...}
}