BlueJ and Input from keyboard - java

i have written the following code:
import java.io.*;
public class Typer
{
public static void main(String[] args)
{
Console cons;
cons = System.console();
boolean edition = true;
if(cons == null)
{
edition = false;
}
if(edition)
{
String name = cons.readLine("Give your name: ");
System.out.println("Your name is: "+ name);
}
else
{
System.out.println("There is no console!");
}
}
}
i am using BlueJ and it doesn't prompt for an input. it just prints out there is no console! Any thougts? Thanks you!
When i compile and run the program at powershell it runs normally. the thing is different with bluej for some reason.

To input any value using BlueJ, I normally use the BufferedReader statement.
It goes like this,
BufferedReader name=new BufferedReader(new InputStreamReader(System.in));
After writing this statement in the class or the method, you can input any value using the console.
Be sure to give this statement after asking for a value.
In case of integers-
int variable name= Integer.parseInt(name.readLine);

I think that BlueJ has a View>Console or a View>Output window. I am fairly certain of that, but it's been a long time since I used Bluej. Anyhow, You can use a Scanner object. The Scanner is a good way of handling input and I think it is more commonly used for input. It is a part of the Java API and examples of how to use it can be found here:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
The code shown on the page is used to scan from a file, but the same approach can be used to get input from the console and then do something with that. When you run the code and wherever you see the output from the System.out.println call, the program should wait for you to enter something.

Related

Java Homework Assignment — java.util.NoSuchElementException: No line found

I get an error from automated JUnit 4 unit testing software that my course instructor uses to automatically check assignments.
We upload our draft code to a cloud program tester which automatically checks and grades the assignments.
This is week 1 of first semester. I've never coded in Java before. And the lessons haven't taught if/else, while, loops, switch etc. so I don't think it's okay to use those (they appear next module.)
I followed a class video tutorial, which doesn't throw any exceptions in the tutorial — so I don't know what's going on.
The unit was on variables, input, printing out, Booleans, operators, and a few things like contains, replace, equals etc.
Note: I am allowed to ask questions on StackOverflow per instructor.
The error is: java.util.NoSuchElementException: No line found
No line number is specified in the testing software where the exception occurs. And since it's not happening in my IDE, I don't know where it is.
Other solutions I've found require while and other methods I'm not supposed to use.
My code (below) runs okay in the VSCODE IDE cloud the school provided.
import java.util.Scanner;
public class ContainsAnyCase {
public static void main(String[] args) {
System.out.println("Type a word:\n");
Scanner userInputWord = new Scanner(System.in);
String word = userInputWord.nextLine();
String wordlc = word.toLowerCase();
System.out.println("Type a sentence:\n");
Scanner userInputSentence = new Scanner(System.in);
String sentence = userInputSentence.nextLine();
String sentencelc = sentence.toLowerCase();
boolean isContains = sentencelc.contains(wordlc);
System.out.println(isContains);
}
}
I'm wondering if anyone can explain why there is an error and if there are ways to fix it or avoid the error without going into the territory of future modules? Also, I'm still learning how to use Stack Overflow appropriately. If I asked my question wrong, please advise how I can improve my question or post. Thank you.
I expected for the program to tell me true/false if the word was in the sentence. In my IDE, it worked. When I uploaded it to the JUnit4, it said java.util.NoSuchElementException: No line found
Here's an example of using just ONE SCANNER as suggested in the comments.
I've also eliminated the second set of variables for lower case; just convert the input directly to lower case and store it in the original variable:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a word:\n");
String word = sc.nextLine().toLowerCase();
System.out.println("Type a sentence:\n");
String sentence = sc.nextLine().toLowerCase();
boolean isContains = sentence.contains(word);
System.out.println(isContains);
}
If you need to preserve the exact user input for later, then you can convert to lower case only when you call contains() like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a word:\n");
String word = sc.nextLine();
System.out.println("Type a sentence:\n");
String sentence = sc.nextLine();
boolean isContains = sentence.toLowerCase().contains(word.toLowerCase());
System.out.println(isContains);
}

Problems with Input and output regarding Java String

Well Hello,
I´m trying to program a kind of game in my free right now.
I started coding some time ago in school but recently we didn´t do much with java so I thought I should do something, so that I don´t forget everything. Well, I still need some since we never did something that's kind of like this. My Problem is that it shows an error and tells me an symbol is missing. The program is supposed to start the game and later interact with different types of objects that contain character information such as stats for both monsters and the player.
import java.util.Scanner;
public class Spiel{
public static void main(String[] args) {
System.out.print("What is your name Adventurer?\n ");
Scanner scanner = new Scanner(System. in);
String Abenteurername = scanner. nextLine();
System.out.println("Adventurer "+Abenteurername+" will you help us clean the dungeon? \n");
String Spielstart = scanner. nextLine();
if (Spielstart.equalsIgnoreCase(ja)) {
System.out.println("Gut");
} else {
System.exit(0);
} // end of if-else
}
}
As you wrote ja without quotes, it expects to find a variable defined with that name, like
String ja = "ja";
if (Spielstart.equalsIgnoreCase(ja)) {
System.out.println("Gut");
}
But what you want is just
if (Spielstart.equalsIgnoreCase("ja")) {
System.out.println("Gut");
} else {
System.exit(0);
} // end of if-else

How do I read both from keyboard and from file?

I have a Scanner that could be reading from either keyboard or from a file (via pipes), and apparently there's no way to tell which.
I have te following code:
Scanner scan = new Scanner(System.in);
while (scan.hasNextLine()) {
String line = scan.nextLine();
doStuff();
}
That works wonderfully when redirecting input to a file. But if I try to run the program by itself and read from keyboard, it enters an infinite loop. Is there a way to differentiate between reading from keyboard and from a file? Thanks in advance!
Edit 1:
As requested by #Abra, this is what my code looks like with your suggestion:
Scanner scan = new Scanner(System.in);
do {
String linea = scan.nextLine();
doStuff();
} while (System.in.available() != 0 && scan.hasNextLine());
And here's the command I'm running:
java -jar Class.jar < File.txt
Edit 2:
Solved it, turns out I should only evaluate System.in.available() != 0 once:
Scanner scan = new Scanner(System.in);
boolean file = System.in.available() != 0;
do {
String linea = scan.nextLine();
doStuff();
} while (file && scan.hasNextLine());
The classic practice used commonly in Linux and Unix is to read input from standard input, as you are already doing. In Java, standard input is called System.in.
The program reads from standard input and processes what it reads in a loop until it detects end-of-file, which you are already doing.
So your program is not stuck - it is merely waiting for more input or for the end-of-file signal to come from the outside.
If you want to use this program with input from a file, you run it like this:
myprogram < input_file.txt
And if you want your program to get its input from terminal (where you type it), you run it just like
myprogram
In this case, and after typing your input, you are also responsible to send a special signal from your terminal that will act as a "end-of-file" and will be picked by the program, causing the while-loop to exit. Typically, you do this by pressing Control-D.
Keep in mind that reading from standard input is not strictly the same as reading from keyboard. Standard input only knows about text and end-of-file; it has no concept of line editing, testing for when shift key is pressed/released etc.
The class of System.in is java.io.InputStream. That class has method available(). If you redirect System.in to a file, as in
myprogram < input_file.txt
Then method available() returns a number greater than zero (assuming that input_file.txt has non-zero size) but when System.in refers to the standard input stream, i.e. when you run your program without redirecting standard input, as in
myprogram
Then method available() returns zero.
based on the answer of #Abra you can break the loop if System.in is keyboard so:
import java.util.Scanner;
import java.io.IOException;
public class Main {
public static void main(String[] argv) throws IOException {
Scanner scan = new Scanner(System.in);
boolean isKeyboard = System.in.available() == 0;
while (scan.hasNextLine()) {
String line = scan.nextLine();
doStuff();
if (isKeyboard) {
break;
}
}
}
}

Why does my evenOdd code produce an output?

I'm a first year university student starting my computer science major so sorry for any rookie mistakes. We've just gotten to if/else statements and practice mostly on this website called "Practice-It!", a coding practice website for Java, C++, and Python although I'm currently learning Java. Now, I recently got to this problem called "evenOdd" in which we need to read an integer from the user and print "even" if its an even number or print "odd" if it's an odd number. The exact problem goes as follows:
Write Java code to read an integer from the user, then print even if that number is an even number or odd otherwise. You may assume that the user types a valid integer. The input/output should match the following example:
Type a number: 14
even
I'm pretty sure I know how to do this, but when I enter in my bare code, it produces no output. I'm unsure of why. My code goes as follows:
int number;
Scanner console = new Scanner(System.in);
System.out.print("Type a number: ");
number = console.nextInt();
if (number % 2 == 0) {
    System.out.println("even");
} else  if (number % 2 != 0) {
    System.out.println("odd");
}
I should mention I'm supposed to put in bare code, meaning no class or methods.
I'm not sure if it's just me or maybe the website's slightly faulty. Any help is much appreciated.
Your code is sound, but if that is all the code you submit to the compiler then it won't work. You need to import the Scanner class from java.util.Scanner and you need to run your code inside a function and a class, unlike python which can run free in an IDE or console. Here is the code that worked for me.
import java.util.Scanner;
public class temp{
public static void main(String [] args){
int number;
Scanner console = new Scanner(System.in);
System.out.print("Type a number: ");
number = console.nextInt();
if (number % 2 == 0) {
System.out.println("even");
} else if (number % 2 != 0) {
System.out.println("odd");
}
}
}
Hope that helps.
I would suggest you use some IDE like Eclipse or NetBeans. These IDEs will help you in writing and debugging your code. They will also mark errors in your code and also provide description and quick fix which will help you code.
package abc.xyz.test;
import java.util.Scanner;
public class EvenOdd
{
public static void main(String... args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
if (input.nextInt() % 2 == 0)
{
System.out.println("even");
}
else
{
System.out.println("odd");
}
input.close();
}
}
You can download eclipse from https://www.eclipse.org/downloads/ and NetBeans from https://netbeans.org/downloads/. Both of them are free, you don't have to pay anything for using them.
You need to import the scanner from java.util package. In every java program there must be a main method. try the following code. Look at my code i am creating an instance of Scanner named userInput and at the end of my code i am calling the close() method to prevent resource leak. you will not get any error for not closing but it is part of good practice.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int number = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("Type a number");
number = userInput.nextInt();
if( number % 2 == 0 ) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
userInput.close();
}
}

BlueJ - My program compiles with no errors but doesn't run

Hello I'm having problems with a program that's supposed to take in a string and then capitalize the first letters of each word using the Character Wrapper class.
import java.util.*;
public class wrapper
{
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
String s1;
s1=input.nextLine();
s1= s1.trim();
int howLong= s1.length();
int i;
int counter=0;
char cho;
for(counter=1; counter<= howLong+1; counter++)
{
cho=s1.charAt(counter);
if(Character.isLetter (cho) && ! Character.isLetter(s1.charAt(counter-1)))
{
System.out.print( Character.toUpperCase(cho) );
}
else
{
System.out.print(cho);
}
System.out.println();
}
}
}
That's the program so far, but while it compiles with no errors according to BlueJ, it doesn't run. Any help as to why this is happening would be great.
Edit: Changed the program to what I believe would make it not just print out the spaces that the char variable was initialized to, but it still does not run. Maybe there's something wrong with the loop?
The reason your program compiles but doesn't run is because of the line s1=input.nextLine();. At this line, the program is waiting for input from the user to use as the string s1, but does not show the terminal in order for the user to give such input. A way you can get around this is to force the terminal to show itself before that line. I would recommend putting something like
System.out.println("Enter input:");
before the line, so that the terminal will show itself & the user can enter input into it. From there, you can work on the program like you would normally.

Categories