Java get integer input method requires the input twice - java

here is the Menu class
import java.util.Scanner;
public class Menu {
private String[] menu_options;
public Menu(String[] menu_options) {
this.menu_options = menu_options;
}
public int getUserInput() {
int i = 1;
for (String s : this.menu_options) {
System.out.println(i + ". " + s);
i++;
}
int selection = getint_input(menu_options.length);
return (selection);
}
private int getint_input(int max) {
boolean run = true;
int selection = 0;
while (run) {
System.out.print("Select an option: ");
Scanner in = new Scanner(System.in);
if (in.hasNextInt()) {
int value = in.nextInt();
if(value>=1 || value<=max){
selection = value; //fixed this now working
run = false;
}
} else {
System.out
.print("Invalid input. Please enter a integer between 1 and "
+ max + ": ");
}
}
return selection;
}
}
and here is the menudriver i was using
public class Menutester {
public static void main(String[] args) {
String[] menuitems = new String[2];
menuitems[0] = "option one";
menuitems[1] = "option two";
Menu tm = new Menu(menuitems);
int choice = tm.getUserInput();
System.out.println("Got input");
}
}
the first time i input something it dosn't regester at all and when i try to debug it in eclipse it gives me the error FileNotFoundException(Throwable).(String) line: 195 on the first input.
this is what it returns
option one
option two
Select an option: 1(i entered this and pressed enter)
1(same here only it regestered the input)
Got input

nextInt reads the input and removes it from the buffer. You can't call it like that without storing the value.
Call it once, store the value, and then do all the checks needed.
Change this:
if (in.hasNextInt() && in.nextInt() >= 1 || in.nextInt() <= max) {
selection = in.nextInt();
//...
for this:
if(in.hasNextInt()) {
int selection = in.nextInt();
if(selection >= 1 || selection <= max) {
run = false;
}
}

replace:
if (in.hasNextInt() && in.nextInt() >= 1 || in.nextInt() <= max) {
selection = in.nextInt();
run = false;
System.out.println(run);
}
as:
int input = in.nextInt();
if (input >= 1 || input <= max) {
selection = in.nextInt();
run = false;
System.out.println(run);
}
and try it again.

Related

Returning a set of array to the main method using for loop, gives error deadcode

Currently programming a Clock with an alarm and met my first Dead Code error.
User input have already stored data into the following variables; aAlarm, aHour, and aMinute.. but I can't seem to get them to display into the main method. I have tried searching other problems regarding dead error and none seem to solve my problem. Below is the code, the variable 'instances' equals to 1 and will increment for the amount of times the user creates an alarm.
import java.util.*;
public class Frontend {
public static void main(String args[]) {
Backend nyet = new Backend();
Scanner scn = new Scanner(System.in);
int dec, dec2;
System.out.print("The time is: ");
System.out.println(nyet.displayClock());
//Class clock----------------------------
//Class setTime--------------------------
System.out.print("Do you wish to alter time| 1 = Yes, 0 = No:");
dec = scn.nextInt();
if (dec == 1) {
System.out.print("Input Hour:");
int hour = scn.nextInt();
if (hour < 0 || hour > 24) {
System.out.println("Sorry, there are only 24hrs in one day.");
System.exit(0);
}
System.out.print("Input Minute:");
int minute = scn.nextInt();
if (minute < 0 || minute > 60) {
System.out.println("Sorry, there are only 60mins in one hour.");
System.exit(0);
}
System.out.print("Input Second:");
int second = scn.nextInt();
if (second < 0 || second > 60) {
System.out.println("Sorry, there are only 60second in one minute.");
System.exit(0);
}
nyet.setTime(hour, minute, second);
scn.close();
System.out.print("The time is: ");
System.out.println(nyet.displayClock());
} //Class setTime--------------------------
//Class setAlarm-------------------------
System.out.print("Do you wish to set an alarm| 1 = Yes, 0 = No:");
int dec1 = scn.nextInt();
if (dec1 == 1) {
do {
int instc = 1;
System.out.print("Input alarm number:");
int aNum = scn.nextInt();
System.out.print("Input Hour:");
int aHr = scn.nextInt();
if (aHr < 0 || aHr > 24) {
System.out.println("Sorry, there are only 24hr in one day.");
System.exit(0);
}
System.out.print("Input Minute:");
int aMin = scn.nextInt();
if (aMin < 0 || aMin > 60) {
System.out.println("Sorry, there are only 60mins in one hour.");
System.exit(0);
}
System.out.print("Do you wish to set another alarm| 1 = Yes, 0 = No:");
dec2 = scn.nextInt();
if (dec2 == 1)
instc++;
nyet.setAlarm(instc, aNum, aHr, aMin);
}while (dec2 != 0);
} //Class setAlarm-------------------------
System.out.print("Show alarm| 1 = Show, 0 = Nothing:");
int z = scn.nextInt();
if (z == 1)
nyet.displayAlarm();
}
}
import java.time.OffsetTime;
public class Backend {
OffsetTime nyet = OffsetTime.now();
private int cHour, cMinute, cSecond, instances;
private int[] aAlarm, aHour, aMinute;
private boolean[] alarmOn;
public Backend() {
cHour = nyet.getHour();
cMinute = nyet.getMinute();
cSecond = nyet.getSecond();
aHour = new int[2];
aMinute = new int[2];
aAlarm = new int[2];
alarmOn = new boolean[2];
for (int i = 0; i < 2; i++) {
alarmOn[i] = !alarmOn[i];
}
}
public void setAlarm(int instncs,int aNmbr, int aHr, int aMnt) {
for (int i = 0; i < instncs; i++) {
aAlarm[i] = aNmbr;
aHour[i] = aHr;
aMinute[i] = aMnt;
instances = instncs;
}
}
public void setTime(int hr, int min, int sec) {
cHour = hr;
cMinute = min;
cSecond = sec;
}
public String displayClock() {
return String.format("%02d:%02d:%02d", cHour, cMinute, cSecond);
}
public String displayAlarm() {
for (int i = 0; i < instances; i++) { //<<< Dead Code
return String.format("%02d:%02d:%02d", aAlarm[i], aHour[i], aMinute[i]);
}
}
}
When I entered the code for your class Backend in my Eclipse, it showed a build error for method displayAlarm(), namely...
This method must return a result of type String
Here is the code for method displayAlarm() (exactly as it appears in your question).
public String displayAlarm() {
for (int i = 0; i < instances; i++) { //<<< Dead Code
return String.format("%02d:%02d:%02d", aAlarm[i], aHour[i], aMinute[i]);
}
}
It is possible that the for loop in the method will not be entered and in that case the method does not return anything. So I just added a line to get rid of the build error.
public String displayAlarm() {
for (int i = 0; i < instances; i++) { //<<< Dead Code
return String.format("%02d:%02d:%02d", aAlarm[i], aHour[i], aMinute[i]);
}
return "";
}
After adding the line, I got the dead code warning. I admit that it took me a while to discover the reason. Finally it dawned on me. The only thing in the for loop body is return. Hence there will only ever be precisely one loop iteration, so why increment i?
Guess the problem was the class had no 'static' in it.
Front end code:
public static void main(String args[]) {
int dec, dec2, amount = 0, deci0;
Backend nyet = new Backend();
Scanner scn = new Scanner(System.in);
System.out.print("Do you wish to set an alarm| 1 = Yes, 0 = No:");
int dec1 = scn.nextInt();
if (dec1 == 1) {
do {
System.out.print("Input alarm number(Stored = " + amount + "):");
int aNum = scn.nextInt();
System.out.print("Input Hour:");
int aHr = scn.nextInt();
if (aHr < 0 || aHr > 24) {
System.out.println("Sorry, there are only 24hr in one day.");
System.exit(0);
}
System.out.print("Input Minute:");
int aMin = scn.nextInt();
if (aMin < 0 || aMin > 60) {
System.out.println("Sorry, there are only 60mins in one hour.");
System.exit(0);
}
nyet.setAlarm(amount, aNum, aHr, aMin);
System.out.print("Do you wish to set another alarm(max 3)| 1 = Yes, 0 = No:");
dec2 = scn.nextInt();
if (dec2 == 1) {
amount++;
}else if (dec2 == 0) {
amount++;
nyet.setAlarm(amount, aNum, aHr, aMin);
}else {
System.out.println("The only choices are '1' and '0'.");
System.exit(0);
}
if (amount > 3) {
System.out.println("You have reached maximum storage.");
dec2 = 0;
}
}while (dec2 != 0);
}
Back end code:
public class Backend {
OffsetTime nyet = OffsetTime.now();
private int cHour, cMinute, cSecond;
private static int[] aAlarm, aHour, aMinute;
private boolean[] alarmOn;
private static int amnt;
public void setAlarm(int instncs,int aNmbr, int aHr, int aMnt) {
int i = instncs;
aAlarm[i] = aNmbr;
aHour[i] = aHr;
aMinute[i] = aMnt;
amnt = instncs;
}
public static void displayAlarm() {
for (int i = 0; i < amnt; i++) {
System.out.println("Alarm #" + aAlarm[i] + " - " + aHour[i] + ":" + aMinute[i]);
}
}

Program won't continue when pressing enter. How do I fix this error?

I am working on a rock paper scissors homework assignment for my java class. I am done with the program and I compiled it successfully. I ran the file and it looked like it was working. It gives me the menu and I choose a variable, R for example, and when I press enter it doesn't do anything but go to the next line. I press enter again and it gives me an index out of bounds error which I assume is because the second time it didn't have a variable to use. How do I get the program to move forward? The program is supposed to play five times then return a winner. Thanks in advance.This image is what I get when I run the program and press enter twice
package Rock;
import java.util.Scanner;
public class RPSG {
public static void main(String[] args) {
String[] computerHandArray = {"R","P","S"};
String computerHand ="", thisWinner="", theFinalWinner="";
int index=0;
int timesIWon=0;
int timesComputerWon=0;
Scanner in = new Scanner(System.in);
System.out.println("\tMenu\n\n(R) Rock\n(P) Paper\n(S) Scissors" + "\n\nEnter Your Hand (R, P, or S): ");
for (int i=0; i<5; i++) {
String myHandString = in.nextLine();
String myHand = myHandString.substring(0,1);
myHand = myHand.toUpperCase();
index = (int)(Math.random() * 10) % 3;
computerHand = computerHandArray[index];
thisWinner = theWinnerofOneGame(myHand, computerHand);
if(thisWinner.equals("ME")){
timesIWon++;
}
else if(thisWinner.equals("COMPUTER")) {
timesComputerWon++;
}
}
if(timesIWon == timesComputerWon)
theFinalWinner = "TIE";
else if(timesIWon > timesComputerWon)
theFinalWinner = "ME";
else if(timesComputerWon > timesIWon)
theFinalWinner = "COMPUTER";
System.out.println("I won :" + timesIWon);
System.out.println("I won :" + timesComputerWon);
System.out.println("The Final Winner after 5 games is:" +theFinalWinner);
}
private static String theWinnerofOneGame(String myHand, String computerHand){
String theWinner = "Tie";
if(myHand.equals(computerHand)) {
theWinner = "Tie";
}
else if(myHand.equals("R")) {
if (computerHand.equals("P")) {
theWinner = "COMPUTER";
}
}
else if(computerHand.equals("S")) {
theWinner = "ME";
}
else if(myHand.equals("P")) {
if (computerHand.equals("R")) {
theWinner = "ME";
}
else if(computerHand.equals("S")) {
theWinner = "COMPUTER";
}
}
else if(myHand.equals("S")) {
if (computerHand.equals("R")) {
theWinner = "COMPUTER";
}
else if(computerHand.equals("P")) {
theWinner = "ME";
}
}
return theWinner;
}
}
You print the prompt for input only once, i.e. before the for loop. Now when you enter your first input, the content of the loop will be executed. Because you don't print anything inside the loop, there is no prompt for the next round. After you press enter a second time, the in.nextLine() returns an empty string and subsequently, the substring method throws the exception.
You should probably do something like this (note the marked lines):
System.out.println("\tMenu\n\n(R) Rock\n(P) Paper\n(S) Scissors" + "\n\n");
for (int i=0; i<5; i++) {
> System.out.println("Enter Your Hand (R, P, or S): ");
String myHandString = in.nextLine();
String myHand = myHandString.substring(0,1);
myHand = myHand.toUpperCase();
index = (int)(Math.random() * 10) % 3;
computerHand = computerHandArray[index];
thisWinner = theWinnerofOneGame(myHand, computerHand);
if(thisWinner.equals("ME")){
timesIWon++;
> System.out.println("You won.");
} else if(thisWinner.equals("COMPUTER")) {
timesComputerWon++;
> System.out.println("The computer won.");
}
}
And even better, check if the input of the user is valid before computing the substring.

Endless loop created if scanner receives something other than an int

In this java Method, the point is for scanner to receive an int between the min and the max values. If an int is received that is outside those bounds, the program correctly outputs "Invalid input". However if something like "g" or "h" or something other than an int is entered, an endless loop is created.
I tried to reinitialize Scanner in multiple locations in the code but it looks like when something other than an int is entered from a System.in, it just flies right by scanner again and keeps the loop going. Any Thoughts
public static int promptInt(int min, int max) {
while (false != true) {
int b = 0;
Scanner scnr = new Scanner(System.in);
System.out.print("Choose a value between " + min + " and " + max + ": ");
if (scnr.hasNext()) {
if (scnr.hasNextInt()) {
b = scnr.nextInt();
if (b <= max) {
return b;
} else {
System.out.println("Invalid Value");
}
}
else if (scnr.hasNextInt() == false) {
System.out.println("Not an Int");
}
}
}
}
As per some comments above, a scnr.next() was needed otherwise it was continuing to check the first scanner that was initialized. Here is the revised code which now functions.
public static int promptInt(int min, int max) {
Scanner scnr = new Scanner(System.in);
while (false != true) {
int b = 0;
System.out.print("Choose a number between " + min + " and " + max + ": ");
if (scnr.hasNext()) {
if (scnr.hasNextInt() == false) {
System.out.println("Invalid value.");
//the scnr.next was needed here
scnr.next();
}
else {
b = scnr.nextInt();
if (b <= max) {
return b;
} else {
System.out.println("Invalid value.");
}
}
}
}
}

While Loop Parsing Issue

I'm trying to give the user an infinite amount of inputs until they enter q. I'm using a while statement to run the program, but when the user tries to quit I get an error because the program would try and parse q as an integer. Any ideas on how I should change the structuring of this to prevent the error from occurring?
Scanner in = new Scanner(System.in);
System.out.println("What would you like your Fibonacci number to be?(enter q to quit)");
String value = in.next();
int trueValue;
while(!value.equalsIgnoreCase("q")) {
trueValue = Integer.parseInt(value);
Fibonacci userCase = new Fibonacci(trueValue);
System.out.println(userCase.calculateFibonacci(userCase.getCaseValue()));
System.out.println("Please enter another number.");
value = in.next();
trueValue = Integer.parseInt(value);
}
If it matters, here are the methods being called within the loop.
public int calculateFibonacci(int caseValue) {
if(caseValue == 0)
return 0;
else if(caseValue == 1)
return 1;
else
return calculateFibonacci(caseValue-1) + calculateFibonacci(caseValue-2);
}
public int getCaseValue()
{
return caseValue;
}
You can remove the last
trueValue = Integer.parseInt(value);
since you are already doing that at the start of the loop.
do{ getting the user value before checking } while(checking if it's ok);
/* https://stackoverflow.com/questions/40519580/trying-to-determine-if-a-string-is-an-integer */
private boolean isInteger(String str) {
if(str == null || str.trim().isEmpty()) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if(!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
public static String check(Scanner in) {
String value;
do {
System.out.println("Please enter a number or q to quit.");
value = in.next();
} while(!value.equalsIgnoreCase("q") && !isInteger(value));
return value;
}
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
String value = check(in);
while(!value.equalsIgnoreCase("q")) {
Fibonacci userCase = new Fibonacci(Integer.parseInt(value));
System.out.println(userCase.calculateFibonacci(userCase.getCaseValue()));
value = check(in);
}
in.close();
}

NumberFormatException: For input string: "[memorylocation" java

I'm doing an assignment where the goal is to, among other things, to add two large integers. Here is my code, spread out into four files.
Main that we cannot change:
import java.util.*;
import MyUtils.MyUtil;
public class CSCD210HW7
{
public static void main(String [] args)throws Exception
{
int choice;
String num;
LargeInt one, two, three = null;
Scanner kb = new Scanner(System.in);
num = HW7Methods.readNum(kb);
one = new LargeInt(num);
num = HW7Methods.readNum(kb);
two = new LargeInt(num);
do
{
choice = MyUtil.menu(kb);
switch(choice)
{
case 1: System.out.println(one + "\n");
break;
case 2: System.out.println("The value of the LargeInt is: " + two.getValue() + "\n");
break;
case 3: num = HW7Methods.readNum(kb);
one.setValue(num);
break;
case 4: if(one.equals(two))
System.out.println("The LargeInts are equal");
else
System.out.println("The LargeInts are NOT equal");
break;
case 5: three = two.add(one);
System.out.printf("The results of %s added to %s is %s\n", one.getValue(), two.getValue(), three.getValue());
break;
case 6: HW7Methods.displayAscendingOrder(one, two, three);
break;
default: if(two.compareTo(one) < 0)
System.out.printf("LargeInt %s is less than LargeInt %s\n", two.getValue(), one.getValue());
else if(two.compareTo(one) > 0)
System.out.printf("LargeInt %s is greater than LargeInt %s\n", two.getValue(), one.getValue());
else
System.out.printf("LargeInt %s is equal to LargeInt %s\n", two.getValue(), one.getValue());
break;
}// end switch
}while(choice != 8);
}// end main
}// end class
LargeInt Class(Custom Class We Created)
public class LargeInt implements Comparable<LargeInt>
{
private int[]myArray;
private LargeInt()
{
this("0");
}
public LargeInt(final String str)
{
this.myArray = new int[str.length()];
for(int x = 0; x < this.myArray.length; x++)
{
this.myArray[x] = Integer.parseInt(str.charAt(x)+ "");
}
}
public LargeInt add(final LargeInt passedIn)
{
String stringOne = myArray.toString();
String stringTwo = passedIn.myArray.toString();
int r = Integer.parseInt(stringOne);
int e = Integer.parseInt(stringTwo);
int s = r + e;
return new LargeInt(""+s);
}
public void setValue(final String arrayString)
{
this.myArray = new int[arrayString.length()];
for(int x = 0; x < myArray.length; x++)
{
this.myArray[x]=arrayString.charAt(x);
}
}
#Override
public int compareTo(LargeInt passedIn)
{
if(passedIn == null)
{
throw new RuntimeException("NullExceptionError");
}
int ewu = 0;
int avs = 0;
if(this.myArray.length != passedIn.myArray.length)
{
return this.myArray.length - passedIn.myArray.length;
}
for(int i = 0; i < this.myArray.length -1; i++)
{
if(this.myArray[i] != passedIn.myArray[i])
{
return this.myArray[i]-passedIn.myArray[i];
}
}
return ewu-avs;
}
public int hashCode()
{
String p = "";
for(int f = 0; f < this.myArray.length; f++)
{
p += myArray[f];
}
return p.hashCode();
}
public String getValue()
{
String h = "";
for(int t = 0; t < this.myArray.length; t++)
{
h += myArray[t];
}
return h;
}
#Override
public boolean equals(Object jbo)
{
if(jbo == null)
{
return false;
}
if(!(jbo instanceof LargeInt))
{
return false;
}
LargeInt k =(LargeInt)jbo;
if(k.myArray.length != this.myArray.length)
{
return false;
}
for(int d = 0; d < this.myArray.length; d++)
{
if(k.myArray[d] != myArray[d])
{
return false;
}
}
return true;
}
#Override
public String toString()
{
String c = "";
for(int q = 0; q < this.myArray.length; q++)
{
c += myArray[q];
}
return "The LargeInt is: " + c;
}
}
HW7Methods File
import java.util.*;
import java.io.*;
public class HW7Methods
{
public static String readNum(Scanner kb)
{
String num = "";
System.out.print("Enter Your Large Int: ");
num = kb.nextLine();
return num;
}
public static void displayAscendingOrder(final LargeInt first, final LargeInt second, final LargeInt third)
{
String highestInt;
if(first.compareTo(second) >= 0 && first.compareTo(third) >= 0)
{
highestInt = first.getValue();
}
else if(second.compareTo(first) >= 0 && second.compareTo(third) >= 0)
{
highestInt = second.getValue();
}
else
{
highestInt = third.getValue();
}
String middleInt;
if(first.compareTo(second) >= 0 && first.compareTo(third) <= 0)
{
middleInt = first.getValue();
}
else if(second.compareTo(first) >= 0 && second.compareTo(third) <= 0)
{
middleInt = second.getValue();
}
else
{
middleInt = third.getValue();
}
String lowestInt;
if(first.compareTo(second) <= 0 && first.compareTo(third) <= 0)
{
lowestInt = first.getValue();
}
else if(second.compareTo(first) <= 0 && second.compareTo(third) <= 0)
{
lowestInt = second.getValue();
}
else
{
lowestInt = third.getValue();
}
System.out.println("The LargeInts in order are: " + lowestInt + ", " + middleInt + ", " + highestInt);
}
}
MyUtil file
package MyUtils;
import java.io.*;
import java.util.Scanner;
public class MyUtil
{
public static int menu(Scanner kb)
{
int userChoice;
System.out.println("1) Print First Int");
System.out.println("2) Print Second Int");
System.out.println("3) Add Different Int");
System.out.println("4) Check If Equal");
System.out.println("5) Add Large Ints");
System.out.println("6) Display In Ascending Order");
System.out.println("7) Compare Ints");
System.out.println("8) Quit");
kb = new Scanner(System.in);
System.out.print("Please Select Your Choice: ");
userChoice = kb.nextInt();
while(userChoice < 1 || userChoice > 8)
{
System.out.print("Invalid Menu Choice. Please Re-Enter: ");
userChoice = kb.nextInt();
}
return userChoice;
}
}
When I go to run this code, it prompts me for two Large Integers like it's supposed to. However, when I choose option 5 to add them, this is what I get:
Exception in thread "main" java.lang.NumberFormatException: For input string: "[I#55f96302"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at LargeInt.add(LargeInt.java:24)
at CSCD210HW7.main(CSCD210HW7.java:41)
I've never seen that type of error before. Can someone tell me what is going on?
For input string: "[I#55f96302
That is not a "proper" String you are trying to parse here.
This is what an int[] looks like when you call toString() on it.
String stringOne = myArray.toString();
Why do you do that? What is that supposed to do?
int r = Integer.parseInt(stringOne);
int e = Integer.parseInt(stringTwo);
int s = r + e;
From the looks of it, you try to handle "large" ints with your LargeInt class by somehow storing them in an array of ints. That's okay, BigInteger also works like that (more or less), but you cannot just do calculations by trying to convert back to int (after all those numbers are too big for int arithmetic to handle, even if you do the string parsing properly).

Categories