Why does my scanner ask for input every three lines? - java

Does anyone know why my scanner is asking for input every three lines, rather than every one line? If you run it, you will see that it asks the question first, but then doesn't for two more lines, then it asks the question again. How do I get it to ask a question every line, let alone store it in a linked list.
import java.util.Scanner;
public class StackCalc {
public static StackLL stackll = new StackLL();
public static void create() {
String hold = new String();
Scanner scanner = new Scanner(System.in);
boolean running = true;
while (true) {
System.out.print("Enter number, math operation(+,-,*, or /), or Q to quit: ");
hold = scanner.next();
if (scanner.next().equals("Q") || scanner.next().equals("q")) {
System.out.println(hold);
break;
}
}
}
public static boolean checkInt(String s, int it){
Scanner scan = new Scanner(s.trim());
if(!scan.hasNextInt(it))
return false;
scan.nextInt(it);
return !scan.hasNext();
}
public static void main(String args[]) {
create();
}
}
Any input would be awesome.

It is because you are using the method Scanner.next() three times:
hold = scanner.next()
scanner.next().equals("Q")
and scanner.next().equals("q")
Instead, only call it once by changing:
scanner.next().equals("Q") to hold.equals("Q")
and
scanner.next().equals(q") to hold.equals("Q")

Related

how to use the same input for two different scanners in two methods with formatted input

I realized the issue was due to me creating a new scanner/reader object(the new scanner has a blank input), the issue still persists - how do I use the same input stream for both methods (or) how do I use the same scanner reader for both methods
Original question: how to pass on the main method input stream to called method
So I'm taking in formatted input which is like this from geek for geeks (this is important to my error)
1
4
1 2 3 4
And I am using scanner class to read the numbers into variables. This is my code
// code to print reverse of input string after reading the length of the string and no. of testcases
class Main {
public static void main (String[] args) {
int i,t,n;
String x,y;
Scanner scan = new Scanner(System.in);
try {
t=scan.nextInt();
scan.nextLine();
REV rv=new REV();
for (i=0;i<t;i++){
rv.reverse();
}
}catch (Exception e){
return;
}
}
}
class REV{
public void reverse(){
int i,a[],n;
Scanner scan = new Scanner(System.in);
try {
n=scan.nextInt();
scan.nextLine()
a= new int[n];
for (i=n-1;i>=0;i--){
a[i]=scan.nextInt();
}
System.out.println(a[i]);
}catch(Exception E){
return;
}
}
}
I get no output for this (java.util.NoSuchElementException if I don't use try and catch)
I am able to read the variables in the main method but my input stream becomes empty for the new method
I verified this by using nextLine() both in the main() method and reverse() method as shown
public static void main (String[] args) {
int t,n;
String x,y,z;
t=scan.nextInt();
x=scan.nextLine();
n=scan.nextInt(); //to eat up the n input
y=scan.nextLine();
z=scan.nextLine();
System.out.println(x+y);
....
}
output-
141 2 3 4
and
public void reverse(int n){
....
String k,j;
k = scan.nextLine(); //replacing n- to check what n=scanInt() reads
j= scan.nextLine();
System.out.println(x +y);
....
}
Output is blank again (java.util.NoSuchElementException)
I think this means the input stream is empty for the reverse() method.
So how do I pass on the main() input to reverse()
Note: 1. if I don't use try{} and catch{} it gives me java.util.NoSuchElementException
I'm aware I have made the code needlessly a little complicated, this is due to me trying to solve this problem
I got the try{} and catch{} solution from here, but it doesn't solve my empty input problem
4.This made me understand the empty input exception
Create a method instead of making an Object of a class and then calling the method. (Unless you want it that way).
Create a single static Scanner and use it everywhere.
private static Scanner scanner = new Scanner(System.in)
To print an array use System.out.println(Arrays.toString(a));.
Reductant use of scanner.nextLine() after Scanner.nextInt.
import java.util.Arrays;
import java.util.Scanner;
class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int i, t, n;
String x, y;
t = scanner.nextInt();
for (i = 0; i < t; i++) {
reverse();
}
}
private static void reverse() {
int i;
int[] a;
int n;
n = scanner.nextInt();
a = new int[n];
for (i = n - 1; i >= 0; i--) {
a[i] = scanner.nextInt();
}
System.out.println(Arrays.toString(a));
}
}
Is this your desired output?

ArrayList Scanner input help Java

I am trying to write a code where you sort a given list of numbers, and I'm trying to do so using ArrayList. I am using a while loop to allow for repeated inputs. This is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class sortinggg {
public static Scanner keyboard = new Scanner(System.in);
public static ArrayList<Integer> number = new ArrayList<Integer>();
public static void main (String [] args) {
int count= 0;
System.out.println("Enter your numbers.");
while (keyboard.hasNextInt()); {
number.add(keyboard.nextInt());
}
The integer count is irrelevant right now, as I only use it when I am sorting the list.
The problem is that after I input my numbers, even if I type in a string (for example), the program doesn't move on to the next line of code. Am i missing anything here?
P.S. I tired looking up questions that have been asked previously on this topic, but none of the solutions suggested worked for me.Thank you for your help in advance!
Try this:
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
ArrayList<Integer> number = new ArrayList<Integer>();
System.out.println("Enter your numbers:");
while (keyboard.hasNextInt()) {
number.add(keyboard.nextInt());
}
}
}
Modifications:
In while (keyboard.hasNextInt()); remove semicolon(;) at the end.
Here while loop will keep adding values to the arraylist until you provide int values.
In the first place the ; just after the while is wrong. It does not let you to execute the body. Then how are you going to skip the loop. You may ask the end user to enter some special value and use it to break the loop. The corrected version is given below.
public static void main(String[] args) {
int count = 0;
System.out.println("Enter your numbers or -1 to skip.");
while (keyboard.hasNextInt()) {
int num = keyboard.nextInt();
if (num == -1) {
break;
}
number.add(num);
}
System.out.println(number);
}

How do you add objects into an array from a main method? Also, how do you make a menu in the main method?

Ok so I have to make a driver for one of my assignments and what I'm testing is my ArrayObject class. The class has a "add" method:
private int actualSize; // assume actualSize == 0 for this code
public void add(Object obj)
{
if(actualSize>=arr.length)
return;
arr[actualSize]=obj;
actualSize++;
}
So this adds an object that the user wants when they create the array in the ArrayObject class. Now, I've made an ArrayObjectDriver class and in this class, I need to create a menu where it loops back.
So far:
public class ArrayObjectDriver{
ArrayObject array = new ArrayObject();
public static void main(String[] args)
{
int option = selectionMenu();
Scanner scanner = new Scanner(System.in);
ArrayObjectDriver drive = new ArrayObjectDriver();
drive.methods(option);
}
private static int selectionMenu()
{
int optionNumber = 1;
System.out.println("Menu: ");
System.out.println("1. Add object to the end of the list");
return optionNumber;
}
private void methods(int option)
{
if(option==1)
{
System.out.println("Enter your object: ");
String str = scanner.nextLine(); // putting string for now
array.add(str);
}
}
}
That's a snippet of the code of I were to only use the first option. What I'm having trouble with adding an object to the array. I don't know how you would take user input to add an object to the array in a main method. Another problem that occurred was the program itself. I left it as a string to test string input and everytime I would run the program, it would always stop running after it asked me to "Enter my object: ". How do I stop this so it would add a, let's say, string object, to my array? It doesn't add anything to the array.
The next question I have is how you would loop the main method. I tried a recursive approach in the void methods(int option) code and then testing putting the drive.methods(option) code in a while loop but it didn't work. Would I have to call on the selectionMenu() over and over?
EDIT:
I declared a Scanner.
I declared the array.
To get user input from the console you can use the Scanner class:
Scanner user_input = new Scanner( System.in );
It looks like you have a variable scanner, but from the snippet you have posted you have never initialized it. If you want to loop in your main method you could do something like this:
import java.util.Scanner;
public class TestClass {
private static Scanner scanner;
public static void main(String[] args)
{
scanner = new Scanner(System.in);
ArrayObject array = new ArrayObject();
String option = "";
int selection = selectionMenu();
while(selection != 3){
if(selection == 1){
System.out.println("Enter your object");
String input = scanner.next();
array.add(input);
}else if(selection == 2){
for(Object o : array){
System.out.println("Object value: "+o.toString());
}
}
selection = selectionMenu();
}
scanner.close();
}
public static int selectionMenu(){
System.out.println("Menu:");
System.out.println("\t1. Add object");
System.out.println("\t2. Print objects");
System.out.println("\t3. Quit:");
int option =scanner.nextInt();
return option;
}
}
In your code, create an ArrayObject class object in main method and pass the reference of the object in your methods(int option, ArrayObject arrays) and then you can easily add an object to arrays.
And, for your next question. Why you want to loop the main method, instead just create a for or while loop in the main method.
Something like this:
while(true)
{
System.out.println("Menu ");
System.out.println("1. Option 1 ");
System.out.println("2. Exit");
System.out.println("Enter your choice ");
int n = scanner.nextInt();
switch(n)
{
case 1:
System.out.println("Enter your object: ");
String str = scanner.nextLine(); // putting string for now
array.add(str);
break;
case 2 :
System.exit(0);
}
}

How to make my code accepts an input

I would just like to ask on how can I make my code to just get the input instead of declaring it? Here's my program. I want to input different atomic numbers and not just "37" like what's in my code. Don't mind my comments, it's in my native language. Thanks!
public class ElectConfi {
public static void main(String s[]) {
int atomicNumber = 37;
String electronConfiguration = getElectronConfiguration(atomicNumber);
System.out.println(electronConfiguration);
}
public static String getElectronConfiguration(int atomicNumber) {
int[] config = new int[20]; //dito nag store ng number of elec. in each of the 20
orbitals.
String[] orbitals = {"1s^", "2s^", "2p^", "3s^", "3p^", "4s^", "3d^", "4p^", "5s^",
"4d^", "5p^", "6s^", "4f^", "5d^", "6p^", "7s^", "5f^", "6d^", "7p^", "8s^"};
//Names of the orbitals
String result="";
for(int i=0;i<20;i++) //dito ung i represents the orbital and tapos ung j
represents ng electrons
{
for(int j=0;(getMax(i)>j)&&(atomicNumber>0);j++,atomicNumber--) //if atomic
number > 0 and ung orbital ay kaya pa magsupport ng more electrons, add
electron to orbital ie increment configuration by 1
{
config[i]+=1;
}
if(config[i]!=0) //d2 nagche-check to prevent it printing empty
orbitals
result+=orbitals[i]+config[i]+" "; //orbital name and configuration
correspond to each other
}
return result;
}
public static int getMax(int x) //returns the number of max. supported electrons by each
orbital. for eg. x=0 ie 1s supports 2 electrons
{
if(x==0||x==1||x==3||x==5||x==8||x==11||x==15||x==19)
return 2;
else if(x==2||x==4||x==7||x==10||x==14||x==18)
return 6;
else if(x==6||x==9||x==13||x==17)
return 10;
else
return 14;
}
}
You can use either a Scanner or BufferedReader and get the user input
Using Scanner
Scanner scanner = new Scanner(System.in);
System.out.println("Please input atomic number");
int atomicNumber = scanner.nextInt();
Using BufferedReader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int atomicNumber = Integer.parseInt(reader.readLine());
public static String getElectronConfiguration(int atomicNumber) {}
This method accepting any int value and will return String result. so you only need to provide different number as input. There is no change required in this method.
How to provide different inputs?
You can use Scanner to do that.
Scanner scanner = new Scanner(System.in);
System.out.println("Please input atomic number");
int atomicNumber = scanner.nextInt();
Now call your method
String electronConfiguration = getElectronConfiguration(atomicNumber);
What are the other ways?
You can define set of values for atomicNumber in your code and you can run those in a loop
You can get input from command line arguments by doing below :
Scanner scanner = new Scanner(System.in);
String inputLine = scanner.nextLine(); //get entire line
//or
int inputInt= scanner.nextInt();//get an integer
Check java.util.Scaner api for more info - http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Hope this helps!
You can get the user input from a command line argument:
public static void main(String s[]) {
if (s.length == 0) {
// Print usage instructions
} else {
int atomicNumber = Integer.parseInt(s[0]);
// rest of program
}
}

ChatBot return bug

I'm working on a Chat Bot project, and I'm almost done, other than the fact that whenever I enter an input, it returns multiple outputs depending on the length of the input X.
Here is the source code:
import java.util.*;
public class ChatBot
{
public static String getResponse(String value)
{
Scanner input = new Scanner (System.in);
String X = longestWord(value);
if (value.contains("you"))
{
return "I'm not important. Let's talk about you instead.";
}
else if (X.length() <= 3)
{
return "Maybe we should move on. Is there anything else you would like to talk about?";
}
else if (X.length() == 4)
{
return "Tell me more about " + X;
}
else if (X.length() == 5)
{
return "Why do you think " + X + " is important?";
}
return "Now we are getting somewhere. How does " + X + " affect you the most?";
}
private static String longestWord(String value){
Scanner input = new Scanner (value);
String longest = new String();
"".equals(longest);
while (input.hasNext())
{
String temp = input.next();
if(temp.length() > longest.length())
{
longest = temp;
}
}
return longest;
}
}
This is for testing the Chat Bot:
import java.util.Scanner;
public class Test {
public static void main (String [ ] args)
{
Scanner input = new Scanner (System.in);
ChatBot e = new ChatBot();
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput;
userInput = input.next();
while (!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse(userInput));
userInput = input.next();
}
}
}
I am also trying to modify the Bot so it counts the number of times it has responded; and also modify it so it randomly returns a random response depending on the length of the input. Any help will be much appreciated. Thank You!
You are using the Scanner.next method which only returns the next word in the string. So if you input a string with multiple words, your bot will respond to each of them.
You can use Scanner.nextLine() to get the entire input string, instead of only 1 word.
To count the number of times your bot has responded, you can create a field in the bot class:
private int responseCount = 0;
Then if you change yout getResponse method from a static method to an instance method, you can update this value from this method:
public String getResponse(String value)
{
String X = longestWord(value); //Your longestWord should also not be static.
this.responseCount++;
if (value.contains("you"))
{
...
Regarding counting the responses, just modify your main method:
import java.util.Scanner;
public class Test {
public static void main (String [ ] args)
{
int numberOfResponses = 1;
Scanner input = new Scanner (System.in);
ChatBot e = new ChatBot();
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput;
userInput = input.next();
while (!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse(userInput));
userInput = input.nextLine();
numberOfResponses++;
}
input.close();
System.out.println(numberOfResponses);
}
}
If I have the time I will edit my post in a few minutes to check your problem regarding the double appearences of a response. You also forgot to close the Scanner.
EDIT: It actually happens because scanner has as a default the delimiter set to be on whitespace. so if you input a text with a whitespace, the while loop runs twice for one user input. Just use the nextLine() command.
Why is this code:
Scanner input = new Scanner (System.in);
In your getResponse method? Its not used at all. Take a closer look at your methods as they are holding some strange code.

Categories