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");
}
Related
I am having a problem trying to understand how I can loop through a keyboard input line of text the user will give ex:
Anika 14 Dan 16
I want to read each token and assign to String name, Int, age, String name, int age. in that order.
This is easy however, if the user enters
Anika Anika Anika Anika 13 13 13 Dan 16
Then I want the program to:
Anika,
Integer needed got String,
Integer needed got String,
Integer needed got String,
13,
String needed got Integer,
String needed got Integer,
Dan,
16
So first one will always be a string which is a word EDIT: "word", second an int and thrid string which is a "word" and fourth int.
However, I can not simulate this.
Scanner scan = new Scanner(System.in);
String name = null;
int age = 0;
String name2= null;
int age2= 0;
if(scan.hasNext() == true)
name = scan.next();
age = scan.nextInt();
name2= scan.next();
age2= scan.nextInt();
I know if I do the top I get the right order, but it is the extra inputs that I would like to ignore but write a statement expression why it's wrong and then continue to search for the next int, or third string and so on.
boolean isstring = false;
boolean isnumber = false;
do {
if (scan.hasNext())
{
name = scan.next();
isstring = true;
}
else {
System.out.println("Need String got Integer");
isstring = false;
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt())
{
age = scan.nextInt();
isnumber=true;
}
else {
System.out.println("Need Integer got String");
isnumber=false;
scan.nextInt();
}
} while (!isnumber);
do {
if (scan.hasNext())
{
name2 = scan.next();
isstring = true;
}
else {
System.out.println("Need String got Integer");
isstring = false;
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt())
{
age2 = scan.nextInt();
isnumber = true;
}
else {
System.out.println("Need Integer got String");
isnumber=false;
scan.nextInt();
}
} while (!isnumber);
}
I tried to use do while with ifs and It didnt work. My logic is wrong somewhere, and I think it might be the has.next() method.
Any help will be appreciated!!
If the input is a word while waiting for an Integer, it will throw InputMismatchException. nextInt() first read the value as a String an then parse it as a Integer, so if you ignore the value using nextInt, if the value is a word, it will trow the aforementioned Exception.
Using the same logic of your program
The changes should be:
Ignore the input with scan.next()
Check if a String can be or not an Integer (using scan.hasNextInt()), not if is a String, because any Integer can be expressed as a String.
boolean isstring = false;
boolean isnumber = false;
do {
if (!scan.hasNextInt()) {
isstring = true;
name = scan.next();
} else {
isstring = false;
System.out.println("Need String got Integer");
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt()) {
isnumber = true;
age = scan.nextInt();
} else {
isnumber = false;
System.out.println("Need Integer got String");
scan.next();
}
} while (!isnumber);
do {
if (!scan.hasNextInt()) {
isstring = true;
name2 = scan.next();
} else {
isstring = false;
System.out.println("Need String got Integer");
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt()) {
isnumber = true;
age2 = scan.nextInt();
} else {
isnumber = false;
System.out.println("Need Integer got String");
scan.next();
}
} while (!isnumber);
Using try/catch and one loop
A naive solution using try/catch can be the following
public static void main (String[]args)
{
String name = null;
String name2 = null;
Integer age = null;
Integer age2 = null;
Scanner scan = new Scanner(System.in);
while (scan.hasNext())
{
try
{
if (name == null)
{
System.out.println("Please provide name: ");
name = getNameOrFail(scan);
System.out.println("Name set: " + name);
}
if (age == null)
{
System.out.println("Please provide age: ");
age = getAgeOrFail(scan);
System.out.println("Age set: " + age);
}
if (name2 == null)
{
System.out.println("Please provide name2: ");
name2 = getNameOrFail(scan);
System.out.println("Name2 set: " + name2);
}
if (age2 == null)
{
System.out.println ("Please provide age2: ");
age2 = getAgeOrFail (scan);
System.out.println ("Age2 set: " + age2);
}
}
catch (Exception e)
{
System.out.println(e.getMessage ()); // Print the message put int Exception(message) constructor
scan.nextLine(); // Flush the Scanner cache
}
}
}
public static String getNameOrFail(Scanner scan) throws Exception
{
if (scan.hasNextInt())
throw new Exception("Need String got Integer");
return scan.next();
}
public static Integer getAgeOrFail(Scanner scan) throws Exception
{
if (!scan.hasNextInt())
throw new Exception("Need Integer got String");
return scan.nextInt();
}
Pay attention to the scan.newLine() in the catch clause, this is needed because the Scanner use a cache with the last input, so if is not re-read you enter in a infinite loop condition.
Good luck!
package task;
import java.util.*;
public class Task {
public static void main(String[] args) {
System.out.println("Enter \"t\" to terminate.");
for(;;){
Scanner input = new Scanner(System.in);
int i;
double I = Double.POSITIVE_INFINITY;
for(i = 0; i <= I; i++){
System.out.println("Integer " + i);
String a = input.next();
if(a.equals("c")){
break;
}
}
}
}
}
I am having trouble in prompting the user to enter "t" to end the for loop. I basically want the for loop to print out every single positive integer, and when I decide to end, I enter "t".
If I could get some help, I'd appreciate it. Thanks!
You could simply use a do while instead of a for+break
Do while :
System.out.println("Enter \"t\" to terminate.");
Scanner input = new Scanner(System.in);
String pressed;
int i = 0;
while (true) {
i=0;
do {
System.out.println("Integer " + i);
pressed = input.next();
i++;
} while (!pressed.equals("t"));
}
Note that you are not testing if the input is an integer.
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 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);
I've been writing this program that is supposed to build accounts for people inputted, saving their info all together in as one "superString" string, so it can be written and read from a txt file. I thought I had it all together correctly, but after testing various inputs and then reading back, it seems as though it isn't setting up the string lengths correctly.
If I only want account number 1, it will print out the account number 1.
If I put more accounts in and then try to only print out account 1, it'll print out account 1 and part of 2.
The output changes based on the size of the inputs, even though I put loops in there to have strict sizes.
I've been looking at the same problem for too long now and hopefully I'm just overlooking an easy fix. Can anyone help me out with this?
public class FirstTr {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException, IOException
{
File loc = new File("C:\\Users\\Desktop\\Exc2.1.txt");
RandomAccessFile store = new RandomAccessFile(loc, "rw");
for(int i=0; i<20; i++)
{
String dummy = "12345678901234567890123456789012345678901234567890123456789012345678901";
store.writeUTF(dummy);
}
String userChoice = GettingUserInput();
System.out.println("The choice you entered: " +userChoice);
while(true){
if(userChoice.equals("new"))
{
String playerID = PlayerIDMethod();
System.out.println("The playerID you entered: " +playerID);
String playerName = PlayerNameMethod();
System.out.println("The playerName you entered: " +playerName);
String playerTeamName = PlayerTeamNameMethod();
System.out.println("The playerTeamName you entered: " +playerTeamName);
String playerSkillLevel = PlayerSkillLevelMethod();
System.out.println("The playerSkillLevel you entered: " +playerSkillLevel);
String todaysDate = TodaysDateMethod();
System.out.println("The date you entered: " +todaysDate);
String superString = "";
superString = playerID + playerName+ playerTeamName + playerSkillLevel + todaysDate;
//System.out.println("Combined string is: "+superString);
int playerIDDigit = Integer.parseInt(playerID);
store.seek((playerIDDigit-1)*73);
store.writeUTF(superString);
System.out.println("Length of string: " +superString.length());
userChoice = GettingUserInput();
}
if(userChoice.equals("old"))
{
System.out.println("Please enter player ID: ");
String desiredID = input.next();
int recLocation;
recLocation = Integer.parseInt(desiredID);
store.seek((recLocation-1)*73);
String printed = store.readUTF();
System.out.println("String: "+printed);
userChoice = GettingUserInput();
}
if(userChoice.equals("end"))
{
System.out.println("Program Closed.");
store.close();
System.exit(0);
}
}
}
public static String GettingUserInput()
{
System.out.println("Please type in a command: new, old, or end to exit");
String userChoice = input.next();
while(!userChoice.equals("New") && !userChoice.equals("new") && !userChoice.equals("Old") && !userChoice.equals("old") && !userChoice.equals("End") && !userChoice.equals("end"))
{
System.out.println("Looks like you didn't enter a correct choice.");
System.out.println("Please type in a command: new, old or end");
userChoice = input.next();
}
return userChoice;
}
public static String PlayerIDMethod()
{
String playerID = "";
Boolean loop = true;
while(loop)
{
try
{
System.out.println("Please input Player ID: ");
playerID = input.next();
int playerIDDigit = Integer.parseInt(playerID);
if (playerID.length()> 5){
playerID.substring(0,5);
}
if (playerID.length()< 5){
StringBuilder paddedName = new StringBuilder(playerID);
while(paddedName.length()<5){
paddedName.append(" ");
}
playerID = paddedName.toString();
}
while(Pattern.matches("[a-zA-Z]+", playerID)|| playerID.startsWith("-")|| playerIDDigit>20 || playerIDDigit<0)
{
System.out.println("Player ID cannot have characters, negatives, and must be within 1-20!");
System.out.println("Please input Player ID: ");
playerID = input.next();
}
loop = false;
}
catch(Exception e)
{
System.out.println("No way Hosay! Only Integers!");
}
}
return playerID;
}
public static String PlayerNameMethod ()
{
String playerName = "";
try{
System.out.println("Enter Player's Name: ");
playerName = input.next();
while(Pattern.matches("^\\d+", playerName))
{
System.out.println("No cool names include numbers! Try again.");
System.out.println("Enter Player's Name: ");
playerName = input.next();
}
if (playerName.length()> 26){
playerName.substring(0,26);
}
if (playerName.length()< 26){
StringBuilder paddedName = new StringBuilder(playerName);
while(paddedName.length()<26){
paddedName.append(" ");
}
playerName = paddedName.toString();
}
}
catch(Exception e){
System.out.println("ERROR PLEASE TRY AGAIN");
}
return playerName;
}
public static String PlayerTeamNameMethod ()
{
String playerTeamName = "";
try
{
System.out.println("Please enter Team name: ");
playerTeamName = input.next();
if (playerTeamName.length()> 26){
playerTeamName.substring(0,26);
System.out.print("The Player Name is" + playerTeamName);
}
if (playerTeamName.length()< 26){
StringBuilder paddedName = new StringBuilder(playerTeamName);
while(paddedName.length()<26){
paddedName.append(" ");
}
playerTeamName = paddedName.toString();
}
}
catch(Exception e)
{
System.out.println("ERROR PLEASE TRY AGAIN");
}
return playerTeamName;
}
public static String PlayerSkillLevelMethod ()
{
String playerSkillLevel = "";
Boolean loop = true;
while(loop)
{
try
{
System.out.println("Please enter player skill level between 0 and 99: ");
playerSkillLevel = input.next();
while(Pattern.matches("[a-zA-Z]+", playerSkillLevel))
{
System.out.println("Player skill level must be an integer!");
System.out.println("Please enter player skill level between 0 and 99: ");
playerSkillLevel = input.next();
}
loop = false;
}
catch(Exception e){
System.out.println("ERROR PLEASE TRY AGAIN ");
}
}
return playerSkillLevel;
}
public static String TodaysDateMethod (){
String todaysDate = "";
try{
System.out.println("Please enter todays date: ");
todaysDate = input.next();
if (todaysDate.length()> 9)
{
todaysDate = todaysDate.substring(1,9);
}
if (todaysDate.length()< 9)
{
StringBuilder paddedName = new StringBuilder(todaysDate);
while(paddedName.length()<26){
paddedName = paddedName.append(" ");
}
todaysDate = paddedName.toString();
}
}
catch(Exception e){
System.out.println("ERROR ");
}
return todaysDate;
}
//CONVERT TO STRING
public static String RecordtoFile (RandomAccessFile store){
return null;
}
//WRITE INTO FILE AT RECORD LOCATION INDICATED BY ID
public static String WriteToFile (RandomAccessFile store){
return null;
}
}
The way I see it resolved is creating a Person class with a constructor that would take an int id and a String name as parameters.
This class would have a private void recordToFile method and you would only record one person per line in the id space name format.
Aditionally, in the FirstTr class you would have a private Person retrieveFromFile(int id) that would verify every line in the file and would return the Person with the given id or null if no person was found. That method could get a String name too in the parameters but it's really your call.
The way using a String[ ] could be useful too but you should decide.
I found what was causing the problem. When parsing, three of the five values that make up the string had been set to length 26, so this already created a string of length 78. The desired size is 71, and when the other two values are added, it can reach to 80 or 81. Changing what the strings are parsed or added to changed the length of the super string and no longer run into any issues. Thanks for the help