I created a code to generate a random credit card number and I'm using this method to return a credit card number based in the user input. For some reason I am having a problem returning a value. Help please.
public String getIssuerCode(String issuerSymbol) {
String creditCardNumber = null;
for (int i = 0; i < 15; i++) {
switch (issuerSymbol) {
case ISSUER_MASTER_CARD:
creditCardNumber = generateMasterCard();
break;
case ISSUER_AMER_EXPRESS:
creditCardNumber = generateAmericanExpress();
break;
case ISSUER_VISA:
creditCardNumber = generateVisa();
break;
// System.out.println("error");
default:
break;
}
}
return creditCardNumber;
}
You have a couple of things going on here.
First and foremost, you have a simple typo in your code, as #brycem in his answer already told you. Secondly, it is possible that, after the for-loop and switch statements, creditCardNumber hasn't been initialized. This means that no value has been assigned to it. Now this may be impossible to happen, but your compiler doesn't know that. Thus, a simple fix is to assign it to null in the beginning:
public String getIssuerCode(String issuerSymbol) {
String creditCardNumber = null;
for (int i = 0; i < 15; i++) {
switch (issuerSymbol) {
case ISSUER_MASTER_CARD :
creditCardNumber = generateMasterCard();
break;
case ISSUER_AMER_EXPRESS :
creditCardNumber = generateAmericanExpress();
break;
case ISSUER_VISA:
creditCardNumber = generateVisa();
break;
default:
break;
}
}
return creditCardNumber;
}
Edit:
From your comment below I drew the conclusion that the class that has this method also has the issuerNumber. In this case, you should definitely do this:
public String getIssuerCode() {
String creditCardNumber = null;
for (int i = 0; i < 15; i++) {
switch (this.getIssuerSymbol()) {
case ISSUER_MASTER_CARD :
creditCardNumber = generateMasterCard();
break;
case ISSUER_AMER_EXPRESS :
creditCardNumber = generateAmericanExpress();
break;
case ISSUER_VISA:
creditCardNumber = generateVisa();
break;
default:
break;
}
}
return creditCardNumber;
}
The problem in your case is that there is one path in your program that might return an uninitialized String. If "issuerSymbol" is none of the three cases, you will fall in your "default case", which don't initialize your creditCardNumber variable.
The solution is to give a default value to the variable creditCardNumber at line 2:
public String getIssuerCode(String issuerSymbol) {
String creditCardNumber = null;
...
}
OR update your default case
switch (issuerSymbol) {
case ISSUER_MASTER_CARD :
creditCradNumber = generateMasterCard();
break;
case ISSUER_AMER_EXPRESS :
creditCardNumber = generateAmericanExpress();
break;
case ISSUER_VISA:
creditCardNumber = generateVisa();
break;
default:
creditCardNumber = "000-000-000";
break;
}
Feel free to put any value as the default value. Personnally "null" is a good candidate as it shows immediately that something wrong happened, but it might make you crash later on if don't handle it correctly. Therefore a safer choice could be any String value, like "000-000-000".
Yeah, well. In case you didn't notice by now, you simply mispelled "card" and wrote "crad".
Concretely, you created a variable String creditCradNumber; <- Notice the "Crad" instead of "Card".
But you spelled it differently in the return statement return creditCardNumber; <- NOW it's Card.
That's most likely your problem. Take another look at your code now and be sure to check your variable's name spelling now so it remains the same every time you want to use it. :)
Cheers.
Edit: As shown in other answers, your code ALSO has the problem of not initializing the String creditCardNumber if none of the cases are met on your switch. Initializing it to null:
String creditCardNumber = null;
or using a default case on your switch:
default:
creditCardNumber="000-000-000";
break;
may solve the problem.
Okay, just to debug your "null", you should try to add more debug lines:
public String getIssuerCode(String issuerSymbol) {
String creditCardNumber = null;
System.out.println(issuerSymbol);
switch (issuerSymbol) {
case ISSUER_MASTER_CARD:
System.out.println("Card was of type: " + ISSUER_MASTER_CARD);
creditCardNumber = generateMasterCard();
break;
case ISSUER_AMER_EXPRESS:
System.out.println("Card was of type: " + ISSUER_AMER_EXPRESS);
creditCardNumber = generateAmericanExpress();
break;
case ISSUER_VISA:
System.out.println("Card was of type: " + ISSUER_VISA);
creditCardNumber = generateVisa();
break;
default:
System.out.println("Card is NOT one of the expected type!");
break;
}
}
System.out.println("Generated credit card number is : " + creditCardNumber);
return creditCardNumber;
}
If you have "null", then you must see "Card is NOT one of the expected type!". If not, this means that there is a problem in your function generatedAmericanExpress() and this is what returns null.
You've used a variable named "creditCradNumber" when setting in several instances rather than "creditCardNumber".
Related
public void operationOnClick(View view){
int operandOneValue = Integer.valueOf(operandOne.getText().toString());
int operandTwoValue = Integer.valueOf(operandTwo.getText().toString());
int resultValue = 0;
Button op = (Button)view;
String operation = op.getText().toString();
switch(operation){
// now i change the keyword 'return' with 'break'
// i got the problem.
case "+" : resultValue = operandOneValue+operandTwoValue;return;
case "-" : resultValue = operandOneValue-operandTwoValue;return;
case "*" : resultValue = operandOneValue*operandTwoValue;return;
case "/" : resultValue = operandOneValue/operandTwoValue;return;
}
result.setText(String.valueOf(resultValue));
}
The value operandOneValue+opearndTwoValue assigned to 'resultValue' is never used?I can't figure out the error?
In your switch statement, replace every return; with break; which is the signal to break out of the switch, but the rest of the code will run. When you write return within a void method, when its reached it means you are breaking out of the method itself so no code past it will be read. In this case, if your switch cases match, you will never reach the setText method.
Method's return type is void and you returned from inside case so statement below are inaccessible. Try like below.
String output="";
switch(operation) {
case "+":
output=(operand1+operand2).toString();
break;
case "-":
output=(operand1-operand2).toString();
break;
case "*":
output=(operand1*operand2).toString();
break;
case "/":
output=(operand1/operand2).toString();
break;
}
result.setText(output);
This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 4 years ago.
import java.util.*;
public class Lab04B {
public static String toMeters (int unitNumber) {
String value;
switch (unitNumber) {
case 1:
value = "Meter";
break;
case 2:
value = "Nautical mile";
break;
case 3:
value = "Furlong";
break;
case 4:
value = "Mil";
break;
case 5:
value = "Rod";
break;
case 6:
value = "Vershok";
break;
case 7:
value = "Sheppey";
break;
case 8:
return 1.702;
default:
return -1;
}
{
public static double fromMeters (int unitNumber)
{
switch (unitNumber)
{
case 1:
return 1;
case 2:
return 1/1852.0;
case 3:
return 1/201.168;
case 4:
return 1/0.0254;
case 5:
return 1/5.029;
case 6:
return 1/0.04445;
case 7:
return 1/1408.0;
case 8:
return 1/1.702;
default:
return -1;
}
{
public static String getUnitName (int unitNumber)
{
String value;
switch (unitNumber)
{
case 1:
value = "Meter";
case 2:
value = "Nautical mile";
case 3:
value = "Furlong";
case 4:
value = "Mil";
case 5:
value = "Rod";
case 6:
value = "Vershok";
case 7:
value = "Sheppey";
case 8:
value = "Smoot";
default:
value = "faulty input";
}
{
public static void main (String[] args)
Scanner input = new Scanner (System.in);
System.out.println("Converting Measurements");
System.out.println("By: Ashleigh Pacewicz");
System.out.println("1.\tMeter");
System.out.println("2.\tNautical Mile");
System.out.println("3.\tFurlong");
System.out.println("4.\tMil");
System.out.println("5.\tRod");
System.out.println("6.\tVershok");
System.out.println("7.\tSheppey");
System.out.println("8.\tSmoot");
System.out.println("From what unit would you like to convert? ");
int = input.nextInt();
System.out.println("To what unit would you like to convert? ");
int = input.nextInt();
System.out.print("What measurement would you like to convert? ");
double = input.nextDouble();
}
}
}
I am just learning how to code. I'm trying to write a program to convert meters but I keep receiving error on line 40 and line 63 and line 96. Error:
'.class' expected.
What am I doing wrong?
First of all
int = input.nextInt();
System.out.println("To what unit would you like to convert? ");
int = input.nextInt();
You didn't give them a name
and look at your braces
}
{
public static String getUnitName (int unitNumber)
{
It's the same at every method
it should be like this
public void methodName() {
}
but you're doing this
{
public void methodName()
{
and you forgot breaks;
1 more thing you should really use an IDE
I want to be honest. I do not know why you are getting this error...
I've just copied your code and compiled. After removing 2 to 3 braces and adding one, your code compiled without errors. I'm sure you are getting the error, you pasted into your question, from somewhere else.
You have to apply some fixes:
System.out.println("To what unit would you like to convert? ");
int NAME_YOUR_VARS = input.nextInt();
And in a few places you are placing open braces infront of method headers:
{
public static double fromMeters(int unitNumber){
Or you forgot to close method bodys:
public static String toMeters (int unitNumber) {
switch(unitNumber) {
/* case statements were cut out here*/
}
//<- Here you forgot a brace!
Keeping track of code blocks and brace placing is very important!
I do not why eclipse markes the switch-case statement with red squiggle, an says Syntax error on token "{", SwitchLabels expected after this token I tried both of the below posted code and i receive the same complain.
Code_1
switch (Test.h1.size()) {
int size = Test.h1.size();
case 1:
break;
case 2:
break;
}
Code_2
switch (Test.h1.size()) {
int size = Test.h1.size();
case size == 1:
break;
case size == 2:
for (int i=1; i<=Test.h1.size()-1; i++) {
for (int j=i+1; j<=Test.h1.size(); j++) {
System.out.println( Test.h1.get(i)+"+"+Test.h1.get(j)+"= "+((Test.h1.get(i))+(Test.h1.get(j))) );
}
}
break;
}
All your code needs to be in cases. Did you read the docs? http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Try this:
int size = Test.h1.size();
switch (size) {
case 1:
break;
case 2:
....;
}
To solve your problem in code 1 you only have to remove the line int size = Test.h1.size();.
For code 2 you should know, that in Java you cannot use boolean expressions in switch cases.
This program is supposed to read the values of the string input and return a result.
However, when I use
System.out.println(Arrays.toString(stack.toArray()));
to check what the stack looks like at the end, or even during the program, I noticed that the pop() method foe the stack doesn't seem to be removing the elements it's returning.
I'm probably doing something horribly wrong, but I haven't been able to figure it out.
I'd really appreciate any insight !
// Test example : (((1+1)+1)+1)
import java.util.*;
public class Task2
{
public static void main(String[] args) //run Start() method
{
System.out.print("Enter an expression, or press Enter to quit: ");
Stack<String> stack = new Stack<String>();
Scanner scanner = new Scanner(System.in);
String n = scanner.nextLine();
if(!n.isEmpty())
{
for(int i = 0 ; i < n.length() ; i++)
{
if(!(n.charAt(i) == ')'))
{
stack.push(n.charAt(i) + "");
}
else
{
int two = Integer.parseInt(stack.pop());
char op = (stack.pop()).charAt(0);
int one = Integer.parseInt(stack.pop());
switch(op)
{
case '+':{stack.push((one + two) + "");}
case '-':{stack.push((one - two) + "");}
case '*':{stack.push((one * two) + "");}
case '/':{stack.push((one / two) + "");}
}
}
}
}
else
{
System.out.print("\ngoodbye");
System.exit(0);
}
}
}
Sorry for the lack of comments, and thanks !
This is my first solution here, so be gentle :D. The issue was not with pop(), as pop was doing what it was supposed to. You forgot to add break points in your switch statement. It did every operation and added it to the stack giving it the illusion that pop was not working. I will leave the printing part to you. Cheers.
switch(op)
{
case '+':
stack.push((one + two) + "");
break;
case '-':
stack.push((one - two) + "");
break;
case '*':
stack.push((one * two) + "");
break;
case '/':
stack.push((one / two) + "");
break;
}
i have the following problem: i want to read in a String from the user, so far it works pretty well but everytime i press just "return" i get alway the following error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
at Shell.execute(Shell.java:20)
at Shell.main(Shell.java:55)
This would be the code:
private static void execute(BufferedReader stdin) throws IOException {
boolean quit = false;
Field test = new Field();
while (!quit) {
System.out.print("ch> ");
String input = stdin.readLine();
if (input == null) {
break;
}
String[] tokens = input.trim().split("\\s+");
tokens[0].toLowerCase();
char tmp = tokens[0].charAt(0);
switch (tmp) {
case 'n':
test.setPoints(null);
break;
case 'a':
test.add(new Point(Integer.parseInt(tokens[1]), Integer
.parseInt(tokens[2])));
break;
case 'r':
test.remove(new Point(Integer.parseInt(tokens[1]), Integer
.parseInt(tokens[2])));
break;
case 'p':
System.out.println(test);
break;
case 'c':
System.out.println(test.convexHull());
break;
case 'h':
System.out.println("");
break;
case 'q':
quit = true;
break;
default:
break;
}
}
}
Thanks for your help.
If you get an index out of bounds exception when accessing the 0th element, you string is probably empty. You need to add a check for this, checking for null is not enough.
By the way, when you write like this:
tokens[0].toLowerCase();
I highly suspect your tokens[0] remains unchanged. Since strings in java are immutable, toLowerCase will have to return a new string which only contains lower case character.
See whether your tokens array is populated with any strings after splitting because I think that is creating problem.
Your input String is empty if you pressed return change your code as follows to fix it.
while (!quit) {
System.out.print("ch> ");
String input = stdin.readLine();
if (input == null && input.length()<1) { //changed line!
break;
}
String[] tokens = input.trim().split("\\s+");
here is the problem
String input = stdin.readLine();
if (input == null) {
break;
}
here pressing "return" doesn't give you the null and your if condition fails.
code fails at below line
tokens[0].toLowerCase();
It is clear user input is empty string. Put empty string check before splitting it.
if (input == null && input.isEmpty()) {
break;
}