How can i fix this Integer variable to String? - java

I have a integer variable but I want it so that
if the user inputs the string 'quit' it will close the program.
public static void input() {
System.out.println("Input: ");
Integer choice = scan.nextInt();
choiceExecute(choice);
if (choice == 'quit') {
goBack();
}
}
Thanks in advance.

Use scan.hasNextInt() to check if the input is a Integer. If so, you can use scan.nextInt(); for getting the integer. If it returns false, you can read the value with scan.nextLine(). If this equals quit, the program should close.

There are a couple things wrong here.
This only searches for Integers:
Integer choice = scan.nextInt();
However, this will return the entire line:
String line = scan.nextLine();
And from this you can do the check to see if it is equal to quit:
if(line.equals("quit"){
// do your processing
goBack();
}else{
Integer num = Integer.parseInt(line);
// do your processing on the number
choiceExecute(num);
}
This is of course making the assumption that you are only storing one item per line and that all other lines that are not equal to "quit" are indeed numbers. Here is how I assume your data looks:
221
357
quit
43
565
quit

One way would be to just read in strings using:
scan.nextLine();
(So you can easily check for "quit").
Then just covert the string to an Integer using:
Integer.parseInt(myString);

Related

While-loop will not terminate in console after entering numbers

I keep trying to get this to work but when I enter in the numbers and enter them into the console it does not finish. I have to terminate myself.
import java.util.Scanner;
public static void main(String[] args) {
int cmlSum = 0;
int inputNum;
String outputSum = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter sequence of numbers ");
do {
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
} while (keyboard.hasNextInt());
System.out.println(outputSum);
}
Well, yes. The keyboard.hasNextInt() call will return false for two reasons.
The next token is a NOT an integer.
You have reached the end-of-input.
What is (most likely) happening is that you have stopped entering numbers. The program is (patiently) waiting for you to enter ... something.
Solutions:
Tell the user to enter the (OS specific) terminal "end of file" character. On Linux it is CTRL-D. On Windows CTRL-Z.
Tell the user to enter something that isn't an integer.
Pick an integer as meaning that there are no more numbers, and test for that.
You also need to instruct the user how to "end" the sequence; e.g.
System.out.println("Enter sequence of numbers. Enter a non-number to stop.");
This is actually a problem with your application's "user interface" design. If the user is expected to type an arbitrarily long sequence of numbers (or something else), then there needs to be some way for the user to tell the program that the sequence is finished. The program cannot magically distinguish the cases of "there are no more" and "hang on, I'm taking a break from typing".
The hasNext() method checks if the Scanner has another token in its input. A Scanner breaks its input into tokens using a delimiter pattern, which matches whitespace by default. That is, hasNext() checks the input and returns true if it has another non-whitespace character.
In this case hasNext() won't return true because there is neither any integer nor any whitespace. Therefore the program waits for the next input. Besides use a specific integer to break the loop.
for instance,
System.out.println("Input -1 will end the program!";
do{
int x = keyboard.nextInt();
if(x == -1){
break;
}
//do something
}while(true);
Your code is ok. There is no issue.
But before writing code, we need to think about it. The workflow of your code below:
1st time when we enter do loop, keyboard.nextInt() takes input from us.
Then it calculates the sum and performs string operation.
After that, while's keyboard.hasNextInt() takes next input from you.
Checks your input. If your input is not an integer, while loop will terminate(break).
If your input is an integer then, code loop back to keyboard.nextInt(). But this time, it does not take input from you.
It pases the buffered input(keyboard.hasNextInt()) to keyboard.nextInt() and assign the value to inputNum
So, when you want to terminate while loop, you should input any character like a, b, c, etc.
You haven't specified when the loop will end. Have a condition such as inputting a certain number that will end the program once entered, as currently your program is just going to wait for more input. Something like :
System.out.println("Enter sequence of numbers to add. Enter '0' to end the program");
do {
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
} while (inputNum != 0);//Keeps going as long as 0 is not entered
//When zero is entered, program shows the total sum and terminates
if (inputNum == 0) {
System.out.println("The sum of all total numbers: ");
System.out.println(outputSum);
System.exit(0);//Terminates program
}
Basic syntax of do-while Loop:
do{
// do something
}while(terminating condition);
If you are using hasNextInt() method of Scanner object for terminating condition in do-while loop then loop will be terminated once it get input other than an integer value (e.g float, double, char, String etc.. ) as shown in below complete program.
import java.util.Scanner;
public class Cumulative{
public static void main(String[] args){
int cmlSum = 0;
int inputNum;
String outputSum = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter sequence of numbers ");
do{
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
}while (keyboard.hasNextInt()); // loop will terminated whenever get any value other than valid integer such as float char or String etc..
System.out.println(outputSum);
}
}

Is it possible to check if the input is an integer without hasNextLine and exit loop if it's 0?

My method works perfectly,but I want to exit the loop if 0 is entered.I know I can use getArray.hasNextInt() and then if the input was an integer put into a new variable and then check again if it's 0,then leave the loop,but I think that'd be too long of a code and needs at least two other variables(an integer and a boolean) to be created.
I have written a method like so:
public static char[] play() { //Takes a string from the user,checks if the length is 5,and converts to character array.
boolean fiveChars =false;
System.out.println("Please enter your input: ");
Scanner getArray = new Scanner (System.in);
while(!fiveChars) {
String gotArray = getArray.nextLine();
if(gotArray.length()==5) {
myInput=gotArray.toCharArray();
break;}
else
{ if(gotArray.charAt(0)==0 && gotArray.length()==1) {
a++;
menu();
break;}
else
System.out.println("Please try again!Your input should consist of 5 characters!");
System.out.println("giving a new input doesn't count as one of your choices.");
}}
return myInput;
}
But it doesn't work.I want to know why
if(gotArray.charAt(0)==0 && gotArray.length()==1)
Blockquote
doesn't work here.Also,would you please tell me if there is a shorter way that works exists?Thanks.
Either
if(gotArray.charAt(0)=='0' && gotArray.length()==1)
OR
if(Integer.parseInt(gotArray.charAt(0))==0 && gotArray.length()==1)
should work.

Java Nested If statement-Or Compared to !=

I wasn't sure how to give a title for this problem, but basically this is part of my blackjack program. Also, since I did not know how to title this, I wasn't sure how to look it up, which is why I am asking here. So I am saying that when the user enters either 1 or 11 for the ace value, if they enter something other than 1 or 11, it asks the user again to put in 1 or 11. In my program everything works fine except when the user enters 1, then it just asks the question again. The program should only asks again if the input is not equal to 1 or 11. Here is my code as I made sure it always gives an ace for testing purposes:
String card1="A";
int total=0;
Scanner input_var=new Scanner(System.in);
if (card1=="A"){
System.out.println("Do you want a 1 or 11 for the Ace?: ");
int player_ace_selection=input_var.nextInt();
if ((1|11)!=(player_ace_selection)){
System.out.println("Please enter a 1 or 11: ");
int new_selection=input_var.nextInt();
total=total + new_selection;
}
else {
total=total + player_ace_selection;
}
}
System.out.println(total);
Thanks in advance.
The expression (1|11) uses binary OR, which produces 11:
11 = 01001
1 = 00001
(11|1) = 01001
Hence, the comparison is the same as 11!=player_ace_selection
You should change the code to use logical OR, i.e.
if (1!=player_ace_selection && 11!=player_ace_selection) {
...
}
In addition, you need to fix card1 == "A" comparison for card1.equals("A")
Instead of an If statement, try a while loop. A while loop ensures that your program waits for your user to pick the right answer. You also made a mistake with your logical operations. The correct way to use "OR" in this context is to compare your user input to both '1' and '11' separately using '||'.
String card1="A";
int total=0;
Scanner input_var=new Scanner(System.in);
if (card1.equals("A")){
System.out.println("Do you want a 1 or 11 for the Ace?: ");
int player_ace_selection=input_var.nextInt();
while(player_ace_selection != 1 && player_ace_selection != 11){
System.out.println("Do you want a 1 or 11 for the Ace?: ");
player_ace_selection = input_var.nextInt();
}
total += player_ace_selection;
}
System.out.println(total);
There are some problems in your code, please consider this example and compare it with yours.
String card1="A";
int total=0;
Scanner input_var=new Scanner(System.in);
if (card1.equals("A")){ // compare the content not the reference (==)
System.out.println("Do you want a 1 or 11 for the Ace?: ");
try{ // wrap with try-catch block
int player_ace_selection = Integer.parseInt(input_var.nextLine()); //read the entire line and parse the input
if ((player_ace_selection!=1)&&(player_ace_selection!=11)){
System.out.println("Please enter a 1 or 11: ");
try{
int new_selection = Integer.parseInt(input_var.nextLine()); //again read the entire line and parse the input
total=total + new_selection;
}catch(NumberFormatException e){
// do something to catch the error
}
}
else {
total=total + player_ace_selection;
}
}catch(NumberFormatException e){
// do something to catch the error
}
System.out.println(total);
}

How do I ensure that Scanner hasNextInt() asks for new input?

New programmer here. This is probably a really basic question, but it's stumping me nevertheless.
What I'm trying to do is write a method that supplies only one integer input so I can use that input in my main program without having to mess around with non-integer inputs. However, even writing the method to do that in its own method seems to be problematic.
public static int goodInput () {
Scanner input = new Scanner (System.in); //construct scanner
boolean test = input.hasNextInt(); //set a sentinel value
while (test == false) { //enter a loop until I actually get an integer
System.out.println("Integers only please"); //tell user to give me an integer
test = input.hasNextInt(); //get new input, see if it's an integer
}
int finalInput = input.nextInt(); //once i have an integer, set it to a variable
input.close(); //closing scanner
return finalInput; //return my integer so I don't have to mess around with hasNextInt over there
}
This seems to be broken in multiple levels, but I'm not really sure why.
If I enter an integer value like 0 or 1 when I'm first asked for input, it should skip the loop entirely. But, instead, it enters the loop, and prints "Integers only please". Even worse, it doesn't actually ask for input while I'm in there, and just prints that line repeatedly.
I understand the latter problem is probably due to token issues, but I'm not necessarily sure how to solve them; closing and then reopening the scanner gets Eclipse to bug me over "duplicate objects", simply assigning the old input to a garbage String variable that is never used tells me that "No line was found" at runtime, and I'm not experienced enough to think of other ways to get new input.
Even once that's solved, I need to find some way to avoid entering the loop in the case of having an integer. I don't really understand why integer inputs inter the loop to begin with, so I'm not sure how this would be possible.
Please help? Sorry if this is an old question; tried looking at past questions but none of them seem to have the same problem that I have.
You were close: this works fine for me:
Scanner input = new Scanner(System.in); //construct scanner
while(!input.hasNextInt()) {
input.next(); // next input is not an int, so consume it and move on
}
int finalInput = input.nextInt();
input.close(); //closing scanner
System.out.println("finalInput: " + finalInput);
By calling input.next() in your while loop, you consume the non-integer content and try again, and again, until the next input is an int.
//while (test == false) { // Line #1
while (!test) { /* Better notation */ // Line #2
System.out.println("Integers only please"); // Line #3
test = input.hasNextInt(); // Line #4
} // Line #5
The problem is that in line #4 above, input.hasNextInt() only tests if an integer is inputted, and does not ask for a new integer. If the user inputs something other than an integer, hasNextInt() returns false and you cannot ask for nextInt(), because then an InputMismatchException is thrown, since the Scanner is still expecting an integer.
You must use next() instead of nextInt():
while (!input.hasNextInt()) {
input.next();
// That will 'consume' the result, but doesn't use it.
}
int result = input.nextInt();
input.close();
return result;

Java - appending & passing values

I'm having trouble with passing a string and double to another class because it keeps on crashing at double cost = input.nextDouble();. Also, i was wondering if i am correct with the appending method used in public boolean addPARTDETAILS(String partDESCRIPTION, double partCOST).
For example. If the user enters the parts and cost, i want it to store that in a list and print it out with the cost appended.
Parts used:
brake pads ($50.00)
brake fluids ($25.00)
Note. Assuming that i have declared all variables and the array.
System.out.print("Enter registration number of vehicle");
String inputREGO = input.next();
boolean flag = false;
for(int i=0; i<6; i++){
if(inputREGO.equalsIgnoreCase(services[i].getregoNUMBER())){
System.out.print("Enter Part Description: ");
String parts = input.nextLine();
double cost = input.nextDouble();
services[i].addPARTDETAILS(parts, cost);
//System.out.println(services[i].getregoNUMBER());
flag = true;
}
}if(flag==false);
System.out.println("No registration number were found in the system.");
public boolean addPARTDETAILS(String partDESCRIPTION, double partCOST){
if(partDESCRIPTION == "" || partCOST <= 0){
System.out.println("Invalid input, please try again!");
return false;
}
else{
partCOST=0;
StringBuffer sb = new StringBuffer(40);
String[] parts = new String[50];
for (int i=0;i<parts.length;i++){
partDESCRIPTION = sb.append(partCOST).toString();
}
System.out.println(partDESCRIPTION);
totalPART+=partCOST;
return true;
}
}
it keeps on crashing at double cost = input.nextDouble();.
It is highly unlikely that your JVM is crashing. It is far more likely that you are getting an Exception which you are not reading carefully enough and have forgotten to include in your question.
It is far more likely your code is incorrect as you may have mis-understood how scanner works. And so when you attempt to read a double, there is not a double in the input. I suspect you want to call nextLine() after readDouble() to consume the rest of the the line.
I suggest you step through the code in your debugger to get a better understanding of what it is really doing.
Just to expand a bit on Joop Eggen's and Peter Lawrey's answers because I feel some may not understand.
nextLine doesn't play well with others:
nextDouble is likely throwing a NumberFormatException because:
next, nextInt, nextDouble, etc. won't read the following end-of-line character, so nextLine will read the rest of the line and nextDouble will read the wrong thing.
Example: (| indicates current position)
Start:
|abc
123
def
456
After nextLine:
abc
|123
def
456
After nextDouble:
abc
123|
def
456
After nextLine (which reads the rest of the line, which contains nothing):
abc
123
|def
456
Now nextDouble tries to read "def", which won't work.
If-statement issues:
if(flag==false);
or, rewritten:
if(flag==false)
;
is an if statement with an empty body. Thus the statement following will always execute. And no need to do == false, !flag means the same. What you want:
if (!flag)
System.out.println("No registration number were found in the system.");
String comparison with ==:
partDESCRIPTION == ""
should be:
partDESCRIPTION.equals("")
or better:
partDESCRIPTION.isEmpty()
because == check whether the strings actually point to the exact same object (which won't happen unless you assign the one to the other with = at some point, either directly or indirectly), not just whether the have the same text (which is what equals is for).
Data dependent error.
if(flag==false);
System.out.println("No registration number were found in the system.");
should be (because of the ;):
if (!flag) {
System.out.println("No registration number was found in the system.");
}
And
partDESCRIPTION == ""
should be:
partDESCRIPTION.isEmpty()

Categories

Resources