Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 months ago.
Improve this question
How do you write a Java program that accepts number as input and based on the value entered, displays a message?
Like
"1" displays "Yes"
"2" displays "No"
The main thing you will want to look into is the Java Scanner. You can import it via import java.util.Scanner; To make a new Scanner which reads from the console you will write:
Scanner userInput = new Scanner(System.in);
Scanners are very versatile, so they are built to read from any input stream. This could be a file, a String, or many other things. Just like System.out is an output stream to the console, System.in is an input stream from the console.
For more information you can read the scanner documentation here.
Now with your scanner created to get a number input we can use the nextInt() method.
int input = userInput.nextInt();
Here is a simple program similar to what you described.
import java.util.Scanner;
public class ScannerInputTest{
public static void main(String[] args){
Scanner userInput = new Scanner(System.in);
System.out.print("Enter Input > ");
int input = userInput.nextInt();
if(input == 1){
System.out.println("Yes");
}else if(input == 2){
System.out.println("No");
}else{
System.out.println("I don't Know");
}
}
}
Since you are just starting out please try your best to read through documentation, and don't just copy and paste answers from here. Try to tinker and change things to get a better understanding.
If you are going to be making a lot of console programs, I highly recommend also looking into switch statements, as if else statements will eventually become very bloated the more branches you need.
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 4 months ago.
Improve this question
I need to read from a text file in java and pass that information through a polymorphic method. My idea is a CryptoWallet in a .txt file reading as coin, amount and value, where in the text file its represented as Bitcoin 100 1.25.
Ive got the code reading from the file and printing it, as below.
public class CryptoCurrencies
public static void main (String[] args) throws IOException
{
System.out.println("Welcome to your Crypto Wallet"
+ "\nCurrently, you only own one coin.");
File CryptoWallet = new File("/Users/curti/OneDrive/Desktop/crypto.txt");
Scanner scan = new Scanner(CryptoWallet);
String fileContent = " ";
while(scan.hasNextLine())
{
System.out.println(scan.nextLine());
continue;
}
My main issue is actually getting the text file too recognise the numbers as doubles and variables, and assigning them to run through a polymorphic method. I understand the polymorphism side, but if anyone has any ideas for a possible polymorphic method id really appreciate it, having trouble thinking at the moment!
Thanks everyone.
It is unclear what role polymorphism is supposed to have here.
Assuming that each row represents a record and each record has the same form then we can parse each row in an identical fashion. That allows you to extract the numeric values using the parse methods in the appropriate Number classes.
For instance...
while(scan.hasNextLine()) {
String line = scan.nextLine());
String[] tokens = line.split(" ");
String name = tokens[0];
int amount = Integer.parse(tokens[1]);
double value = Double.parse(tokens[2]);
}
p.s. obligatory comment that you shouldn't represent money in floating point variables.
Split the current line by space or "\s+" regex, check if the length is 3, then use the double.parse function from the double object on the 2nd and 3rd element in the array.
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 1 year ago.
Improve this question
I'm trying to understand why my java code doesn't behave as I expect it to do.
I want to print the question once, wait for the user to input their answer, then decide whether to loop back or proceed depending on the answer.
When I run the code below, the question gets printed twice, and the loop didn't stop and wait for user input after its first run.
Scanner input = new Scanner(System.in);
String answer = "";
while (!answer.equals("Yes") && !answer.equals("No")){
System.out.println("abc1");
System.out.println("Do you want to quit the game? Answers: y/n");
System.out.println("abc2");
System.out.println("abc3");
answer = input.nextLine();
System.out.println("abc4");
}
I don't think I need a second .nextLine(), because the first one already consume the end of the input line (\n). But for the sake of experimenting, I modified the code by adding an extra .nextLine() (as shown below). Two problems with this new code:
On the first run (first loop), the code skips the first .nextLine() and waits for user input at the second .nextLine() (I can tell this is the case because "abc3" gets printed before I, as a user, can input anything).
Starting from the second loop, the code prints "abc2", wait for user input, prints "abc3", then wait for user input again.
Scanner input = new Scanner(System.in);
String answer = "";
while (!answer.equals("Yes") && !answer.equals("No")){
System.out.println("abc1");
System.out.println("Do you want to quit the game? Answers: y/n");
System.out.println("abc2");
answer = input.nextLine();
System.out.println("abc3");
answer = input.nextLine();
System.out.println("abc4");
}
I modified the code further (answer = input.nextLine(); vs just answer = input.nextLine();) and still get the same behaviors.
Scanner input = new Scanner(System.in);
String answer = "";
while (!answer.equals("Yes") && !answer.equals("No")){
System.out.println("abc1");
System.out.println("Do you want to quit the game? Answers: y/n");
System.out.println("abc2");
input.nextLine();
System.out.println("abc3");
answer = input.nextLine();
System.out.println("abc4");
}
What do I get wrong here?
Any advice is greatly appreciated!
I found where the mistake was! I left a .nextInt() elsewhere in my code but forgot I needed to consume the end of the line (\n). My (first) .nextLine() finished what had been left off by the .nextInt() without me realizing this was happening.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am stuck on some homework as i am new to java and still learning. I am wondering if it is possible to find a word in a .txt file and output the line that the word is on. I also need to allow a user to make a choice based on what is displayed back.
Example :
Word is Details
Txt file contains
Details on lion
Details on tiger
Output : "Details on tiger"
Thank in advanced for any help
This question has been answered before, but anyway You can go with this apporach.
Simply put:
Create a Scanner object and pass the required file into the
constructor as a new file object.
Iterate over the file with a
while loop until you find the specified string.
In order to store the lines that contains the desired word,we decalre a new string variable
Here's the code snippet:
Scanner scanner= new Scanner(new File("filename.txt"));
String lines = "";
while(scanner.hasNextLine()){
String stringLine = scanner.nextLine();
if(stringLine.indexOf("YOUR_WORD") != -1){
//print whatever you want here
System.out.println(stringLine);
//add every line that contains stringLine into another string;
lines+=stringLine;
}
}
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 9 years ago.
Improve this question
My issue is when I run the code in eclipse it just never seems to do anything at the bottom. The other day I made some almost identical programs and they worked fine. The only thing I can assume is going on is it never gets the input from scanner so it never prints the line so the program just keeps on running.
import java.util.Scanner;
public class testrun {
public static void main(String args[]){
String name;
Scanner get = new Scanner(System.in);
name = get.nextLine();
System.out.println(name);
}
}
You may need to type something and hit that ENTER key. The Scanner's nextLine() is waiting for input.
:)
It happens to us all.
The program works good and asks for input.
Keep some sop to print some helping statements and make it user friendly.
import java.util.Scanner;
public class Testrun {
public static void main(String args[]){
String name;
System.out.println("Please Enter : ");
Scanner get = new Scanner(System.in);
name = get.nextLine();
System.out.println(name);
}
}
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 9 years ago.
Improve this question
I want to make a JUnit testclass which tests a very simple method.
public static String whatsYourName() {
System.out.println("Input your name:");
yourName = in.next();
return yourName;
}.
My Question was regarded to how you could test a simple methode as above stated.
I think the below solution is perfect!
I would first change the method to take the Scanner as an argument (dependency injection principles):
public static String whatsYourName(Scanner in) {
System.out.println("Input your name:");
yourName = in.next();
return yourName;
}
Then it becomes easy to test:
#Test public void testName() {
Scanner in = new Scanner("my name");
assertEquals("my name", whatsYourName(in));
}
Now that only tests that your method extract the right information from the Scanner, it does not test that a user can actually input something - but that would be part of your integration tests, not unit tests.
Also note that your method is essentially equivalent to return in.next(); so you are actually testing the next method of Scanner, which is unnecessary. But if the method beocmes more complex the principle will apply.
A very interesting piece to read: Google guide on Writing Testable Code.