System.out.println() is not getting executed [duplicate] - java

This question already has answers here:
How to get out of while loop in java with Scanner method "hasNext" as condition?
(9 answers)
Closed 2 years ago.
import java.util.Scanner;
public class testFixedCapacityStack {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
FixedCapacityStack<String> s;
s = new FixedCapacityStack<String>(100);
while(sc.hasNext()) {
String item = sc.next();
if(!item.equals("-")) {
s.push(item);
} else if (!s.isEmpty()) {
System.out.print(s.pop() + " ");
}
}
System.out.println(s.size());
}
}
I have no idea why the last line is not getting executed. Someone please point out where I did wrong.
Thank you.

Your code is requesting a new string as input and continuing the loop if it's not empty. This is making your while loop a never-ending loop. That is the reason the last line is not executing. You can insert an if-statement in the loop for an exit string.
import java.util.Scanner;
public class testFixedCapacityStack {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
FixedCapacityStack<String> s;
s = new FixedCapacityStack<String>(100);
while(sc.hasNext()) {
String item = sc.next();
if(item.equals("/")) {
break;
}
if(!item.equals("-")) {
s.push(item);
} else if (!s.isEmpty()) {
System.out.print(s.pop() + " ");
}
}
System.out.println(s.size());
}
}
Now when you enter the value "/" as the input, it will get out of the while loop and the last line will execute.

Related

Tried to call method, it was skipped. //Used the same fromat from a working project. Java eclips

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
String input = "";
Scanner in = new Scanner(System.in);
System.out.println("math");
input= in.nextLine();
math(input);
System.out.println("end");
public static void math (String input)
{
if (input=="a" || input=="A")
{
System.out.println("4.0");
}
else if (input== "A-" || input== "a-")
{
System.out.println("3.7");
}
//etc
}
}
What is being printed out is this:
math
a (I entered "a" as input)
end
My method section is being skipped completely! I know that I am calling my method right cuz I did it for a different project last week and legit just copy and pasted the format over!
Try this snippet of code that I had just written for you below.
Ultimately, you should compare strings using variableName.equals(object).
As a tip, I would also recommend that you indent your code so that it looks more cleaner and to improve readability.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Math Letter Grade! \nPlease enter Letter Grade:");
String input = sc.next();
// This calls the method
// Passing what was entered into the Math Parameter.
Math(input);
System.out.println("Program Terminates.");
}
public static void Math(String input) {
if (input.equals("A") || input.equals("a")) {
System.out.println("Your GPA is 4.0");
} else if (input.equals("A-") || input.equals("a-")) {
System.out.println("Your GPA is 3.7");
} else {
System.out.println("More information to be outputted..." +
" But You did well!");
}
}

how to stop taking user inputs and print out arraylist

I am trying to create a program that takes user inputs stores them into an Arraylist and the prints the Arraylist out after user inputs a certain string. my current problem is that i cant get the user inputs to stop and print out. i think what i have currently have is a strong base, i cant see what is wrong.
import java.util.ArrayList;
import java.util.Scanner;
public class GroceryArraylist {
public static void main(String[] args) {
ArrayList<String> Grocerylist = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.print("Enter an item, enter end to stop ");
while (!input.equals("end")) {
Grocerylist.add(input.next());
if (Grocerylist.equals("end")){
for(String str:Grocerylist)
System.out.println(str);
}
}
}
}
Here is the mistake:
Grocerylist.equals("end")
GroceryList is of type ArrayList and it will never be equal to the string "end". It's like comparing apples with oranges.
You could try this instead:
while (!input.equals("end")) {
String input = input.next();
Grocerylist.add(input);
if ("end".equals(input)){
for(String str:Grocerylist)
System.out.println(str);
}
break;
}
You can use hasNext command to avoid including "end" into the array.
public class GroceryArraylist {
public static void main(String[] args) {
ArrayList<String> Grocerylist = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.print("Enter an item, enter \"end\" to stop ");
while (input.hasNext()) {
Grocerylist.add(input.next());
if(input.hasNext("end")) {
System.out.println(Grocerylist);
break;
}
}
}
}
Or you can use a do-while loop instead of:
public class GroceryArraylist{
public static void main(String[] args) {
ArrayList<String> Grocerylist = new ArrayList<>();
Scanner input = new Scanner(System.in);
System.out.print("Enter an item, enter \"end\" to stop ");
do {Grocerylist.add(input.next());}
while (!input.hasNext("end"));
System.out.println(Grocerylist);
System.exit(0);
}
}

Close Scanner when entering "0"

I am writting a program where the user enters a String input and the program finds the number of words and the number of int numbers. Scanner should close when the user enters "0".
My code
import java.util.Scanner;
public class RunMe
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String input = in.nextLine();
Counter numbers = new Counter();
Counter words = new Counter();
Scanner s = new Scanner(input).useDelimiter("\\s");
while(s.nextInt() != 0)
{
if(s.hasNextInt())
{
numbers.add();
}
else
{
words.add();
}
}
s.close();
in.close();
System.out.println("Number of numbers : " + numbers.value());
System.out.println("Number of words : " + words.value());
}
}
and the class Counter
public class Counter
{
private int value;
public int add()
{
value++;
return value;
}
public int value()
{
return value;
}
}
When I run my program I get the following excepion:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at RunMe.main(RunMe.java:13)
Change the condition of your main loop to check if there is something to read and use a break if the numeral is equals to 0.
Solution
while(s.hasNext())
{
if(s.hasNextInt())
{
if (s.nextInt() == 0) break;
numbers.add();
}
else
{
s.next();
words.add();
}
}
With Scanner the console input must be feed using "enter". To avoid this, some other native library would be required, such as JLine. There are other options in this similar question.

While loop wont stop looping with exception

probably missing something really silly, but my while loop will not stop printing the error message.
Could someone have a quick look and point me in the right direction?
package week5;
import java.util.*;
public class Week5 {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
inputInt();
}
public static int inputInt(){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Enter number:");
int num;
boolean carryOn = true;
while (carryOn = true) {
{
try {
num = myKeyboard.nextInt();
carryOn = false;
}
catch (Exception e) {
System.out.println ("Integers only");
}
}
}
return 0;
}
This line is the problem
while (carryOn = true) {
Instead of using the comparison operator ==, you are using the assignment operator =. So essentially, you're setting carryOn to true every iteration, then automatically running the body of the loop since the condition essentially becomes
while (true) {
Just change that problem line to
while (carryOn == true) {
Apart from the infinite loop and the fact you always return 0; no matter what the user types, the code is far more complex than it needs to be.
// only create one scanner
private static final Scanner myKeyboard = new Scanner(System.in);
public static void main(String[] args) {
int num = inputInt();
// do something with num
}
public static int inputInt() {
System.out.println("Enter number:");
while (true) {
if (myKeyboard.hasNextInt()) {
int num = myKeyboard.nextInt();
myKeyboard.nextLine(); // discard the rest of the line.
return num;
}
System.out.println ("Integers only, please try again");
}
}
In your case:
while(carryOn==true)
or
while(carryOn)
will solve your problem

"Java.Util.NoSuchElementException: No Line Found"

//I am not able to figure out what is wrong? Please help me. I was able to use the //scanner .I am not able to input the values.Java.Util.NoSuchElementException: No Line //Found.
//String arrayValue = null;
int Rows= boardsize, Columns=boardsize;
int[][] sudokuArray = new int[Rows][Columns];
String[] sudokuTempArray;
String delimiter = "\\,";
#SuppressWarnings("resource")
Scanner userInput = new Scanner(System.in);
for(int i=0;i<Rows;i++ ){
System.out.println("Enter the value of array separated by ',' for row" + i);
while(userInput.hasNext())
{
String arrayValue = userInput.next();
sudokuTempArray = arrayValue.split(delimiter);
if(sudokuTempArray.length == Rows)
{
for (int j = 0;j<Columns;j++)
{
sudokuArray[i][j] = Integer.parseInt(sudokuTempArray[j]);
System.out.println(sudokuArray[i][j]);
}
}
}
/*
else
{
System.out.println("Try again!");
}*/
}
If you have used a scanner previously reading from System.in and have closed that scanner, you will have closed the System.in InputStream.
Have you previously closed a scanner reading from System.in?
Yes this is a common error. Look at my answer to this question.
java - Scanner class NoSuchElementFoundException
He essentially closed the input in another method, which you are likely doing as well.
Search for .close in your code base.
See this:
java - Scanner class NoSuchElementFoundException
import java.util.*;
import java.util.StringTokenizer;
class shift
{
Scanner sc=new Scanner(System.in);
void test(int x)
{
String s=sc.nextLine();
StringTokenizer st=new StringTokenizer(s);
String wen="";
{
while(st.hasMoreTokens())
{
String temp=st.nextToken();
for(int i=1;i<=x;i++)
{
wen=wen+temp+" ";
}
}
System.out.print(wen);
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
shift reff=new shift();
if(n<=0)
{
System.out.print("EMPTY");
}
else
{
reff.test(n);
}
}
}
//output : java.util.NoSuchElementException: No line found

Categories