I have to keep inputting x and y coordinates, until the user inputs "stop". However, I don't understand how to parse the input from String to int, as whenever I do, I get back errors.
public class Demo2 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
while (true) {
System.out.println("Enter x:");
String x = kb.nextLine();
if (x.equals("stop")) {
System.out.println("Stop");
break;
}
System.out.println("Enter y:");
String y = kb.nextLine();
if (y.equals("stop")) {
System.out.println("Stop"); }
break;
}
}
}
}
To Parse integer from String you can use this code snippet.
try{
int xx = Integer.parseInt(x);
int yy = Integer.parseInt(y);
//Do whatever want
}catch(NumberFormatException e){
System.out.println("Error please input integer.");
}
Nice way to do this in my opinion is to always read the input as a string and then test if it can be converted to an integer.
import java.util.Scanner;
public class Demo2 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
while (true) {
String input;
int x = 0;
int y = 0;
System.out.println("Enter x:");
input = kb.nextLine();
if (input.equalsIgnoreCase("STOP")) {
System.out.println("Stop");
break;
}
try {
x = Integer.parseInt(input);
System.out.println(x);
} catch (NumberFormatException e) {
System.out.println("No valid number");
}
}
}
}
With
String variablename = Integer.toString(x);
Related
How can I use any alternative to 'goto' in java?
I tried using break label. But since I am not breaking out of any loop, it is giving undefined label error.
import java.io.*;
class $08_02_Total_Avg_Marks
{
public static void main(String args[]) throws IOException
{
//declare and initialize variables
int subNo = 0, totalMarks = 0;
float avg = 0.0F;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
label1:
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
//goto label1
}
int[] marksArray = new int[subNo];
for(int i=0; i<marksArray.length; i++)
{label2:
System.out.println("Enter marks for subject " + (i+1));
try
{
marksArray[i] = Integer.parseInt(br.readLine().trim());
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
//goto label2
}
}
}
}
I was terminating the program on invalid input. But I need to execute the same lines on invalid input.
Rather than wanting to go to a specific point explicitly, wrap the bit you might want to repeat in a loop. If you don't want to execute the loop again, break.
For the first one:
while (true) {
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
break;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
// Nothing required to continue loop.
}
}
For the second one, wrap the loop body in loop:
for(int i=0; i<marksArray.length; i++)
{
while (true) {
System.out.println("Enter marks for subject " + (i+1));
try
{
marksArray[i] = Integer.parseInt(br.readLine().trim());
break;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
}
}
}
Or, probably better, write a method wrapping this loop:
int getInt(BufferedReader br) throws IOException {
while (true) {
try
{
return Integer.parseInt(br.readLine().trim());
} catch(NumberFormatException e) {
System.out.println("Please enter a whole number.");
}
}
}
and then call this method:
System.out.println("Enter no. of subjects");
int subNo = getInt(br);
for(int i=0; i<marksArray.length; i++) {
System.out.println("Enter marks for subject " + (i+1));
marksArray[i] = getInt(br);
}
This code snippet will loop until a correct number is inserted, in this example (it solves your first goto problem)
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean noNumberEntered; //Default on false
System.out.println("Enter no. of subjects");
//TODO: check if input is integer
while(!noNumberEntered){
try
{
subNo = Integer.parseInt(br.readLine().trim());
noNumberEntered = true;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
}
}
I have reformatted your code a little bit. My basic idea was: All of the goto statements can be written in equivalent loops. The first one has now been made with a while loop, which terminates ones there comes NO exception. As for the second label, that has been done with the same mechanism (so a while-loop), however, with a label that can be exited/terminated with a "break + nameOfYourLable" - statement.
import java.io.*;
class $08_02_Total_Avg_Marks
{
public static void main(String args[]) throws IOException
{
//declare and initialize variables
int subNo = 0, totalMarks = 0;
float avg = 0.0F;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean goToLabel1 = true;
while (goToLabel1) {
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
goToLabel1 = false; //parsing succeeded, no need to jump to label1
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
//goto label1
}
}
int[] marksArray = new int[subNo];
for(int i=0; i<marksArray.length; i++)
{
label2: while (true) {
System.out.println("Enter marks for subject " + (i+1));
try
{
marksArray[i] = Integer.parseInt(br.readLine().trim());
break label2;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
}
}
}
}
}
You can use a do while loop and a boolean instead, like that :
class $08_02_Total_Avg_Marks
{
public static void main(String args[]) throws IOException
{
//declare and initialize variables
int subNo = 0, totalMarks = 0;
float avg = 0.0F;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean goodEntry = true;
do {
goodEntry = true;
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
goodEntry = false;
}
} while(!goodEntry);
}
You can do the same with your second goto.
There are many ways to do that (with while loop and a boolean, with breaks...), but loops are better then goto.
Hy, I wrote this piece of code where I'm asking the user to input a number:
public static double[] getscores()
{
int numscores=8;
double score[] = new double[numscores];
for (int a=0;a<numscores;a++)
{
Scanner ip=new Scanner(System.in);
System.out.println("Enter a score");
score[a]=ip.nextDouble();
}
return score;
}
In the eventuality where the user accidentally enters a String, how am I supposed to tell him to input a number without making the program shut down? Thanks You
You should catch the exception thrown when the user doesn't input a double, ask the user to try again, and keep looping there until the user inputs a double. Alternatively, you can use while(true) and a break statement instea of a do { ... } while. Perhaps that is a bit shorter, but this is more readable.
Use a BufferedReader instead, because Scanner does not consume the input if it fails to parse it, so you'll get stuck in an infinite loop.
public static double[] getScores() throws IOException {
final int NUM_SCORES = 8;
double[] score = new double[NUM_SCORES];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < NUM_SCORES; i++) {
System.out.println("Enter a score:");
boolean isDouble = false;
do {
try {
score[i] = Double.parseDouble(br.readLine());
isDouble = true;
} catch (NumberFormatException e) {
System.out.println("You didn't enter a double. Please try again!");
}
} while (!isDouble);
}
br.close();
return score;
}
The user is always entering a String; Scanner#nextDouble() is a convenience method to interpret String input as a double.
Write a method that keeps reading input until a double is entered:
static double readDouble(Scanner scanner) {
double score;
while (true) {
System.out.println("Enter a score");
String input = scanner.nextLine();
try {
score = Double.parseDouble(input);
break;
} catch (NumberFormatException e) {
System.out.println("'" + input + "' is not a valid score");
}
}
return score;
}
then call it from your loop:
score[a] = readDouble(ip);
A quick but "dirty" solution would be by using try-catch:
public static double[] getscores() {
int numscores = 8;
double score[] = new double[numscores];
for (int a = 0; a < numscores; a++) {
Scanner ip = new Scanner(System.in);
System.out.println("Enter a score");
try{
score[a] = ip.nextDouble();
} catch(InputMismatchException ime) {
System.out.println("Wrong input");
a--;
}
}
return score;
}
my teacher asked us to create an additive prime program for my computer science class. I have created all my void methods, and believe to have all the math logic figured out. However, when I try to pass arguments into the instances of my methods within my main method, It gives me an error saying:
it can not find the variable in this case variable 'x'
package additiveprimes;
import java.util.Arrays;
import java.util.Scanner;
/**
*
* #author talarik048
*/
public class AdditivePrimes {
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
additivePrime.userInput(x);
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
public void userInput(String x){
Scanner sc = new Scanner(System.in);
try{
System.out.println("Please enter a number: ");
x = sc.nextLine();
} catch(NumberFormatException e){
System.out.println("Error, try again: ");
x = sc.nextLine();
}
}
public void isPrime(String x){
this.userInput(x);
boolean prime = true;
int y = Integer.parseInt(x);
for(int i = 0; i < y; i++){
if(y % i == 0){
prime = false;
break;
}
if(prime){
System.out.println("Your number is prime...");
} else {
System.out.println("Your number is not prime...");
}
}
}
public void numArray(String x){
this.userInput(x);
String[] strArray = x.split("\\s+");
boolean prime = true;
int[] numbArray = new int[strArray.length];
for(int j = 0; j < strArray.length; j++){
try{
numbArray[j] = Integer.parseInt(strArray[j]);
} catch(NumberFormatException e){
System.out.println("ERROR");
}
for(int i = 0; i < numbArray.length; i++){
int sum = (Arrays.stream(numbArray).sum());
if(sum % i == 0){
prime = false;
break;
}
if(prime){
System.out.println("Your number is an additive prime...");
} else {
System.out.println("Your number is not an additive prime...");
}
}
}
}
}
I think you wanted to RETURN a value from userInput:
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
String x = additivePrime.userInput();
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
public String userInput(){
Scanner sc = new Scanner(System.in);
String x = null;
try{
System.out.println("Please enter a number: ");
x = sc.nextLine();
} catch(Exception e){// see OH GOD SPIDERS comment
System.out.println("Error, try again: ");
x = sc.nextLine();//this is not a good way for a retry
}
return x;
}
Alternatively you could make x a field.
Your methods accept a string as an argument, but you have not passed any. You need to initialize x in main.
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
String x= "55";
additivePrime.userInput(x);
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
Note
Although the above code fixes your current issue. It doesn't seem to be the correct way to use this class. You should probably be calling .userInput() method and getting the userInput then passing it to your other methods.
You could probably change your overall class to
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
String x = additivePrime.userInput();
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
public String userInput(){
Scanner sc = new Scanner(System.in);
String x = null;
try{
System.out.println("Please enter a number: ");
x = sc.nextLine();
} catch(NumberFormatException e){
System.out.println("Error, try again: ");
x = sc.nextLine();
}
return x;
}
You have not defined x as anything before using it. Try defining x. In this case since your arguments are strings, I recommend...
String x = new String();
how can i get the following code to repeat input() until a numeric is entered and at the same time tell the user what type of of variable was entered,be it string,double or integer and if conditions are met prints out a success message?
package returnin;
import java.util.*;
public class trycatch {
public static void main(String[]args){
String chck=input();
String passed =check(chck);
System.out.println("If you see this message it means that you passed the test");
}
static String input(){
Scanner sc= new Scanner(System.in);
System.out.println("Enter a value");
String var=sc.nextLine();
return var;
}
static String check(String a){
double d = Double.valueOf(a);
if (d==(int)d){
System.out.println( "integer "+(int) d);
}
else {
System.out.println(" double "+d);
}
return a;
}
}
Here's a commented example:
package returnin;
import java.util.*;
public class trycatch {
public static void main(String[] args) {
// Don't recreate Scanner inside input method.
Scanner sc = new Scanner(System.in);
// Read once
String chck = input(sc);
// Loop until check is okay
while (!check(chck)) {
// read next
chck = input(sc);
}
System.out.println("If you see this message it means that you passed the test");
}
static String input(Scanner sc) {
System.out.println("Enter a value");
return sc.nextLine();
}
static boolean check(String a) {
try {
// Try parsing as an Integer
Integer.parseInt(a);
System.out.println("You entered an Integer");
return true;
} catch (NumberFormatException nfe) {
// Not an Integer
}
try {
// Try parsing as a long
Long.parseLong(a);
System.out.println("You entered a Long");
return true;
} catch (NumberFormatException nfe) {
// Not an Integer
}
try {
// Try parsing as a double
Double.parseDouble(a);
System.out.println("You entered a Double");
return true;
} catch (NumberFormatException nfe) {
// Not a Double
}
System.out.println("You entered a String.");
return false;
}
}
Alright so I am an intro student in a programming class and I am trying to test a catch statement of a NFE. I don't know how to format the code properly, but here it is.
import java.util.Scanner;
public class Geo {
public static void main(String[] args) {
try {
Scanner inp = new Scanner(System.in);
System.out.print("Name?");
String name = inp.nextLine();
System.out.print("Number?");
double num = inp.nextDouble();
System.out.print("Integer?");
int num2 = inp.nextInt();
} catch(NumberFormatException e) {
System.out.println("Usage error");
}
System.out.println(name);
System.out.println(num);
System.out.println(num2);
}
}
It keeps saying the variables, name, num, and num2 are undefined. What am I doing wrong here, because I was looking back at an old lab and that is exactly how I had done it before. Any hints?
Now I fixed it so the code looks like this
public static void main(String[] args) {
try {
Scanner inp = new Scanner(System.in);
System.out.print("Name?");
String name = inp.nextLine();
System.out.print("Number?");
double num = inp.nextDouble();
System.out.print("Integer?");
int num2 = inp.nextInt();
System.out.println(name);
System.out.println(num);
System.out.println(num2);
} catch(NumberFormatException e) {
System.out.println("Usage error");
}
}
but the catch isnt running. How does that get fixed. Like I want it run the try completely, but if something is wrong it keeps running, then out of try, then catches the issue.
You must initial variables on top of try/catch.
public static void main(String[] args) {
String name = null;
double num = 0;
int num2 = 0;
try {
Scanner inp = new Scanner(System.in);
System.out.print("Name?");
name = inp.nextLine();
System.out.print("Number?");
num = inp.nextDouble();
System.out.print("Integer?");
num2 = inp.nextInt();
} catch (Exception e) {
System.out.println("Usage error");
}
System.out.println(name);
System.out.println(num);
System.out.println(num2);
}
or
public static void main(String[] args) {
try {
Scanner inp = new Scanner(System.in);
System.out.print("Name?");
String name = inp.nextLine();
System.out.print("Number?");
double num = inp.nextDouble();
System.out.print("Integer?");
int num2 = inp.nextInt();
System.out.println(name);
System.out.println(num);
System.out.println(num2);
} catch (Exception e) {
System.out.println("Usage error");
}
}
The variables you are referring to are defined in the try block and are therefore visible only in it, while you are trying to read them outside of the try block.
You can either do the printing in the try block, or define the variables in main function.