Java scanner.nextInt throws NoSuchElement second time around - java

So I have a loop that runs which takes input from the user via a scanner and System.in. The scanner is just called s. I use s.nextInt to get an int for my switch, where I have a lot of cases, so the user has some choices. Now in one of those cases, I use another scanner, and when I close it and the function terminates (which takes me back to my while loop) I want to take a new int from the user, to choose the next thing they want to do. This time around it throws an NoSuchElementException. I used the "I'm before" and "I'm after" and the userrequest = s.nextInt is where I get the error. Any ideas? My function is way too long to post, but it doesn't really do anything that should interfere, except open a new scanner, but I have other functions which does that, but doesn't break it.
while (on) {
System.out.println("What may I do for you today? ");
System.out.println("I'm before");
int userrequest = s.nextInt();
System.out.println("I'm after");
switch (userrequest) {
case 1:
System.out.println("");........
EDIT: Okay, I edited out some non important stuff from the function. This is the function it runs, before returning to my while loop:
public static void buysystem(Connection con, Scanner sysbuy) {
System.out.println("What system do you want to buy?");
String sysreq = sysbuy.next().toUpperCase();
try {
Statement st = con.createStatement();
String query = "SQL";
ResultSet rs = st.executeQuery(query);
rs.next();
String nome = rs.getString("noob");
int price = rs.getInt("cpuprice") + rs.getInt("ramprice") + rs.getInt("mainboardprice") + rs.getInt("casesprice") + rs.getInt("gfxprice");
System.out.println("How many systems do you want to buy?");
int sysamount = sysbuy.nextInt();
//NEED TO MAKE CHECK AMOUNT FUNCTION
int realprice;
if (sysamount>10){
realprice = (price*130/100)-((price*130/100*120/100)-(price*130/100));
System.out.println("You want to buy " + sysamount + " of the system: " + sysreq + " for the price of " + realprice + "?");
System.out.println("Yes/No?");
String yesno = sysbuy.next();
if (yesno.toUpperCase().equals("YES")){
System.out.println("You just bought " + sysamount + " of the system " + sysreq + " for the price of " + realprice);
//UPDATE DB
}
}
else{
realprice = (price*130/100)-((price*130/100*(sysamount*2+100-2)/100)-(price*130/100));
System.out.println("You want to buy " + sysamount + " of the system: " + sysreq + " for the price of " + realprice + "?");
System.out.println("Yes/No?");
String yesno = sysbuy.next();
if (yesno.toUpperCase().equals("YES")){
System.out.println("You just bought " + sysamount + " of the system " + sysreq + " for the price of " + realprice);
//UPDATE DB
}
}
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("Print me");
}
I get this error now:
You just bought 1 of the system SERVER1 for the price of 7540
Print me
What may I do for you today?
I'm before
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at DBtest.requestHandler(DBtest.java:43)
at DBtest.main(DBtest.java:24)

Do not create multiple Scanners, instead use one scanner and use it inside your function or pass it to it if it is out of scope.
You created multiple Scanners, which you should not do, but also closed the second scanner. When you closed that scanner you closed the input stream which both scanners are using (the System's inputstream). This is what caused your crash.

Related

The insertion point is skipping a line

This is my first week of coding and I am unsure of why when I go to ask "Do you enjoy life", it forces me to type the answer on the next line.
import java.util.Scanner;
public class messing {
public static void main(String[] args) {
Scanner keyboardInput = new Scanner(System.in);
System.out.print("Enter Your Name: ");
String name = keyboardInput.nextLine();
System.out.print("How old are you: ");
int age = keyboardInput.nextInt();
System.out.println(name + " you are " + age + "?" + " Do you enjoy life: " );
String enjoy = keyboardInput.next();
System.out.print(enjoy + "?");
}
}
This is because the line of code that displays the question (line 13) uses the System.out.println() function, which, in addition to the text displayed, appends a newline character. This sends any further text onto the next line in the console. Replacing the function with the System.out.print() function removes this behavior.
That's because you're using System.out.println when asking the user if they enjoy life.
Simply change the function to System.out.print like the rest so you can input your answer in the same line.
System.out.print(name + " you are " + age + "?" + " Do you enjoy life: " );

Is there anyway to format this? The code already runs fine but the formatting will run if the value is too big

I know that I can just use printf to format it but printf is used to print. I want to use the formatting to store the data then call the data to print it outside the do while loop.
#Override
public String toString() {
Scanner input = new Scanner(System.in);
String enter = "", data = "";
double totalCommission = 0.0;
DecimalFormat df = new DecimalFormat();
do {
setTransaction();
setSalesNum();
setName();
setAmount();
setCommission();
setRate();
do {
//prompt user to enter another
System.out.println("Would you like to enter another? [Y/N]");
boolean error = false;
//error prompt if y or n is not entered
enter = input.next();
if (!(enter.equals("n") || enter.equals("N") || enter.equals("y") || enter.equals("Y"))) {
error = true;
System.out.println("Invalid input! Please enter again.\n Would you like to enter another student's mark? [Y/N]");
} else {
error = false;
}
} while (false);
//setting the decimal places
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(2);
//transaction details saved here
data += getTransaction() + "\t" + getSalesNum() + "\t\t" + getName() + "\t\t" + (df.format(getAmount())) + "\t" + " " + getRate() + "%" + "\t\t" + (df.format(getCompute())) + "\n";
totalCommission = totalCommission + getCompute();
} while (enter.equalsIgnoreCase("Y"));
System.out.println("Sales\tCommission");
System.out.println("TNO#\tSALESNO#\tNAME\t\tAMOUNT\t\t" + " " + "COMM RATE\tCOMMISSION");
return String.format(data + "\t\t\t\t\t\t" + " " + "TOTAL COMMISSION\t" + (df.format(totalCommission)));
}
So what I wanted to do is for this part data += getTransaction() + "\t" + getSalesNum() + "\t\t" + getName() + "\t\t" + (df.format(getAmount())) + "\t" + " " + getRate() + "%" + "\t\t" + (df.format(getCompute())) + "\n"; to be formatted inside while (enter.equalsIgnoreCase("Y")); then send data here: return String.format(data + "\t\t\t\t\t\t" + " " + "TOTAL COMMISSION\t" + (df.format(totalCommission)));
I'm sorry but I don't understand what you want to achieve. You may add an input and desired output example.
First of all:
if (!(enter.equals("n") || enter.equals("N") || enter.equals("y") || enter.equals("Y"))) {
if (!(enter.equalsIgnoreCase("n")|| enter.equalsIgnoreCase("y"))) {
You talked about print so you may want to take a look into: https://www.javatpoint.com/java-string-format
Because you mentioned String.format already I guess I misunderstood your question. If you reply back to me I will try to help you.
You wrote that you want to store your data inside that while loop and return it later. In this case, I would add every data to a list and return this list.

Print the formula used to describe the addition of two numbers

I am stuck in the U of Helsinki Java MOOC:
Create a program that can be used to add two integers together. In the beginning, the user is asked to give two integers that are to be summed. The program then prints the formula that describes the addition of the numbers.
Example output:
Give the first number:
5
Give the second number:
4
5 + 4 = 9
I am trying to get the system to print " "first" + "second" is "result". For some reason I am stumped on this otherwise easy question. My code is always throwing an error. What am I doing wrong in the last line?
import java.util.Scanner;
public class AdditionFormula {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// write your program here
System.out.println("Give the first number: ");
int first = Integer.valueOf(scanner.nextLine());
System.out.println("Give the second number: ");
int second = Integer.valueOf(scanner.nextLine());
//System.out.println("first" " + " Integer.valueOf(first) + Integer.valueOf(second));
System.out.println(first + " + " + second " = " + (first + second));
}
The code you provided does not compile
Change to
System.out.println(first + " + " + second + " = " + (first + second));

Program still looping after break in Java [duplicate]

This question already has answers here:
How do I break out of nested loops in Java?
(37 answers)
Closed 4 years ago.
I've been working on a program that will take the user's input of the name or symbol of an element in the periodic table and then output some facts about that element. After quite a few questions on here I've gotten to the point the program stores all the data correctly, outputs it in the way I want and can accept an input of both the name or symbol. The problem I'm having now is that the breaks I have inserted into a loop are not actually breaking from the loop, and I'm really not sure why. The program will just keep on asking for an input even if it received a correct input. In addition, if the user inputs a symbol rather than a name the program will repeatedly tell the user that their input was invalid before finally outputting correctly (and then restarting the loop rather than breaking as it should). I'm new to Java, so if anyone could help me fix either of these issues and explain why the problem occurred and how they fixed it fairly simply I would greatly appreciate it.
import java.util.Scanner;
public class PeriodicTable {
public enum Element {
Hydrogen("H", "Nonmetal", "1.008"),
Helium("He", "Noble Gas", "4.003"),
Lithium("Li", "Alkali Metal", "6.941"),
Beryllium("Be", "Alkaline Earth", "9.012"),
Boron("B", "Semimetal", "10.811"),
Carbon("C", "Nonmetal", "12.011"),
//The rest of the periodic table is here, I just removed it for the sake of this post.
private String symbol;
private String group;
private String weight;
private Element(String symbol, String group, String weight) {
this.symbol = symbol;
this.group = group;
this.weight = weight;
}
}
static Element cName = null;
public static void main(String[] args) {
System.out.println("Enter the name or symbol of an element in the periodic table. ");
do {
Scanner reader = new Scanner(System.in);
String input = reader.nextLine().trim();
for (Element sy : Element.values()) {
if (sy.symbol.equalsIgnoreCase(input)) {
System.out.println("Element: " + sy + " (" + sy.symbol + ")" + "\nGroup: " + sy.group + "\nAtomic Mass: " + sy.weight);
reader.close();
break;
} else {
try {
cName = Element.valueOf(input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase());
System.out.println("Element: " + cName + " (" + cName.symbol + ")" + "\nGroup: " + cName.group + "\nAtomic Mass: " + cName.weight);
reader.close();
break;
} catch(IllegalArgumentException e) {
System.out.println("That name or symbol is not valid. Please try again. ");
continue;
}
}
}
} while (true);
}
}
The problem is that the break's are within the for loop, so it only breaks to for loop. If you want to break the do-while loop you can use a label:
outer:
do {
Scanner reader = new Scanner(System.in);
String input = reader.nextLine().trim();
for (Element sy : Element.values()) {
if (sy.symbol.equalsIgnoreCase(input)) {
System.out.println("Element: " + sy + " (" + sy.symbol + ")" + "\nGroup: " + sy.group + "\nAtomic Mass: " + sy.weight);
reader.close();
break outer;
} else {
try {
cName = Element.valueOf(input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase());
System.out.println("Element: " + cName + " (" + cName.symbol + ")" + "\nGroup: " + cName.group + "\nAtomic Mass: " + cName.weight);
reader.close();
break outer;
} catch(IllegalArgumentException e) {
System.out.println("That name or symbol is not valid. Please try again. ");
continue;
}
}
}
} while (true);

an array does not get a value

I have a problem with the following code
public static void SideBet(int numberDice,int bet,int money) {
System.out.println("You established a " + "\""+ "point" + "\"" + ". " + "Your " + "\""+ "point" + "\"" + " is " + numberDice + ". " + "You have to roll a(n) " + numberDice + " to win your bet, "+ bet +" chips." );
System.out.println();
System.out.println("You can put side bets for 4,5,6,8,9 or 10.");
SideBetChoice = Console.readLine("Would you like to make any side bets ? (Type " + "\""+ "Yes" + "\"" + " or "+ "\""+ "No" + "\"" + ", then hit Enter.)");
int s = 0;
int r = 0;
if (SideBetChoice.equals("Yes")) {
System.out.println("You can put as many side bets as you would like for the numbers 4,5,6,8,9 or 10.");
int SideBetNumber = Console.readInt("How many side bets would you like to make ? (Introduce a number, minimum 1, maximum 6.)");
int[] SBNArray = new int[SideBetNumber];
int[] sbArray = new int[SideBetNumber];
for (s = 0; s <= (SideBetNumber -1) ; s++) {
SBNArray[s] = Console.readInt("On which number would you like to put a side bet ?");
sbArray[s] = Console.readInt("Currently you have " + money + " chips, how much would you like to bet ?");
money = money - sbArray[s];
System.out.println("Thank you for your " +sbArray[s]+ " chip side bet on number " +SBNArray[s]+".");
System.out.println();
}
}
if (SideBetChoice.equals("No")) {
return;
}
sbArray and SBNArray does not get a value and it keeps crashing ...
Can anyone help me out and tell me what is wrong, why the 2 arrays do not get a value, therefor they are null ?
There is no readInt()-method in Console.
Also I'm not sure if you're using console correctly, it should look like this:
Console console = System.console();
console.readLine("Type something");
Just use readLine() and convert it to an int:
Console console = System.console();
String input = console.readLine("Type a number");
try
{
int myNumber = Integer.parseInt(input);
}
catch(NumberFormatException e)
{
System.out.println("This ain't a number!");
}
Also please never use Capital Letters for Variables' Names or method-names, it's very confusing because you could think it would be a Class or a Type.
So please change the name of SBNArray and SideBetNumber, SideBetChoice etc. etc.
Only Constants should be written with only Capital Letters and Classes and Types start with Capital Letters.
EDIT:
Sorry, it seems that you're using BreezyGUI.Console, therefore there is a readInt()-method.
Could you give more information?
I'd like to know if the text of the readInt() is even displayed.

Categories