I have looked around and couldn't find a solution. My code is supposed to take input from the user and stop when there input is blank. The code was simple at first but now I think I've over complicated it so sorry about it.
Scanner read = new Scanner(System.in);
System.out.println("Input words, enter blank to stop");
boolean working = true;
do {
if(working == false)
{
break;
}
String a = read.next();
if (a.equals("")) {
working = false;
System.out.println("no data");
} else {
Container.addWord(a);
}
} while (working == true);
Thanks.
Change next() to nextLine():
Scanner read = new Scanner(System.in);
System.out.println("Input words, enter blank to stop");
boolean working = true;
do {
if (working == false) {
break;
}
String a = read.nextLine();
if (a.isEmpty()) {
working = false;
System.out.println("no data");
} else {
Container.addWord(a);
}
} while (working == true);
Have you tried using String#trim().isEmpty()
It'll also consider strings like " " to be empty.
do {
String a = read.next();
if (a.trim().isEmpty()) {
working = false;
System.out.println("no data");
} else {
Container.addWord(a);
}
} while (working);
Here is a bit more elegant version
public static void main(String...args){
Scanner read = new Scanner(System.in);
String line = null;
System.out.println("Enter text:");
while(!(line=read.nextLine()).equals("")){
System.out.println("Your text:"+line);
System.out.println("Enter text or press enter to exit:");
}
System.out.println("Bye bye !!!");
}
I think your code could be replaced with the following:
Scanner read = new Scanner(System.in);
System.out.println("Input words, enter blank to stop");
while(true) {
if (!read.hasNext()) {
System.out.println("no data");
break;
}
String a = read.next();
Container.addWord(a);
}
I also removed the working variable and replaced it with a break statement.
If you change read.next() to read.nextLine() be sure to also update the read.hasNext() to read.hasNextLine().
yourString.isEmpty() || yourString.equals("")
You can simplify the whole thing:
Scanner read = new Scanner(System.in);
System.out.println("Input words, enter blank to stop");
boolean working = true;
do {
String keyEntered = read.nextLine();
if (keyEntered.isEmpty()) {
working = false;
System.out.println("No data");
} else {
System.out.println("You entered: " + keyEntered);
}
} while (working);
Related
Java newbie here... I want to scan some user input after a button is pressed. The first thing that I scan from keyboard works fine but in the second input the programm crashes. I believe the problem is with the second use of try{//blocks of code}finally{input. close();} (same code though). I used it so I can get out of the scanning process. I need your sights. Thx for the help. Here is my code:
#Override
public void action Performed(Action Event e) {
if(e.getSource()==button1){
System.out.println("Sth");
label1.setVisible(true);
Scanner input = new Scanner(System.in);
try {
String userInput = "";
System.out.println("Asking the user a q, (yes/no)");
userInput = input.nextLine();
if(userInput.equalsIgnoreCase("yes")) {
System.out.println("Okay");
int Temp = input.nextInt();
System.out.println("Print the scanned value");
input.close();
}else if(userInput.equalsIgnoreCase("no")) {
System.out.println("Default answer to q");
}
}finally{
input.close();
}
} else if(e.getSource()==button2){
System.out.println("Sth");
label2.setVisible(true);
Scanner input = new Scanner(System.in);
try {
String userInput = "";
System.out.println("Q for user, (yes/no)");
userInput = input.nextLine();
if(userInput.equalsIgnoreCase("yes")) {
System.out.println("Sth");
int Time = input.nextInt();
System.out.println("" + Time + "");
input.close();
}else if(userInput.equalsIgnoreCase("no")) {
System.out.println("Okay");
}
}finally{
input.close();
}
}
}
public class Menu extends AirPorts{
public static String checkerUK() {
Scanner sc = new Scanner(System.in);
boolean valid = false;
String ukAP = "";
while(valid == false) {
System.out.println("Please enter the code of the UK AirPort ");
ukAP = sc.next();
if(ukAP.equalsIgnoreCase(ukOne)) {
valid = true;
break;
}
if(ukAP.equalsIgnoreCase(ukTwo)) {
valid = true;
}
else {
System.out.println("Please try again");
}
sc.close();
}
return ukAP;
}
}
I'm trying to get checkerUK to return the ukAP within the while loop. The current error I have is,
ukAP cannot be resolved or is not a field
for line, Scanner sc = new Scanner(System.in);. It seems to be that ukAP is local to the while loop, and I have tried to put, "return ukAP" within the while loop but then I get an error saying that checkerUK needs to return a String, so it doesn't recognise it.
I have also tried to create a public/global ukAP for the whole class but that doesn't have any affect on the ukAP within the while loop.
I'm using Eclipse and Java 14.
This works for me.
public static String checkerUK() {
final String ukOne = "LTH";
final String ukTwo = "LGW";
Scanner sc = new Scanner(System.in);
boolean valid = false;
String ukAP = "";
System.out.print("Please enter the code of the UK AirPort: ");
while (valid == false) {
ukAP = sc.nextLine();
switch (ukAP) {
case ukOne:
case ukTwo:
valid = true;
break;
default:
valid = false;
System.out.print("Please try again: ");
}
}
return ukAP;
}
Java supports string switch since Java 7. The values must be constant, though. That's why I declared them as final.
Never close a Scanner that wraps System.in.
import java.util.Scanner;
public class CurrencyTester
{
public static void main(String[]args)
{
i want to loop from the beginning, but not to ask the user to type in for same converter, how do i do it?
CurrencyConverter one= new CurrencyConverter();
System.out.println("Convert dollar to euro/gbp/cad");
i want to ask for the input euro gbp or cad after the first loop
System.out.println("enter euro/gbp/cad");
System.out.println("");
Scanner input = new Scanner(System.in);
String a = input.next();
if("euro".equalsIgnoreCase(a))
{
euro
do {
System.out.println("Enter Dollars:");
Scanner in = new Scanner(System.in);
String d = in.next();
if ("Q".equalsIgnoreCase(d)) {
System.out.println("Stop!");
break;
} else {
try {
double ds = Double.parseDouble(d);
one.setDollar(ds);
System.out.println("Euro:");
System.out.println("€"+one.getCurrencyE());
} catch (NumberFormatException e) {
System.out.println("Not double,wrong input");
}
}
} while (true);
}
if("gbp".equalsIgnoreCase(a))
{
GDP
do { System.out.println("Enter Dollars:");
Scanner in = new Scanner(System.in);
String d = in.next();
if ("Q".equalsIgnoreCase(d)) {
System.out.println("Stop!");
break;
} else {
try {
double ds = Double.parseDouble(d);
one.setDollar(ds);
System.out.println("GDP:");
System.out.println("£"+one.getCurrencyG());
} catch (NumberFormatException e) {
System.out.println("Not double,wrong input");
}
}
} while (true);
}
if("cad".equalsIgnoreCase(a))
{
CAd
do { System.out.println("Enter Dollars:");
Scanner in = new Scanner(System.in);
String d = in.next();
if ("Q".equalsIgnoreCase(d)) {
System.out.println("Stop!");
break;
} else {
try {
double ds = Double.parseDouble(d);
one.setDollar(ds);
System.out.println("Canadian Dollar:");
System.out.println("$"+one.getCurrencyC());
} catch (NumberFormatException e) {
System.out.println("Not double,wrong input");
}
}
} while (true);
}
}
}
}
I tried to use while loop in the beginning ,but it doesn't work.
The main problem with your existing code is that you have duplicated the same logic in three different places. What you instead want to do is group any code that is common for all your different cases into methods or otherwise structuring your logic so you don't have to duplicate it.
Here is one way to structure your code in a more readable and maintainable way:
public static void main(String[] args) {
CurrencyConverter one = new CurrencyConverter();
do{
System.out.println("Convert dollar to euro/gbp/cad");
System.out.println("enter euro/gbp/cad");
System.out.println("");
Scanner input = new Scanner(System.in);
String a = input.next();
String d = enterDollars();
if( d == null )
break;
try {
double ds = Double.parseDouble(d);
one.setDollar(ds);
if( "euro".equalsIgnoreCase(a) )
System.out.println("Euro:\n€" + one.getCurrencyE());
else if( "gbp".equalsIgnoreCase(a) )
System.out.println("GBP:\n£" + one.getCurrencyG());
else if( "cad".equalsIgnoreCase(a) )
System.out.println("Canadian Dollar:\n$" + one.getCurrencyC());
}
catch (NumberFormatException e) {
System.out.println("Not double,wrong input");
}
} while (true);
}
private static String enterDollars(){
System.out.println("Enter Dollars:");
Scanner in = new Scanner(System.in);
String d = in.next();
if ("Q".equalsIgnoreCase(d)) {
System.out.println("Stop!");
return null;
}
return d;
}
I have put the code for getting user input in dollars into its own separate method, which makes the code easier to read. Similarly, you could further divide your code into smaller methods (like enterCurrency(), presentResult(), etc) to make your main method more readable.
You are copying and pasting similar pieces of logic. This is not good practice and typically means you should start creating functions for similar behavior. I am not sure how far into programming you are so I am going to show you a simple way to get input from the user using a single do/while and another do while for grabbing a valid dollar amount.
Put this in your main
CurrencyConverter one= new CurrencyConverter();
Scanner input = new Scanner(System.in);
System.out.println("Convert dollar to euro/gbp/cad");
HashSet<String> conversions = new HashSet<>();
conversions.add("euro");
conversions.add("gdp");
conversions.add("cad");
System.out.println("");
String userInput = "";
do {
System.out.println("enter euro/gbp/cad");
userInput = input.nextLine();
double amount = 0;
//check to see if we need to get a dollar amount
if(conversions.contains(userInput))
{
do {
System.out.println("Enter Dollars:");
String sAmount = input.nextLine();
amount = Double.MAX_VALUE;
//check it's a number before parsing
if(sAmount.matches("\\d+"))
{
amount = Double.parseDouble(sAmount);
//then set it for the object once
one.setDollar(amount);
}
else
{
System.out.println("Error when parsing dollar amount: " + sAmount);
System.out.println("Please Try again!");
}
} while (amount != Double.MAX_VALUE);
}
//check for euro
if(userInput.equals("euro"))
{
System.out.println("Euro: ");
System.out.println("€"+one.getCurrencyE());
}
else if(userInput.equals("gdp"))
{
System.out.println("GDP: ");
System.out.println("£"+one.getCurrencyG());
}
else if(userInput.equals("cad"))
{
System.out.println("Canadian Dollar: ");
System.out.println("$"+one.getCurrencyC());
}
else if (!userInput.equals("quit"))
{
System.out.println("Error with input : " + userInput);
}
} while (!userInput.equals("quit"));
I have a simple do while loop here. The only problem I am having is this loop right now is only accepting numbers. I need it to accept everything except a blank input.
import java.util.Scanner;
public class Assignment6 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean notValid = true;
int numberAsInt = 0;
do {
try {
System.out.print("Enter a number to Convert > ");
String number = scan.nextLine();
numberAsInt = Integer.parseInt(number);
notValid = false;
}
catch (Exception e) {
}
} while (notValid);
}
}
I'm a bit confused on what you asked because you are parsing the result in your code, but I hope this is what you are asking of:
public class Assignment6 {
public static void main(String[]args){
Scanner scan = new Scanner( System.in );
boolean notValid = true;
String input;
do{
System.out.print( "Enter a number to Convert > " );
input = scan.nextLine( );
if(!input.isEmpty())
notValid = false;
} while ( notValid );
}
}
You can do something like:
String number = readLine("Enter a number to Convert > ");
while(number.isEmpty()){
number = readLine("Please enter a *non-blank* number > ");
}
Here we are comparing if entered value is space than not valid will be true
try {
System.out.print( "Enter a number to Convert > " );
String number = scan.nextLine( );
if(number.equals(" "))
{
notValid = ture;
sysytem.out.println(" Please do not enter blank space");
}
else
{
numberAsInt = Integer.parseInt(number);
notValid = false;
}
}
Use this snippet in your code:
if(number.trim().equals(""))
{
notValid = ture;
sysytem.out.println(" Please do not enter blank space");
}
public class Main {
public static void main(String[] args)
{
int ch = 0;
do
{
Scanner in = new Scanner(System.in);
String s;
System.out.println("Enter the part number");
s=in.nextLine();
try{
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Ankit\\Documents\\NetBeansProjects\\tcs_1\\number.txt"));
BufferedReader Br = new BufferedReader(new FileReader("C:\\Users\\Ankit\\Documents\\NetBeansProjects\\tcs_1\\number1.txt"));
String strLine;
int flag=0;
while ((strLine = br.readLine()) != null)
{
if(strLine.equals(s))
{
flag=1;
System.out.println ("Part Number exists in 1");
break;
}
else
{
flag=0;
System.out.println ("Part Number doesnot exist in 1");
break;
}
}
if(flag==0)
{
while ((strLine = Br.readLine()) != null)
{
if(strLine.equals(s))
{
System.out.println ("Part Number exists in 2");
break;
}
else
{
System.out.println("File does not exist in 2");
break;
}
}
}
System.out.println ("Do you want to continue-Press1 for yes and 2 for no");
ch= in.nextInt();
br.close();
Br.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
while(ch==1);
}
}
this is the program that I made to search a user given string from 2 diff text files. Its working fine but only searching the first line.
eg.: If a file has
1000
1001
1002
it wll only search 1000. How do I go to next line and keep on using the .equals() method?
You should use Scanner not BufferedReader as it's a more recent class
and I feel does a nicer job with this task. Especially since you have
already used Scanner elsewhere in your code and thus imported it.
Below is a scanner that will read all the lines in a file while there
is a next one to read.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class JavaApplication32
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Scanner scanner1 = null;
Scanner scanner2 = null;
String partCheck;
String repeatLoop;
boolean isInOne;
boolean isInTwo;
File file1 = new File("data1.txt");
File file2 = new File("data2.txt");
try
{
scanner1 = new Scanner(file1);
scanner2 = new Scanner(file2);
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
do
{
isInOne = false;
isInTwo = false;
System.out.println("Enter the part number");
partCheck = keyboard.nextLine();
while (scanner1.hasNextLine() && !isInOne)
{
String line = scanner1.nextLine();
if(line.equals(partCheck))
{
System.out.println("Part Number exists in 1");
isInOne = true;
}
}
if(!isInOne)
{
System.out.println("Part Number does not exist in 1");
}
while(scanner2.hasNextLine() && !isInOne && !isInTwo)
{
String line = scanner2.nextLine();
if(line.equals(partCheck))
{
System.out.println("Part Number exists in 2");
isInTwo = true;
}
}
if(!isInTwo)
{
System.out.println("Part Number does not exist in 2");
}
System.out.println("Do you want to continue? (Y/N)");
repeatLoop = keyboard.nextLine();
} while(repeatLoop.equalsIgnoreCase("y"));
scanner1.close();
scanner2.close();
}
}
Example Text File data1.txt:
Test1
Test2
Test3
Test4
Example Test File data2.txt
Check1
Check2
Check3
Check4
Example stdout when code is run with these datafiles:
run:
Enter the part number
Test1
Part Number exists in 1
Part Number does not exist in 2
Do you want to continue? (Y/N)
y
Enter the part number
Check1
Part Number does not exist in 1
Part Number exists in 2
Do you want to continue? (Y/N)
n
BUILD SUCCESSFUL (total time: 19 seconds)
You also shouldn't put all of your read in information in a loop. By
putting do at the top you effectively keep creating a new set of
BufferedReaders and naming them the same thing and telling to do the
same thing and then telling them to break after the first hit. If you
did actually get rid of the break you'd have even more problems since
all of this other stuff is in the loop where it shouldn't be.
Since you have used
break;
in while loop it will exit from the loop after check first line. Try removing break; if you want to read all lines.