Java Debugging, syntax issues [duplicate] - java

This question already has answers here:
Why can't I do assignment outside a method?
(7 answers)
Closed 6 years ago.
I have a couple debug issues I cant figure out. I commented them out in the code below, if someone could please correct it AND explain why the errors happened, I would really appreciate it. I'm new to java, and this is one of the first few projects I'm working on
public class handleexceptions2 {
int sideA = -1;
int sideB = -1;
Scanner input = new Scanner(System.in){
do //Syntax Error on Token "do", delete this token
{
System.out.println("Enter your choice ( a/b/c/q ) : ");
char ch = in.nextChar();
switch(ch)
{
case 'a': sideA = in.nextDouble();
if(sideA<0)
System.out.println("Error! Please enter a valid number!");
break;
case 'b': sideB = in.nextDouble();
if(sideB<0)
System.out.println("Error! Please enter a valid number!");
break;
case 'c': if(sideA<0 || sideB<0)
System.out.println("Other two sides not yet given! please provide a and b first. ");
else
System.out.print("Side C(the hypotenuse) is: "+ Math.sqrt((sideA*sideA) + (sideB*sideB)));
break;
case 'q': break;
default : System.out.println(" Enter a valid choice! ");
}
while(ch!='q');
} //Multiple markers at this line
Syntax Error, insert "}" to complete class body
Syntax Error, insert ";" to complete FieldDecleration
//

// The Scanner class is found in java.util, so it needs to be imported.
import java.util.*;
// As per convention, classes should always start with an uppercase letter, and you should
// capitalize each word.
public class HandleExceptions2 {
// The main method will get called when you run the class.
public static void main(String[] args) {
// These need to be doubles, and not integers since you are reading doubles from the input.
double sideA = -1;
double sideB = -1;
// You had "{" at the end of this line, which would allow you to create an anonymous class
// extending Scanner, which was certainly not your intention.
Scanner input = new Scanner(System.in);
// 'ch' needs to be defined outside the loop since you are using it in your 'do while' loop
// condition.
char ch;
do {
System.out.println("Enter your choice ( a/b/c/q ) : ");
// Your scanner is called 'input' not 'in'. Also, nextChar() is not a method in the Scanner
// class, so perhaps you want to read the entire line and grab the first character?
ch = input.nextLine().charAt(0);
switch (ch) {
case 'a':
sideA = input.nextDouble();
// We want to finish reading this line (so that the next time we call nextLine() we don't
// just get an end-of-line character).
input.nextLine();
if (sideA < 0)
System.out.println("Error! Please enter a valid number!");
break;
case 'b':
sideB = input.nextDouble();
input.nextLine();
if (sideB < 0)
System.out.println("Error! Please enter a valid number!");
break;
case 'c':
if (sideA < 0 || sideB < 0)
System.out.println("Other two sides not yet given! please provide a and b first. ");
else
// You probably want to finish writing the line here (System.out.print() doesn't add a
// line break).
System.out.println("Side C(the hypotenuse) is: " + Math.sqrt((sideA*sideA) + (sideB*sideB)));
break;
case 'q': break;
default : System.out.println(" Enter a valid choice! ");
}
// The while loop condition needs to be placed right after the matching bracket after 'do'
} while (ch != 'q');
}
}

Put your code in a function for instance:
public class handleexceptions2 {
public static void main(String... args) {
...your code here...
}
}

Related

How do you limit input to "yes" "no"

If a user answers "yes" one of the 4 quotes print, randomly generate a number between 1 out of 4 and not print it, if a user answers "no" it prints "No quotes " and if it's neither it prints "Invalid", Should i use switch? if/else?
This is Java.
public static void main(String[] args) {
Scanner keyedInput = new Scanner(System.in);
String answer;
System.out.println("Do you want to be inspired? (Enter Yes/No)");
var Gen = Math.floor(Math.random() * 4 + 1);
answer = keyedInput.nextLine();
if (answer.equals("Yes")) {
System.out.println("Quote1");
}
else if (answer.equals("Yes")) {
System.out.println("Quote2");
}
else if (answer.equals("Yes")) {
System.out.println("Quote3");
}
else if (answer.equals("Yes")) {
System.out.println("Quote3");
}
if (answer.equals("No")) {
System.out.println("No quotes");
}
else {
System.out.println("Invalid");
}
}
This is a complex task: You want to ask the user yes/no, then if they answer neither 'yes' nor 'no', print something indicating that it's not valid and ask again.
So, make a method! And this method should loop - after all, it needs to keep doing the same thing, over and over again, until the user manages to provide a valid answer.
As a side-note, never use .nextLine(), it doesn't do what you think it does. Only use .next() if you want a string, .nextInt() if you want an int, etcetera. If you want whole lines of input (and you usually do), after making your scanner configure it to read lines at a time with scanner.useDelimiter("\\R");
public static boolean askBoolean(String prompt, Scanner scanner) {
while (true) {
System.out.print(prompt + " (yes/no): ");
String answer = scanner.next();
if (answer.equalsIgnoreCase("Yes")) return true;
if (answer.equalsIgnoreCase("No")) return false;
System.out.println("Please enter yes or no.");
}
}
Let's not use a switch, because equalsIgnoreCase sounds useful here.
and to use:
boolean wantsToBeInspired = askBoolean("Do you want to be inspired?", scanner);
if (wantsToBeInspired) {
showAQuote();
} else {
System.out.println("No quote for you");
}
I believe this is what you are trying to achieve:
int Gen = Math.floor(Math.random() * 4) + 1;
if(answer.equals("Yes")){
switch(Gen){
case 1: System.out.println("Quote 1"); break;
case 2: System.out.println("Quote 2"); break;
case 3: System.out.println("Quote 3"); break;
case 4: System.out.println("Quote 4"); break;
}
}else if(answer.equals("No")){
System.out.println("No quotes");
}else{
System.out.println("Invalid");
}

Make a loop with a-z input

I am a complete noob to Java, but I wish to make a program that takes an input from user, [A/a] - [C/c], [D/d] - [F/f], and so on, and then returns a value ([A/a-C/c = 1], [D/d-F/f = 2]....
If the input is not A-Z or a-z, returns a "Invalid input". (I think I can figure this one out myself).
I suppose I could make a "ToUpperCase" statement on the input, but I am not entirely sure how to do so.
I would prefer not to use any special databases.
Here is my code so far:
import java.util.Scanner;
public class TelefonTastatur {
public static void main(String[] args) {
String korrTall = "Korresponderer til tallet "; //Strings are in Norwegian, but I don't need help with those :-)
System.out.println("Dette programmet konverterer bokstav-input til korresponderende tall på et telefontastatur.");
System.out.println("Oppgi en bokstav (A-Z: "); //Asks user for A-Z input.
Scanner sc = new Scanner(System.in);
char c = sc.next().charAt(0); //Perhaps toUpperCase to lower number of switch cases?
switch (c) {
case ('A'-'C'): //Not sure how to make A-C and/or a-c. I could make an individual case for all inputs, but that would make a lot of code.
case ('a'-'c'):
System.out.print(korrTall + "2.");
break;
case (D/d - F/f):
case ():
System.out.print(korrTall + "3.");
break;
case (G/g - I/i):
case ():
System.out.print(korrTall + "4.");
break;
case (J/j - L/l):
case ():
System.out.print(korrTall + "5.");
break;
case (M/m - O/o):
case ():
System.out.print(korrTall + "6.");
break;
case (P/p - S/s):
case ():
System.out.print(korrTall + "7.");
break;
case (T/t - V/v):
case ():
System.out.print(korrTall + "8.");
break;
case (W/w - Z/z):
case ():
System.out.print(korrTall + "9.");
break;
case 'F':
case 'f':
System.out.print(korrTall + "0.");
break;
default:
System.out.println("Det du har tastet inn tilsvarer ikke noe tall på et telefontastatur.");
break;
}
}
}
If you want to read a single letter from the user you can use the readInput()provided in the code snippet.
Then, for example in your main(), you could ask for the user to input 2 letters and then you will provide him the result.
public static void main(String[] args) {
try{
char inputOne = readInput();
char inputTwo = readInput();
handle(inputOne,inputTwo);
}catch(Exception e){
System.out.println(e.getMessage());
}
}
static char readInput(){
System.out.println("Insert a character");
String input = Console.readLine();
if (input.length==0) {
char c = input.charAt(0);
if (Character.isLetter(c)) {
return c;
}
}
throw new Exception("Invalid input!");
}
static void handle(char a, char b){
// your logic to handle the input of the user
}
Your question is not clear at all but i try to help you. Next time post what u tried.
This simple code will help you, this can be improved so let's do this :D
Scanner scanner = new Scanner(System.in);
System.out.println("Insert first char");
String firstChar = scanner.next().toUpperCase();
if (firstChar.length() != 1 || (firstChar.toCharArray()[0] < 65 || firstChar.toCharArray()[0] > 90)) {
System.out.println("Please, insert one single character [a-z/A-Z]");
return;
}
System.out.println("Insert second char");
String secondChar = scanner.next().toUpperCase();
if (secondChar.length() != 1 || (secondChar.toCharArray()[0] < 65 || firstChar.toCharArray()[0] > 90)) {
System.out.println("Please, insert one single character");
return;
}
System.out.println(firstChar + " - " + secondChar + " = " + Math.abs(firstChar.toCharArray()[0] - secondChar.toCharArray()[0]));
Note that You can create methods to do repetitive action. In this simple example you can create a method that check if what you just read from keyboard is a single character.
One other improve you can do is handle when user insert something wrong.
Let's try to code :D
Bye
You're going to have to use the Scanner class to accomplish user input.
import java.util.Scanner;
Then create a variable that takes in the keyboard input.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a letter: ");
String text = keyboard.nextLine();
Create a method that returns a number given a character.
a-z is equal to 97-122 in Java, and A-Z is equal to 65-90.
public int toNum(String text) {
//Ensure that the text is only 1 character long.
if(text.length() > 1) return -1;
//Convert the one-character String to type char.
char letter = text.charAt(0);
//Convert char to its equivalent number value.
int rawNum = letter;
int newNum;
//Convert the number to a value 0-25.
if(rawNum >= 'a' && rawNum <= 'z') {
newNum = rawNum - 'a';
} else if(rawNum >= 'A' && rawNum <= 'Z') {
newNum = rawNum - 'A';
} else {
//None of the characters were letters A-Z.
System.out.println("Invalid input");
return -1;
}
//If {a,b,c} are 1 and {d,e,f} are 2, then {0,1,2} -> 1 and {3,4,5} -> 2
//Take the floor of the new number divided by 3.
int toReturn = Math.floor(newNum / 3.0) + 1;
return toReturn;
}
Now just call your method with the user input.
toNum(text);
You can print the returned value of the user input as well.
System.out.println(toNum(text));

Java Switch nested for loop will duplicate

I am new to Java and am having trouble with this particular for loop. Everytime I run the loop and enter a number that is not 1 or 2, the loop displays: "Please choose a correct option". What could be the cause of this?
public class Kbin {
public static void main (String args[]) throws java.io.IOException {
int option;
int i = 0;
System.out.println("What would you like help with?");
System.out.println("\t1. If statement");
System.out.println("\t2. Switch statement");
option = (char) System.in.read();
// loop:
for(i = 0; option != 1 & option != 2; i ++){
System.out.println("What would you like help with?");
System.out.println("\t1. If statement");
System.out.println("\t2. Switch statement");
option = (char) System.in.read();
switch(option){
case '1':
System.out.println("here is how you do an if statement");
i += 1;
break loop;
case '2':
System.out.println("Here is how you do a switch statement");
i += 1;
break loop;
default:
System.out.println("Please choose a correct option.");
continue;
}
}
}
}
Option variable is not getting the correct value that u expect it to hold.
As by seeing your code the user would enter either 1 or 2, then you are trying to convert it into char thats where the problem is. Try to take int as input
Scanner input = new Scanner(System.in);
option = input.nextInt();

How would I go about creating input commands to execute different part of my code? - Java

I have created a basic java program that determines the hypotenuse of a triangle. Originally, the program would ask for side A, then side B, and automatically calculate the hypotenuse.
I want to create a input command list that will allow the user to type "a" in when giving the A side value, type "b" when giving the B side value, and then type "c" to calculate the hypotenuse, or "q" to exit the program.
Instead of forcing the user to put in side A first, I want them to be able to put in either side at there will. However, if the user types "c" and either the A or B value is missing (or both) I would like an error message and have the user correct it.
So far I have
import java.util.InputMismatchException;
import java.util.Scanner;
public class handleExceptions1 {
public static void main(String[] args) {
Scanner initial = new Scanner(System.in);
System.out.println(" Type 'a' to enter the value for side A.\n Type 'b' to enter the value for side B.\n Type 'c' to calculate the hypotenuse.\n Or type 'q' to exit");
String inputselected = initial.next();
boolean repeat = true;
double _sideA = 0;
while (repeat) {
try {
Scanner input = new Scanner(System.in);
System.out.print("Please enter side A, this may not be 0: ");
_sideA = input.nextDouble();
if (_sideA > 0){
repeat = false;
}
} catch (InputMismatchException e) {
System.out.print("Error! Please enter a valid number!");
}
}
boolean repeat2= true;
double _sideB = 0;
while (repeat2){
try {
Scanner input = new Scanner(System.in);
System.out.print("Please enter side B, this may not be 0: ");
_sideB = input.nextDouble();
if (_sideB > 0){
repeat2= false;
}
} catch (InputMismatchException e) {
System.out.print("Error! Please enter a valid number!");
}
}
double hypotenuse = Math.sqrt((_sideA*_sideA) + (_sideB*_sideB));
System.out.print("Side C(the hypotenuse) is: "+ hypotenuse);
}
}
My logic is to put something after "String inputselected = ..." but I'm not sure what. If anyone can help me, it would be greatly appreciated !
sideA = -1;
sideB = -1;
Scanner input = new Scanner(System.in);
do
{
System.out.println("Enter your choice ( a/b/c/q ) : ");
char ch = in.nextChar();
switch(ch)
{
case 'a': sideA = in.nextDouble();
if(sideA<0)
System.out.println("Error! Please enter a valid number!");
break;
case 'b': sideB = in.nextDouble();
if(sideB<0)
System.out.println("Error! Please enter a valid number!");
break;
case 'c': if(sideA<0 || sideB<0)
System.out.println("Other two sides not yet given! please provide a and b first. ");
else
System.out.print("Side C(the hypotenuse) is: "+ Math.sqrt((_sideA*_sideA) + (_sideB*_sideB)););
break;
case 'q': break;
default : System.out.println(" Enter a valid choice! ");
}
}while(ch!='q');

How to make this program go back to prompt until the user exits

While writing code for my program I thought of testing the first part before moving on and writing the operations. Although I have the user input, but I want the options to be displayed after each operation (add, deltete..) is done untill the users presses exit. How do I modify my code to do it?
import java.io.*;
import java.util.*;
public class Records {
public static void main(String[] args) {
int choice;
do {
System.out.println("1.Add \n 2.Delete \n 3.Update \n 4.Show \n Exit");
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//int choice;
System.out.println("Enter your Choice : ");
Scanner sc = new Scanner(System.in);
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("Getting ready to Add a Record ");
//set();
break;
case 2:
System.out.println("Getting ready to Delete a Record ");
//delete();
break;
case 3:
System.out.println("Getting ready to Update a Record ");
//update();
break;
case 4:
System.out.println("Here is your record ");
//display();
break;
case 5:
System.out.println("Out we go.");
System.exit(0);
//exit();
break;
default:
System.out.println("Try again");
break;
}
} while ( choice > 5 || choice < 1 );
}
}
Simply change your while condition to:
} while ( choice > 0 && choice < 5 );
First make sure your scanner really has an int, use sc.hasNextInt() to validate the user entered a number. To end the do/while loop at "5.Exit", just have it like do{...}while(choice!=5). Code below is not tested.
import java.io.*;
import java.util.*;
public class Records {
public static void main(String[] args) {
int choice;
do {
System.out.println("1.Add \n 2.Delete \n 3.Update \n 4.Show \n 5.Exit");
System.out.println("Enter your Choice : ");
choice = -1;
Scanner sc = new Scanner(System.in);
// validate the next thing in your scanner is an int
// otherwise, sc.nextInt() might cause an exception
if (sc.hasNextInt()){
choice = sc.nextInt();
switch (choice) {
case 1: System.out.println("Getting ready to Add a Record ");
// ...
break;
case 2: System.out.println("Getting ready to Delete a Record ");
// ...
break;
case 3: System.out.println("Getting ready to Update a Record ");
// ...
break;
case 4: System.out.println("Here is your record ");
// ...
break;
case 5: System.out.println("Out we go.");
// skip System.exit(0), your main method ends
// automatically when you leave your do/while loop
break;
default: System.out.println("Try again");
break;
}
}
// if choice == 5 it ends, otherwise, starts over...
} while ( choice != 5 );
}
}
Although I have the user input, but I want the options to be displayed
after each operation (add, deltete..) is done untill the users presses
exit.
You can set int flag=0; and when user selects exit option set flag to 1 to tell loop to exit.As of now you are already breaking out for number > 5 or < 1 in default case so no need to put that condition in while.
int flag=0;//Declare outside the loop
do{
...
case 5: System.out.println("Out we go.");
flag=1;//Set flag to 1 if user enters 5
break;
...
} while ( flag!=1 );//Exit the loop when flag==1
//Or directly while ( choice!=5 );
Serious EDIT
As Java Programmer I should probably suggest you to use boolean primitive type for flagging.
boolean flag=true;//Declare outside the loop
do{
...
case 5: System.out.println("Out we go.");
flag=false;//Set flag to 1 if user enters 5
break;
...
} while (flag);//Exit the loop when flag==false
One More thing:
Surround code with try-catch to leave out invalid inputs and prompt again for input.
Most of the times it's not recommended to swallow the Exception.
do{
try{
....//Your Switch case
}catch(InputMismatchException e){}
} while (choice !=5);//But remove System.exti(0); from your switch statement
Simply make your while loop as:
} while ( choice!=0 );(The Wrong one)
Correction:
} while(choice!=0 && choice<=5)

Categories

Resources