EDIT: Made the code a little nicer, deleted backstory, rephrased question.
So I had everything working, but then moved to a different computer, and it stopped working. Because this is for marks, I don't want to hand in a program that could possibly stop not work on my prof's computer.
So here's what I'm trying to do - I want to input data continuously, until enter is pressed on an empty line.
My real question is this. Why does it only work when the print statement is there after readLine command? And why does that not work on someone else's computer ?
(Could it be that I'm running from the IDE? JCreator 4.5 it works, JCreator 4 on the school computer didn't.)
import java.util.*;
import java.io.*;
public class TestIfWorks {
public static ArrayList<String> getArrList() {
String input = "Empty";
ArrayList<String> info = new ArrayList<String>();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
boolean go = true;
while (go) {
try {
input = in.readLine();
System.out.print(">"); //This causes it to work on my computer, but not on other computers. What!?!
} catch (Exception e) {
System.out.println("ERROR: key read problem");
}
if (input.equals("")) go = false;
else info.add(input);
}
return info;
}
public static void inputmethod() {
System.out.println("Please enter a brief summary if desired. Press enter on an empty line to stop entering data.");
ArrayList<String> info = new ArrayList<String>();
info = getArrList();
System.out.println("Now printing the arraylist out.");
for (int i = 0; i < info.size(); i++) {
System.out.println(info.get(i));
}
}
public static void main(String[] args) {
inputmethod();
}}
So yeah, it likes to loop once, enter that data fine, then on the second loop it always thinks you're entering nothing, and so only the first data is stored. Unless the output statement is there. Then it likes to work, but only sometimes.
What is happening?
I think you should start using
if(str != null && !str.isEmpty())
in order to see if it's empty or not
also you should add
tempStr = "";
after your if else block because if something goes wrong your tmpStr will still have the value from last loop state.
If i were you i'd try this instead:
String input = System.console().readLine();
Related
It works well on Intellij.
However, NoSuchElement appears on the algorithmic solution site.
I know that NoSuchElement is a problem caused by trying to receive it even though there is no value entered.
But I wrote it so that the problem of NoSuchElement doesn't occur.
Because given str, the for statement executes. Given "END", the if statement is executed. And because it ends with "break;".
I don't know what the problem is.
Algorithm problem: Arrange the reverse sentence correctly.
My code for algorithmic problems
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
while(true) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
if(str.equals("END")){
break;
}
for (int i = str.length()-1; i >=0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}
Output
!edoc doog a tahW
erafraw enirambus detcirtsernu yraurbeF fo tsrif eht no nigeb ot dnetni eW
END
Expected
What a good code!
We intend to begin on the first of February unrestricted submarine warfare
This happens when there is no input at all, for example when you hit Ctrl + d or run your code like echo "" | java Main.java.
To avoid this, check that the Scanner actually has input before trying to grab the next line. Pull scan out of the loop, there is no point to create a new Scanner for each line anyway. Then use hasNext to see if there is input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String str = scan.nextLine();
if(str.equals("END")){
break;
}
for (int i = str.length()-1; i >=0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}
I'm kinda new to Java so I'm looking for an help to do this.
As the title says, I'm trying to write a program that checks if a number given by the user from console is inside a text file with one number for each line or not.
I am using the Scanner class to check every line, but I am having problems with what condition the if statement should have when the number is found inside the file.
I wrote down this part code (I'm not even sure if it's correct itself, so correct me if I'm wrong):
int lines = 0;
while (filescanner.hasNextLine()) {
String line = filescanner.nextLine();
lines++;
if(conditon here) {
System.out.println("I found the number on line " + lines);
}
}
Thanks in advance.
Since you are getting the input number from Scanner keyboard, you can get its value like this:
String input = keyboard.next();
Then your if condition can be if(line.contains(input))
You need to convert the line to an integer and then test it. If it is not an integer the parseInt method throws an exception.
try {
int n = Integer.parseInt(line);
if (n == number) {
// found it
}
} catch (NumberFormatException e) {
// Not a number
}
Hi I wanted to know how to write up a try and catch block to stop from getting the below error.
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
I have this method which takes a sentence and splits it into an ArrayList. I then use that to store values into a hashmap, where index 1 is the key and the words after become the value. I use the below method to split the user input into an array.
private Scanner reader;
/**
* Create a new InputReader that reads text from the text terminal.
*/
public InputReader()
{
reader = new Scanner(System.in);
}
public ArrayList<String> getInput()
{
System.out.print("> "); // print prompt
String inputLine = reader.nextLine().trim().toLowerCase();
String[] wordArray = inputLine.split(" "); // split at spaces
// add words from array into ArrayList
ArrayList<String> words = new ArrayList<String>();
for(String word : wordArray) {
words.add(word);
}
return words;
}
}
and the below method uses the class above to detect user input. So when the user types in write they can write into a hashmap but if they press return before they type in a key and value I get the out of bounds exception. So How can i rewrite the below method to avoid this?
public void start()
{
boolean finished = false;
printWelcome();
while(!finished) {
ArrayList<String> input = reader.getInput();
if(input.contains("shutdown")) {
finished = true;
}
if (input.contains("load")) {
System.out.println();
instruct.readAndFill();
System.out.println();
}
if (input.contains("write")) {
String key = input.get(1);
String value = "";
for(int i=2; i<input.size(); i++) {
value = value + " " + input.get(i);
}
instruct.mapWrite(key, value);
}
}
instructorGoodBye();
}
Sorry if i wasn't clear enough, or if my code is not up to scratch i have only been learning java for about 2 months now.
basically if the user types in write key value on one line it is fine but if they hit return after write then the error happens.
So, fundamentally what you are missing is error checking. Your program is taking input from a user, and assuming it is valid. This is always a bad idea.
Instead, you should validate what you get from the user. One way you can do this, for your "write" block, is to make sure the elements you expect to be there, are actually there.
To start, I would rewrite your loop as follows:
while(!finished) {
List<String> input = reader.getInput();
if(input.size() == 0) {
throw new IllegalArgumentException("Must specify command, one of 'shutdown', 'load', 'write'");
}
final String command = input.remove(0).toLowerCase();
// TODO: Make sure command is one of the valid commands!
Note the changes:
Assigning to List instead of ArrayList is just a good general practice.
Checking the input to make sure it has more than zero elements
Taking the first element, since we don't want to have to do List.contains(). Consider the input garbage garbage garbage write, clearly we don't want this to invoke the "write" command, it should be considered invalid input.
Finally, we use this to rewrite the conditions on executing our commands:
if(command.equals("write")) {
// Make sure the user put the right stuff in here
// Since we removed the command from the input already, just make sure what is left is
if(input.size() <= 1) {
throw new IllegalArgumentException("Must specify correct data");
}
String key = input.remove(0);
String value = String.join(" ", input); // Java 8
instruct.mapWrite(key, value);
}
You are getting the error for below part of the code..
if (input.contains("write")) {
String key = input.get(1);// here is the problem..
String value = "";
for(int i=2; i<input.size(); i++) {
value = value + " " + input.get(i);
}
instruct.mapWrite(key, value);
}
in the line 2 of this code snippet. you are accessing a value by using the index. Now just imagine you just enter a single word in the console. so the arraylist you will get from the getInput() method will have the size of 1. So.. in the arraylist the word will be placed on 0th position.(that is the first position) but you are accessing the value on second position.. Thats gives you a index out of bond exception..
basically the fix was simpler than throwing a new exception and using a try and catch block. All I had to do was slightly change the logic and just use and if else statement.
if (input.contains("write")) {
if(input.size() >=2) {
String key = input.get(1);
String value = "";
for(int i=2; i<input.size(); i++) {
value = value + " " + input.get(i);
}
mapWrite(key, value);
} else {
System.out.println("Please type in the key & value after write all on line");
}
}
From what I have learned from java so far, is that the best solutions are normally always normally the simplest. Thanks for all the help, everyone who commented and tried to help me basically helped me come up with the idea.
My question is about Java.
Is there a way to print out a String in the console when using Scanner so the user can edit and/or add more to it?
For example...
String aString = "Hello!"
System.out.println("Write some text, please.");
aString = scanner.nextLine();
And now I want some sort of System.out of aString but editable. I want the user to be able to simply edit aString. When user finish editing, Scanner will save everything to aString again.
My solution right now is I let the user input some new text and then just add it to the end of the String using:
aString += scanner.nextLine();
Appreciate any help. Thank you.
You may be able to approach what you want with the Robot class. Try the following, for example:
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.Scanner;
public class RobotText {
static private Robot robot;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter some text, blank line to end.");
int count = 1;
while (true) {
System.out.print("?>");
insert("Line " + count);
count++;
String line = input.nextLine();
if (line.length() == 0) break;
System.out.println("You entered '" + line + "'");
}
System.out.println("That's all folks!");
input.close();
}
private static void insert(String text) {
if (robot == null) {
// Lazily initialise the robot
try {
robot = new Robot();
robot.setAutoDelay(5);
robot.setAutoWaitForIdle(true);
} catch (AWTException e) {
e.printStackTrace();
}
}
char[] chars = text.toCharArray();
for (char c : chars) {
int code = KeyEvent.getExtendedKeyCodeForChar(c);
robot.keyPress(code);
robot.keyRelease(code);
}
}
}
This inserts the text you want the user to edit as keystrokes, before using the Scanner to read the resulting line. Note - don't insert a newline or the user will never get a chance to type!
Unfortunately you will still be at the mercy of whatever line editing facility is provided by the shell you run your application from. In my case that means that all the user can do with the above is backspace over as much of the pre-entered text as needed before retyping a replacement.
To avoid this you will need to replace the use of Scanner with something a bit more sophisticated. I haven't tried it, but it looks like JLine may fill your needs here.
For extreme overkill, in an environment where a GUI can run, or if for some reason you are not able to add new jars to your classpath, you could also use JOptionPane for input:
...
while (true) {
String line = JOptionPane.showInputDialog("Enter some text","Line "+count);
count++;
if (line == null || line.length() == 0) break;
System.out.println("You entered '" + line + "'");
}
...
This does start up a new Swing Event thread for each line of input, and then shut it down again afterwards, so it really is using a cannon to kill a fly! But of course it requests input in a separate window from the console, which may deviate too far from your goal.
Ultimately the answer would be to give your application a graphical interface, as every text input widget provided by every toolkit I've ever met allows you to pre-initialise the widget with text that can be subsequently edited by the user. I shall leave the choice of toolkit and the implementation as an exercise to the reader. :)
I apologize since I'm always asking n00b questions but I could really use the help. Anyways I'm trying to import words of only a certain length from the dictionary into the variable words which is a hash set. When I run my program and try to print my words aka the hashset of strings. I get nothing in the console and the program does not stop running. How can I fix this? P.S. Also I know part of the JOptionPane code got cut enough, but it's error free and you get the point. Thanks!
Alex
public void inputWords()
{
try
{
frame = new JFrame("Hangman");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
input = new Scanner(new FileInputStream("dictionary.txt"));
wordLength = Integer.parseInt( JOptionPane.showInputDialog(null,
String importedWords = input.nextLine();
while(stillHasWords==true)
{
if(importedWords.length()==wordLength)
{
words.add(importedWords);
}
else
{
}
}
}
catch(FileNotFoundException f)
{
System.out.println("File does not exist.");
System.exit(0);
}
catch(NoSuchElementException q)
{
stillHasWords=false;
}
public static void main(String[] args)
{
EvilHangman j = new EvilHangman();
System.out.println(stillHasWords);
j.inputWords();
System.out.println(words + " ");
}
}
Regarding:
while(stillHasWords==true)
{
if(importedWords.length()==wordLength)
{
words.add(importedWords);
}
else
{
}
}
I'm not sure what words.add(importedWords) does, but most important to the problem you're experiencing,
Question: Where do you change stillHasWords inside of your loop?
Answer: You don't, and so the loop will never end.
I suggest that first you fix this while loop
As an aside, it's better to avoid using == true in a while loop and instead simply test the boolean:
while (stillHasWords) {
// add a word
// change stillHasWords to false if we've run out of words
}
Edit
You state:
Still has words changes in the catch(NoSuchElementException q)
There is no catch block posted inside of the while loop, and so I submit that still the stillHasWords value cannot change inside of the while loop based on code you've posted so far. If you have more pertinent code, then you'll of course want to show it, else we're reduced to guessing what might be wrong with code not shown. Best to post an SSCCE