Scanning Basics Java - java

So the loop works but I have to press enter twice for it to print out the next input, I know it's with my loop and I know it's because the new input is set after the method scanz but I can't put it before/ eliminate it outside the loop because then the creation of the object Scanning doesn't work. Help is appreciated!
public class NumberScanned {
public static void main(String[] args) {
System.out.println("Please enter '.' when you want to terminate");
Scanner keyboard = new Scanner(System.in);
String scannedString=keyboard.nextLine();
Scanning scanz= new Scanning(scannedString);
do
{
System.out.println("Numbers: "+scannedString);
scanz.set(scannedString);
scanz.printState();
scannedString=keyboard.nextLine();
}
while(!keyboard.nextLine().equals("."));
keyboard.close();
}
}

Change your loop to the following pattern:
String scannedString = keyboard.nextLine();
do {
System.out.println("Numbers: "+scannedString);
scanz.set(scannedString);
scanz.printState();
} while (!(scannedString = keyboard.nextLine()).equals("."));
This way condition check is done together with reading a new line. There is even more readable approach available:
String scannedString = null;
while (!(scannedString = keyboard.nextLine()).equals(".")) {
System.out.println("Numbers: "+scannedString);
scanz.set(scannedString);
scanz.printState();
}

Related

Arraylist User input

I would greatly appreciate some help with my java code. I am using ArrayLists to store the users favorite type of vehicles. So they will input vehicles until they type "Exit" to get out of the loop. It will then print the array list. Right now, it is only reading every other input. Depending on how many inputs there are, the user might have to type "Exit" twice before it prints the results out. Any help would be greatly appreciated, thank you!
package bacaCCh6Sec8;
import java.util.ArrayList;
import java.util.Scanner;
public class BacaCCh6Sec8 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> vehicles = new ArrayList<>();
boolean done = false;
final String EXIT = "Exit";
System.out.printf("Enter your favorite vehicles.\n");
System.out.printf("Type Exit after you have input all your vehicles.\n");
do {
String input = in.next();
if (!input.equals(EXIT)) {
vehicles.add(in.next());
} else {
done = true;
} // end If
} while (!done); // End Do While
System.out.printf("Your favorite vehicles are %s.\n" , vehicles);
} // End Main
} // End Class
the user might have to type "Exit" twice before it prints the results
out
the issue is that you're calling next() method twice hence the user must enter a value twice. the solution is to simply use the value you've got from the first next() method rather than discarding it.
String input = in.next();
if (!input.equals(EXIT)) {
vehicles.add(input); // <--- we're using the input variable
} else {
done = true;
} // end If
Each call of .next() actually reads the input. So if you call .next() twice, it'll read two lines. To rectify change vehicles.add(in.next()); to vehicles.add(input);
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> vehicles = new ArrayList<>();
boolean done = false;
final String EXIT = "Exit";
System.out.printf("Enter your favorite vehicles.\n");
System.out.printf("Type Exit after you have input all your vehicles.\n");
do {
String word = in.next();
if(word.equalsIgnoreCase("exit")) break;
vehicles.add(word);
} while (!done); // End Do While
System.out.printf("Your favorite vehicles are %s.\n" , vehicles);
}
}
Well not my best code but it helped
Enter your favorite vehicles.
Type Exit after you have input all your vehicles.
hola
mundo
exit
Your favorite vehicles are [hola, mundo].

Jumping to lines in Java

I have just now started learning Java and one of the differences I noticed from C++ and VB is that Java has no goto statements, which I tend to use a lot while programming.
Is there any way I could jump between lines using another statement? I tried to use break and continue but to no avail (I might be doing something wrong).
Here is the code with goto statements and how I want it to operate:
public class HelloWorld {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
jump1:
System.out.print("What do you want to calculate? ");
String method = sc.nextLine();
if (method.equals("tax")) tax();
else {
System.out.print("Please input a valid method. \n\n");
goto jump1;
}
}
What is a good replacement for the goto commands?
A while loop in this instance.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html
For this (very specific) instance you could put
System.out.print("What do you want to calculate? ");
String method = sc.nextLine();
while (!method.equals("tax"))
{
System.out.print("Please input a valid method. \n\n");
method = sc.nextLine();
}
tax();
Obviously this only works if your only expected correct input is "tax", but it's a structure to build on.
You would want to put your if-statement in a while-loop by using the hasNextLine() function, which will loop until theres no more lines left to iterate over:
while(sc.hasNextLine()) {
// Your code..
}
For more info regarding the function check Scanner::hasNextLine documentation.
You should avoid "goto" statements in all languages, according to the rules of "structured programming", instead using if-then-else or do or while or for loops to control program flow.
Java DOES have a sort of "goto" statement that you COULD use to only slightly modify your code, but consider the while loop below and the break statement, which jumps out of the loop.
public static void main(String[] args) {
String method = "";
while(! method.equals("tax")){
System.out.print("What do you want to calculate? ");
method = sc.nextLine();
if(method.equals("tax"))
break;
System.out.print("Please input a valid method. \n\n");
}
tax();
}
The break statement enables your "Please ... valid" statement to display. You could also use this:
public static void main(String[] args) {
String method = "";
while(! method.equals("tax")){
System.out.print("What do you want to calculate? ");
method = sc.nextLine();
}
tax();
}
I also kind of like this:
public static void main(String[] args) {
String method = "";
while(1==1){
System.out.print("What do you want to calculate? ");
method = sc.nextLine();
if(method.equals("tax")
break;
System.out.print("Please input a valid method. \n\n");
}
tax();
}
You might go to the Java tutorials; they're good.
In this case you can use a do-while-loop, which will do the statement first and will only repeat if the statement is true:
public class HelloWorld {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
boolean right = true;
do {
if(right)
System.out.print("What do you want to calculate? ");
else
System.out.print("Please input a valid method. \n\n");
String method = sc.nextLine();
boolean right = false;
} while (!method.equals("tax"));
tax();
}
}

how to accept multiple lines of input just once and making sure the user is not asked for input once again

I have tried to solve the 3n+1 problem, and got very close. I think what happens here is the answer should accept multiple lines of input at once should not ask the user to give input again. I have tried the nextLine() method in a loop conditioned by the hasNextLong(), but the problem is whenever it does not find any more long types, it asks the user to give another input instead of breaking the loop. Is there any way to make sure it takes input only once, regardless of how many lines the user inputs?
The loop breaks if I enter a String. What I want to do is break when only the first input has no more long variables to deal with.
import java.util.Scanner;
import java.io.*;
public class te{
public static void main(String[] args){
Scanner key=new Scanner (new BufferedInputStream(System.in));
String s="";
while(key.hasNextInt()){
System.out.println("Entered loop");
s=s+""+key.nextLong();
}
System.out.println(s);
}
}
Not 100% sure what your trying to accomplish, but to answer this problem:
"..whenever it does not find any more long types, it asks the user to give another input instead of breaking the loop."
I just used a try/catch block. If the input is not a number, it breaks the loop. You can keep inputting numbers and hitting enter, and if an input is not a number, the loop will break; and it will print out the concatenated numbers.
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String s = "";
System.out.println("Enter Numbers: ");
while (true) {
try {
s += String.valueOf(scanner.nextInt()); // if input is not an int
} catch (Exception ex) { // it will throw exception
break;
}
}
System.out.println(s);
}
}
Edit: Scanning a line
Scanner input = Scanner(System.in);
System.out.printline("Enter some numbers: ");
String line = scanner.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNextLong()){
long num = lineScanner.nextLong();
// do something with num
}

Correctly scanning a blank input with the Scanner object

I'm working on creating a basic guitar inventory and I'm doing testing with scanner, I was trying to scan a blank entry and when there is a blank entry it should print "ANY" and it does, i'm using scan.useDelimiter("\z"); and now when I enter a correct entry like "fender" it should print "FENDER" but it just prints "ANY" as if the entry was incorrect.. someone know what I can do to solve that problem? Here is an sscce:
import java.util.Scanner;
public class SSCCE {
public static void main(String[] args)
{
System.out.println("Enter a builder name: ");
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\z"); // count a blank entry (end of input)
String entry_1 = scan.next();
if (entry_1.equalsIgnoreCase("FENDER")
|| entry_1.equalsIgnoreCase("MARTIN")
|| entry_1.equalsIgnoreCase("GIBSON")
|| entry_1.equalsIgnoreCase("COLLINGS")
|| entry_1.equalsIgnoreCase("OLSON")
|| entry_1.equalsIgnoreCase("RYAN")
|| entry_1.equalsIgnoreCase("PRS"))
{
entry_1 = entry_1.toUpperCase();
System.out.println(entry_1);
}
else
{
entry_1 = "ANY";
System.out.println(entry_1);
}
}
}
By default, the scanner removes the delimiter from the tokens it return. When the delimiter was a line break (the default), when you do fender, entry_1 was assigned "fender". After you changed the delimiter, the line break caused by the enter is no longer removed, so you get "fender\n" in entry_1, causing your if condition to fail.
To fix, just do String entry_1 = scan.next().trim(); instead which removes the trailing linebreak.
You can try printing the scanned value to see why it is not going into the if statement.
import java.util.Scanner;
public class SSCCE {
public static void main(String[] args)
{
System.out.println("Enter a builder name: ");
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\z"); // count a blank entry (end of input)
String entry_1 = scan.next();
System.out.println("Input = [" + entry_1 + "]");
// rest of the code...
}
I think this is due to your use of \\z. Look at this regex tutorial for a more detailed story. For solving your problem, suffice it to say that changing it to \\Z should do the trick. The following code is working for me:
public static final Set<String> names = Sets.newHashSet("martin", "gibson", ...);
public static void main(String[] args) {
System.out.println("Enter a builder name: ");
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\Z"); // count a blank entry (end of input)
String entry = scan.next();
entry = "any" if (!names.contains(entry.toLowerCase());
System.out.println(entry.toUpperCase());
}
Note: I assumed you are scanning one name at a time. If not, then just use line break.

Scanner looping headache

I have a homework assignment which requires input from the user and stores it in various data structures (arrays of linked-lists, stacks, etc.). However, I've been writing the main class of my previous homework assignments and this one in a very similar fashion. I have a very tiny main method. All the main method does is instantiate a new object which I don't want to be destroyed and then loop through the program forever until the user chooses otherwise. I then have a menu() method which prints a list of selections and reads the user's selection. And then from there, I pass that selection to another method which interprets the selection and performs accordingly.
The problem I have been having in the past assignments and now I've never really gotten a good answer for. The problem seems to lie with my menu() method and more specifically, the Scanner object. There always seems to be some junk left in the stream after I call the nextLine() method on a scanner object. So the next time the menu() method is called, it reads in that junk and loops though the rest of the program with that junk until menu() is called a third time. In the past, I would remedy this by calling the next() method right after I received my input and ignoring it. However, I seem to be having issues with that now as well.
In this program in particular, I have a method which request's a user enter a city name. Now, city names can be more than one word (Palm City, West Palm Beach, Satellite Beach, New York, etc.). Now, when the scanner reads in one of those multi-word cities, it does the same thing as before, reads in some junk the next time the menu() method is called and goes though the whole program with it until menu() is called again. In this case, it prints an string "Invalid Selection" and then prints the menu again. I can't for the life of me figure out what's going on. any help would be appreciated.
import java.util.Scanner;
public class CSAir
{
public static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
CityList flightLog = new CityList();
boolean loop = true;
while(loop)
{
loop = actions(menu(),flightLog);
}
}
private static String menu()
{
System.out.print("Please Make a Selection\n" +
"I) Insert a city\n" +
"A)Add a flight path (One Way)\n" +
"R) Request a flight\n" +
"L) Load from a text file\n" +
"Q) Quit\n" +
"\nSelection: ");
String in = input.next();
//input.next();
System.out.println();
return in;
}
private static boolean actions(String selection, CityList flightLog)
{
if(selection.equalsIgnoreCase("I"))
{
insert(flightLog);
return true;
}
else if(selection.equalsIgnoreCase("A"))
{
add(flightLog);
return true;
}
else if(selection.equalsIgnoreCase("R"))
{
request(flightLog);
return true;
}
else if(selection.equalsIgnoreCase("L"))
{
return true;
}
else if(selection.equalsIgnoreCase("Q")) return false;
else
{
System.out.println("Invalid Selection!\n");
return true;
}
}
private static void request(CityList flightLog)
{
System.out.print("Origin: ");
String origin = input.nextLine();
System.out.print("\nDestination: ");
try
{
flightLog.isPath(origin, input.next());
}
catch (AllDestinationsVisitedException e)
{
e.getMessage();
}
}
private static void add(CityList flightLog)
{
System.out.print("Origin: ");
String origin = input.nextLine();
System.out.print("\nDestination: ");
flightLog.addPath(origin, input.next());
}
private static void insert(CityList flightLog)
{
System.out.print("Enter a City: ");
try
{
flightLog.addCity(input.next());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println();
}
}
Default Deliminator for scanner is white space. So when you enter New York since it has white space now scanner treats it as two tokens if you call next().
A better option would be to use nextLine() method for reading such values.

Categories