Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I wrote simple program that deletes letter or word from text. Everything works perfectly, but I can't write " " [space] in console. When I do that it does nothing. What should I write into console to tell it that I want to delete space from text?
import java.io.*;
import java.util.*;
public class StringDelete {
public static void main(String args[]) {
String x = "bla bla bla";
System.out.println(x);
System.out.println("What do you want to delete?");
Scanner sc = new Scanner(System.in);
String fr = sc.next();
int po = 0;
int le = x.length();
int i = 0;
do {
po = x.substring(i).indexOf(fr);
if (po != -1) {
x = x.substring(0, po+i) + x.substring(po+i + 1);
}
i += po;
}while(i<le&&po!=-1);
System.out.println(x);
}
}
Here:
String fr = sc.next();
You are using next() method.
When this method encounters a whitespace character, it returns the string before that character.
eg:
for "asd fgh" it returns asd".
for "xyz" it returns "xyz"
for " " it reurns ""(empty string)
Hence, when you write " "(space), the string before it is empty String, and it returns the empty string.
Instead of next(), use nextLine().
String fr = sc.nextLine();
You should replace the line String fr = sc.next(); with String fr = sc.nextLine();.
You can find more info here.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I write a code using BufferedReader class to take input from the user. first I took character input and String then tried to print both the inputs on the output screen and some weird output I got.
import java.io.*;
public class scratch_1{
public static void main(String[] args) throws IOException{
InputStreamReader InputObj = new InputStreamReader(System.in);
BufferedReader BufferObj = new BufferedReader(InputObj);
System.out.println("enter the Character: ");
char c = (char)BufferObj.read();
System.out.println("enter the string: ");
String str = BufferObj.readLine();
System.out.println("entered string: "+str);
System.out.println("entered Character: "+c);
}
}
By strange output do you mean this?
enter the Character:
a
enter the string:
entered string:
entered Character: a
It's not a strange output, because BufferedReader#read reads exactly one character and BufferedReader.readLine reads everything from the beginning of the line to newline character (\n).
When you press Enter, you're pushing \n to STDIN. So, in this example, my input was a\n. First read recognized letter 'a' and then readLine read '\n' symbol, thus saving empty string to str.
Fix
To fix this, you need to omit the newline character by calling read again.
InputStreamReader InputObj = new InputStreamReader(System.in);
BufferedReader BufferObj = new BufferedReader(InputObj);
System.out.println("enter the Character: ");
char c = (char)BufferObj.read();
BufferObj.read(); // omit '\n' going after previous char
System.out.println("enter the string: ");
String str = BufferObj.readLine();
System.out.println("entered string: "+str);
System.out.println("entered Character: "+c);
Running this code gives the next output
enter the Character:
a
enter the string:
string
entered string: string
entered Character: a
I guess you mean why it just skips the next readline after entering the character, if that's the case you just need to put BufferObj.read(); after each read() function, so your code will look like this:
...
System.out.println("enter the Character: ");
char c = (char) BufferObj.read();
BufferObj.read();
System.out.println("enter the string: ");
String str = BufferObj.readLine();
System.out.println("entered string: " + str);
System.out.println("entered Character: " + c);
...
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am attempting a programming question at hackerrank.com and is using Java language.
Part of the question required me to split a string by character /.
I met problems in doing this in Java.
Given input:
cu/a/ca ha/ri i/tu san/gat se/juk
My code (Java):
Scanner input = new Scanner(System.in);
String source = input.next();
String[] inputchar = source.split("/");
for (int i = 0; i < inputchar.length; i++){
System.out.print(inputchar[i] + "\n");
}
Result:
cu
a
ca
But, I expected the following output:
cu
a
ca ha
ri i
tu san
gat se
juk
However, when I tried with the following C# code, it gave me the correct result.
String source = Console.ReadLine();
String[] slashchar = source.Split('/');
for (int k = 0; k < slashchar.Length; k++)
{
Console.WriteLine(slashchar[k]);
}
I noticed the string with spaced cannot be splitted properly with my Java code.
Is there any mistakes in my Java code above?
Your Scanner does some tokenizing - on spaces. So you didn't read whole line with
input.next();
You only read until first blank.
Replace with
input.nextLine();
And try again.
Change to String source = input.nextLine(); instead of String source = input.next(); Because input.next() returns string till space, input.nextLine returns string till new line.
With java try using nextLine() like this:
Scanner input = new Scanner(System.in);
String source = input.nextLine();
String[] inputchar = source.split("/");
for (int i = 0; i < inputchar.length; i++){
System.out.print(inputchar[i] + "\n");
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a text file that has two columns, one for account numbers and the other for balances.
I would like to ask the user for his account number and get his balance from the text.
I have methods like deposit and withdraw, which I want to apply to the balances of the user, and then update the text file. What is the best way to do it?
Should I use an array? or there are easier ways to do?
The text file would be like this
1001 50.67
1002 500.32
1003 63.63
1004 953.53
1005 735.22
Using an array is not a practical approach to this problem. I made a sample program that does the above without an array. To make this run, make sure your account file is names BankAccounts.txt
import java.io.*;
import java.util.*;
public class BankAccount {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
File dir = new File("BankAccounts.txt");
System.out.println("Please enter your bank account number.");
String bankNumber = input.nextLine();
input.close();
System.out.println("Your Balance is: "
+ balanceFromAccount(bankNumber, dir));
}
public static String balanceFromAccount(String accountNumber, File file) {
String tempNumber = "";
int i;
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
for (i = 0; line.charAt(i) != ' '; i++) {
tempNumber = tempNumber.concat(line.substring(i, i + 1));
}
if (tempNumber.equals(accountNumber)) {
return line.substring(i + 1);
}
tempNumber = "";
}
br.close();
} catch (Exception e) {
}
return "Not Found!";
}
}
This program simply opens the file, finds each bank account number, checks if it is the desired one, then it returns the value if it is. If not, it says "Not Found!"
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i got a code that i am implementing from another but i get the error of Java ArrayIndexOutofBoundsException can someone help me? I am not sure of what to do it might be the codes that trigger the error
the data in the file is
Username|HashedPassword|no.of chips
code is below
public static void DeletePlayer()throws IOException{
File inputFile = new File("players.dat");
File tempFile = new File ("temp.dat");
BufferedReader read = new BufferedReader(new FileReader(inputFile));
BufferedWriter write = new BufferedWriter(new FileWriter(tempFile));
ArrayList<String> player = new ArrayList<String>();
try {
String line;
Scanner reader = new Scanner(System.in);
System.out.println("Please Enter Username:");
String UserN = reader.nextLine();
System.out.println("Please Enter Chips to Add:");
String UserCadd = reader.nextLine();
while((line = read.readLine()) != null){
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
Integer totalChips = (Integer.parseInt(UserCadd) + Integer.parseInt(Chips));
if(Username.equals(UserN)){
line = Username + "|" + Password + "|" + totalChips;
write.write("\r\n"+line);
}
}
read.close();
write.close();
inputFile.delete();
tempFile.renameTo(inputFile);
main(null);
}catch (IOException e){
System.out.println("fail");
}
}
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
It seems that your details array has only one or two elements. The moment, you try to get something from the array, for an index that is out of (the existing) range, that Exception is thrown.
Are you sure your file doesn't end with an empty line ?
add the line:
System.out.println("length: " + details.length);
right after your split method, or print out all the element of the details array, that will tell you how many elements there are, and how many times you try to do this for which values.
In this code:
while((line = read.readLine()) != null){
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
//...
}
You must check if the user input is at the expected format, in your case,
joe|g00d|12
The minimal check is to have 3 elements separated by |. e.g.
while((line = read.readLine()) != null){
String[] details = line.split("\\|");
if (details.length != 3) {
System.out.println("Bad input, try agains...");
continue;
}
String Username = details[0];
String Password = details[1];
String Chips = details[2];
//...
}
Note that you should String#trim() your inputs in order to strip leading and ending whitespaces (this allows an input like joe | g00d | 123), and you still can have an error when parsing the number of chips which has to be an integer. I would also certainly check that.
So. I'm wondering how could i make it so that
System prints word which contains a-z + å, ä and ö letters.
(At the moment å, ä and ö are printed in a weird way. I'm pretty sure that you know what it looks like :D)
User inputs a word and compares it to the first word. And at the moment if the word above ^ contains ä, ö or å and i input that word.. It won't see the match between those 2..
So the question is: How can I make it so that if you put å, ä or ö to input it will notice that it's exactly the same å, ä, ö in the word it just printed? I'm using
answer.equals(rightanswer)
There's my whole code :D Mostly just quests and answers :)
import java.io.*;
import java.awt.*;
public class sanaopisto {
public static int quanity;
public static String rightanswer;
public static String question;
public static int right;
public static int wrong;
public static double ratio;
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try{
System.out.print("Moneenko sanaan tahdot vastata? ");
quanity = Integer.parseInt(in.readLine());
for(int x=0; x<quanity; x++){
System.out.println(x+1 +". kysymys");
getquestion(quanity);
}
System.out.println("Oikeita vastauksia " +right +" ja v\u201e\u201eri\u201e " +wrong +".");
}catch(Exception e) {
System.out.println("Tapahtui virhe.");}}
public static void getquestion(int quanity) {
try{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int[] done = new int[100];//create array but everything is null
for(int i = 0; i<done.length; i++)
{
done[i] = 0;//need default values else wise it'll just be NULL!!!
}
//must be done before the do-while loop starts
boolean allDone = false;
String answer;
int ran;
if (!areAllQuestionsComplete(done)){ //Changed (!areAllQuestionsComplete(done)) thingy like this..
do{ //And made this work properly etc.
ran = (int)(Math.random() * 53 + 1);
} while (done[ran] == 1);
if(done[ran] != 1)
{
//ask random question
//if answer is correct, set done[ran] = 1
//else just let do-while loop run
if (ran == 1) { //1
question = "ruotsalainen";
rightanswer = "svensk, -t, -a";}
if (ran == 2) { //2
question = "suomalainen";
rightanswer = "finländsk, -t, -a";}
//.
//. Took some code away from here.. Because too many questions.. In real version I have all the 1-84 questions :D
//.
if (ran == 83) { //15
question = "globalisoitunut";
rightanswer = "globaliserad, -at, -ade";}
if (ran == 84) { //15
question = "maailma";
rightanswer = "en värld, -en, -ar, -arna";}
}
System.out.println(question);
System.out.print("Vastaus?: ");
answer = in.readLine();
if (answer.equals(rightanswer)){
right++;
System.out.println("Oikein!\n");
done[ran] = 1;}
else{wrong++;
System.out.println("Oikea vastaus on: " +rightanswer +"\n");}
//check if all questions are answered}
else {
System.out.println("You have answered every question!"); //I know that this is useless.. :D
}
}catch(Exception e) {
System.out.println("You made a mistake.");}
}
private static boolean areAllQuestionsComplete(int[] list)
{
for(int i = 0; i<list.length; i++)
{
if(list[i] != 1)
{
return false;//found one false, then all false
}
}
return true;//if it makes it here, then you know its all done
}
}
Edit Added whole code 'took some of the questions away' And I'm using CMD
I'm guessing you are using System.out and System.in which use the systems default encoding.
This is some kind of DOS encoding in the windows command line, depending on your computer settings.
So to allow any kind of Unicode character like äöü and the like to be read and printed as you want to, you have to change your command line encoding (E.g. tell DOS to use a different encoding) and java to use the same encoding.
To correctly answer on how this can be done, one would need more information about your operating system.
on the java side you can use a InputStreamReader and give the character set (encoding) to it's constructor to read and a PrintStream (giving the same encoding as well) to write.
UTF-8 should enable you to use them.
You're Finnish right? :)
If you try that:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
How is working for you?
EDIT:
Somehow the UTF-8 which should work doesn't seem to do the trick. I tried using -Dfile.encoding=UTF8 as a JVM property but didn't work for me
So I tried basically all the charsets which were available and few of them gave the correct characters, here are the charset names:
x-ISO-2022-CN-GB, x-ISO-2022-CN-CNS, x-IBM922, windows-1258, windows-1254, windows-1252,
ISO-8859-9, ISO-8859-4, ISO-8859-1, ISO-2022-KR and ISO-2022-CN
So if you try for example:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in, "x-ISO-2022-CN-GB"));
It should work