I was able to enter it from the keyboard and save it to a file, but if there are no more than 10 characters, the conditions cannot be handled properly.The program created below.
What kind of content did you add to make it work?
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class Main4 {
public static void main4(String[]args)rows IOException {
System.out.println("Please enter up to 10 characters from the keyboard");
InputStreamReader isr=new InputStreamReader (System.in);
BufferedReader br = new BufferedReader(isr);
String str = null;
try{
str = br.readLine();
br.close();
} catch(IOExceptione){
e.printStackTrace();
}
FileOutputStream fos = new FileOutputStream("C:/Users/Desktop/java.txt"); {
bytesbyte[] = str.getBytes (StandardCharsets.UTF_8);
fos.write(sbyte);
// Write to file
fos.flush();
// Close the file
fos.close();
System.out.println("The characters entered are ""+str+"""");
}
}
}
You can consider the return value of String#length()
as the length of the string.
This time, the string entered by the user is in the variable str
, so you will see the return value of str.length()
and branch the condition.
// Length of string entered
int length = str.length();
if (0<length&=10){
// More than 0 characters and less than 10 characters
// "Save values entered from keyboard to file" process already implemented
} else{
// More than 10 characters or no input value
// Close the file
fos.close();
System.out.println("If more than 10 characters or no input value");
}
© 2024 OneMinuteCode. All rights reserved.