I'm sorry if this is a silly question but I am fairly new to coding and so for my assignment I was given this code:
package webservice;
import webservice.Weather;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the zip code : ");
java.lang.String zipCode = scan.nextLine();
try{
webservice.Weather service = new webservice.Weather();
webservice.WeatherSoap port = service.getWeatherSoap();
webservice.WeatherReturn result = port.getCityWeatherByZIP(zipCode);
System.out.print(result.getCity()+ " ");
System.out.println (result.getState());
System.out.println("Zip code " + zipCode);
System.out.println ("Current Temperature is " + result.getTemperature());
}
catch (Exception ex){
System.out.println("Error");
}
}//end main
}//end class
The code runs perfectly fine but I have to have it loop until i enter "0" for the zip code.
I'm fairly new to coding and I tried to review my previous works to try to incorporate a loop but I was never successful. Which loop would be the most efficient to have the code loop until the user enters "0" as the zip code?
Simply try this:
Scanner scan = new Scanner (System.in);
int zipCode;
while(scan.nextInt()!=0){
System.out.print ("Enter the zip code : ");
zipCode = scan.nextInt();
}
Use a while loop to verify your condition and use .nextInt() to get an int from the scanner.
Also there's a typo:
If you use :
import webservice.Weather;
You don't have to do this:
webservice.Weather service = new webservice.Weather();
It's simply:
Weather service = new Weather();
Take a look at Using Package Members for further information.
How about while loop?
String zipCode;
while(!"0".equals(zipCode = scan.nextLine())) {
//to do rest
}
Sample code:
import java.util.Scanner;
class Ideone
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String zipCode;
while(!"0".equals(zipCode = sc.nextLine())) {
System.out.printf("zip code: %s\n", zipCode);
}
System.out.printf("last zip code: %s\n", zipCode);
}
}
I/P:
123
456
789
0
O/P:
zip code: 123
zip code: 456
zip code: 789
last zip code: 0
while loop would do your trick.
This is because while loop checks the condition first and then iterates over if the condition is found to be true. And in your case we need to check if the user has entered the correct value or not. If he has entered 0 we do not need to proceed further.
Related
For this code, I'm trying to get the user to input a pattern of numbers like "####-##-###" including the dashes. I have this code but it's returning an error.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Scanner;
public class StudentNumber {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter your student number: ");
int su;
Pattern p = Pattern.compile("[\\d]{4,}+[-?]{1,1}+[\\d]{2,}+[-?]{1,1}+[\\d]{3,}");
su = s.nextInt();
String input = String.valueOf(su);
Matcher m = p.matcher(input);
if (m.matches()){
System.out.println("You have successfully logged in.\nWelcome to your new dashboard!");
} else {
System.out.println("Invalid format. Try Again.");
}
}
}
the error is
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:943)
at java.base/java.util.Scanner.next(Scanner.java:1598)
at java.base/java.util.Scanner.nextInt(Scanner.java:2263)
at java.base/java.util.Scanner.nextInt(Scanner.java:2217)
at com.mycompany.studentnumber.StudentNumber.main(StudentNumber.java:21)
The error you're getting is because you have the dashes in the string and you're calling nextInt. You need to read the input as a string (with e.g. nextLine) then apply the regex to that and convert the parts to integers as appropriate.
su = s.nextInt();
Since the input you expect contains dashes, i.e. -, it isn't an int, it's a string, so use method nextLine (rather than method nextInt).
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StudentNumber {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter your student number: ");
Pattern p = Pattern.compile("[\\d]{4,}+[-?]{1,1}+[\\d]{2,}+[-?]{1,1}+[\\d]{3,}");
String input = s.nextLine();
Matcher m = p.matcher(input);
if (m.matches()){
System.out.println("You have successfully logged in.\nWelcome to your new dashboard!");
} else{
System.out.println("Invalid format. Try Again.");
}
}
}
Here is output from a sample run:
Enter your student number: 123-456-789
Invalid format. Try Again.
Here is another sample run:
Enter your student number: 1234-56-789
You have successfully logged in.
Welcome to your new dashboard!
Since,you are using - in int input, input cant't take it as integer, instead of it use next() method of Scanner() class.
String input = in.next()
Also, if you are using
Pattern p = Pattern.compile("[\\d]{4,}+[-?]{1,1}+[\\d]{2,}+[-?]{1,1}+[\\d]{3,}");
It also validates 111111-11-11111. To avoid this use instead
Pattern p = Pattern.compile("[\\d]{4}+[-?]{1}+[\\d]{2}+[-?]{1}+[\\d]{3}");
I'm doing a small project and I have everything done, just one small error. the error shows "symbol not found" and shows the red squiggly line under my scan.
package pkgif.elsestatements.java;
import java.util.Scanner;
public class IfElseStatementsJava {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String your_name;
System.out.print("What is your name?");
your_name = user_input.next();
System.out.println("Hi " + your_name);
String user_input2;
System.out.print(".");
user_input2 = user_input.next();
System.out.println("Do you like Gospel Music Paul?"); //Asks question
String input = scan.nextLine(); //Waits for input
if (input.equalsIgnoreCase("Yes")) { //If the input is Yes)
System.out.println("Here are some songs; Amazing Grace, I'll Fly Away, A Little Talk With Jesus ");
}
else { //If the input is anything else
System.out.println("Ok! Have a nice day!");
}
}
this line is the one giving me trouble ---- String input = scan.nextLine(); //Waits for input
I was feeling really great about finish this with no errors beforehand, then this. Any help is appreciated.
According to the code above. You've defined Scanner user_input = new Scanner(System.in); i.e. user_input as the oject ref.
So, changing String input = scan.nextLine(); to String input = user_input.nextLine(); should do.
https://courses.cs.washington.edu/courses/cse142/15sp/homework/6/spec.pdf
EDIT* Input Files are here:(sorry i'm new to stack overflow, hopefully this works)
I've also tried console.next() but it gives different errors than console.nextLine() in the rePlaceholder method. **
tarzan.txt - https://pastebin.com/XDxnXYsM
output for tarzan should look like this: https://courses.cs.washington.edu/courses/cse142/17au/homework/madlibs/expected_output_1.txt
simple.txt https://pastebin.com/Djc2R0Vz
clothes.txt https://pastebin.com/SQB8Q7Y8
this code should print to an output file you name.
Hello, I have a question about scanners because I don't understand why the code
is skipping the user input on the first iteration but works fine on the rest.
I'm writing a code to create a madlib program and the link will provide the explanation to the program but pretty much you have these placeholders in a text file and when you see one, you prompt for user input to replace it with your own words. However, my program always go through TWO placeholders first and only ask the user input for one, completely skipping the first placeholder. What is wrong with my code??? Also, how do you fix this? Everything else is running perfectly fine, only that the first line is consuming two placeholders so I'm always off by one.
Welcome to the game of Mad Libs.
I will ask you to provide various words
and phrases to fill in a story.
The result will be written to an output file.
(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c
Input file name: tarzan.txt
Output file name: test.txt
Please type an adjective: Please type a plural noun: DD DDDD <--- why is it like this
Please type a noun: DDDD
Please type an adjective: DD
Please type a place:
========================================================================
package MadLibs;
import java.util.*;
import java.io.*;
public class MadLibs2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
intro();
boolean isTrue = true;
while(isTrue) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String choice = console.next();
if (choice.equalsIgnoreCase("c")) {
create(console);
}
else if (choice.equalsIgnoreCase("v")) {
view(console);
}
else if (choice.equalsIgnoreCase("q")) {
System.exit(0);
}
}
}
public static void view(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String viewFile = console.next();
File existingMadLib = new File(viewFile);
Scanner printText = new Scanner(existingMadLib);
while(printText.hasNextLine()) {
System.out.println(printText.nextLine());
}
}
public static void create(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String inputFile = console.next();
File newMadLib = new File(inputFile);
while(!newMadLib.exists()) {
System.out.print("File not found. Try again: ");
inputFile = console.next();
newMadLib = new File(inputFile);
}
System.out.print("Output file name: ");
String outputFile = console.next();
System.out.println();
PrintStream output = new PrintStream(new File(outputFile));
Scanner input = new Scanner(newMadLib);
while(input.hasNextLine()) {
String line = input.nextLine();
outputLines(line, output, console);
}
}
public static void outputLines(String line, PrintStream output, Scanner console) throws FileNotFoundException{
String s = "";
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()){
s = lineScan.next();
if(s.startsWith("<") || s.endsWith(">")) {
s = rePlaceholder(console, lineScan, s);
}
output.print(s + " ");
}
output.println();
}
public static String rePlaceholder(Scanner console, Scanner input, String token) {
String placeholder = token;
placeholder = placeholder.replace("<", "").replace(">", "").replace("-", " ");
if (placeholder.startsWith("a") || placeholder.startsWith("e") || placeholder.startsWith("i")
|| placeholder.startsWith("o") || placeholder.startsWith("u")) {
System.out.print("Please type an " + placeholder + ": ");
} else {
System.out.print("Please type a " + placeholder + ": ");
}
String change = console.nextLine();
return change;
}
public static void intro() {
System.out.println("Welcome to the game of Mad Libs.");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
}
}
in your rePlaceholder, change this line:
String change = console.nextLine();
Into this
String change = console.next();
Your problem is that nextLine doesn't wait for your output, just reads what it has in the console, waiting for a new line.
This is from the documentation to be a bit more precise on the explanation:
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
UPDATE
After reading the comment, the previous solution will not work for multiple words.
After reading the output file, you are using next().
You need to make another call to nextLine() to clean the buffer of any newlines.
System.out.print("Output file name: ");
String outputFile = console.next();
console.nextLine(); // dummy call
System.out.println();
To be fair, I'm not getting these exceptions but merely trying to find a away to cover these exceptions. The exceptions are NosuchElementException and NumberFormatException.
Note: This programs works perfectly because the txt file is fine. However, introduce anything that is not a number and it will fail.
Here is the main class where the problem could occur:
BankReader.java
package bankreader;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class BankReader
{
public static void main(String[] args)
{
BankReader reader = new BankReader();
Scanner scan = new Scanner(System.in);
String fileName = "";
boolean finished = false;
while(!finished)
{
try
{
System.out.print("Enter the name of the file: ");
fileName = scan.nextLine();
scan = reader.checkFile(fileName, scan);
reader.readFile(scan);
finished = true;
}
catch(IOException ex)
{
System.out.print("\nThis file does not exist or had");
System.out.println(" characters that were not numbers. Please enter a different file.\n");
}
}
scan.close();
}
public Scanner checkFile(String fileName, Scanner scan) throws IOException
{
File file = new File(fileName);
scan = new Scanner(file);
return scan;
}
public void readFile(Scanner scan)
{
String accountNumber = "";
double accountBalance = -1;
Bank bank = new Bank();
while(scan.hasNext())
{
accountNumber = scan.next();
accountBalance = Double.parseDouble(scan.next());
BankAccount bankAccount = new BankAccount(accountNumber, accountBalance);
bank.addAccount(bankAccount);
}
if (bank.numberOfAccounts() > 0)
{
BankAccount maxBalance = bank.getHighestBalance();
System.out.println(maxBalance.getAccountNumber() + ": " + "$" + maxBalance.getBalance());
}
else
System.out.println("\nThe file had no accounts to compare.");
}
}
Here is the txt file I'm working with:
346583155444415 10000.50
379611594300656 5000.37
378237817391487 7500.15
378188243444731 2500.89
374722872163487 25000.10
374479622218034 15000.59
342947150643707 100000.77
So even though this is my own txt file, what if I was accessing a text file that a character that wasn't a number or had an account number but no balance and vice versa. I would like to know how I can deal with these exceptions.
What I've tried:
I've tried to do scan.nextLine() to move away from the exception but it just introduces another exception.
I've also tried to use a method that uses regex to check if the string is a number. The problem is I'm using a variable that is not a string and I would rather not create more checks.
It seems to me that no more what I do, I can't recover my scanner after an exception has occurred.
before parsing you can test if it is a double with scan.hasNextDouble and parse or read the number only then else you set default value and move next by reading the incorrect value and dont do anything with it
Ok so i have inputted a number of records to a text file and i can both write to and read from this file, but i am now attempting to search through this textfile and have encountered a problem.
package assignmentnew;
// Import io so we can use file objects
import java.io.*;
import java.util.Scanner;
public class SearchProp {
public void Search() throws FileNotFoundException {
try {
String details, input, id, line;
int count;
Scanner user = new Scanner(System.in);
System.out.println();
System.out.println();
System.out.println("Please enter your housenumber: ");
input = user.next();
Scanner housenumber = new Scanner(new File("writeto.txt"));
while (housenumber.hasNext())
{
id = housenumber.next();
line = housenumber.nextLine();
if (input.equals(id))
{
System.out.println("House number is: " + id + "and" + line);
break;
}
if(!housenumber.hasNext()) {
System.out.println("no house with this number");
}
}
}
catch(IOException e)
{
System.out.print("File failure");
}
}
}
No matter what value i enter i am told that the house number is not present in the file, but obviously it is, any ideas?
Addendum:
File Structure in textfile.
27,Abbey View,Hexham,NE46 1EQ,4,150000,Terraced
34,Peth Head,Hexham,NE46 1DB,3,146000,Semi Detached
10,Downing Street,London,sw19,9,1000000,Terraced
The default delimiter for a scanner is white-space, and not ,.
You have to use housenumber.useDelimiter(","); and the code will work.
EDIT:
Set it before the while.
And that is what I get for example for 27.
Please enter your housenumber:
27
House number is: 27 and ,Abbey View,Hexham,NE46 1EQ,4,150000,Terraced