I'm a relatively new student learning Java programming, but I'd like to ask for some help. The error I'm receiving in my code is stating "variable romanNumeral might not have been initialised."
The intent for this program is for a user to enter a number from 1-39 and then have the appropriate roman numeral value displayed to the user via a dialog box. The code is not complete yet, as I've yet to find a solution to this problem due to the application not letting me compile my code.
Here is the code:
public class exercise4 extends Actor
{
int userNum;
public void act()
{
intInput(userNum);
}
public String intInput(int userNum)
{
String userInput;
String romanNumeral;
userInput = JOptionPane.showInputDialog("Please enter a number to be converted into Roman Numerals.");
userNum = Integer.parseInt(userInput);
switch(userNum)
{
case 1: romanNumeral = "I";
break;
case 2: romanNumeral = "II";
break;
case 3: romanNumeral = "III";
break;
case 4: romanNumeral = "IV";
break;
case 5: romanNumeral = "V";
break;
case 6: romanNumeral = "VI";
break;
case 7: romanNumeral = "VII";
break;
case 8: romanNumeral = "VIII";
break;
case 9: romanNumeral = "IX";
break;
case 10: romanNumeral = "X";
break;
case 11: romanNumeral = "XI";
break;
case 12: romanNumeral = "XII";
break;
case 13: romanNumeral = "XIII";
break;
case 14: romanNumeral = "XIV";
break;
case 15: romanNumeral = "XV";
break;
case 16: romanNumeral = "XVI";
break;
case 17: romanNumeral = "XVII";
break;
case 18: romanNumeral = "XVIII";
break;
case 19: romanNumeral = "XIX";
break;
case 20: romanNumeral = "XX";
break;
case 21: romanNumeral = "XXI";
break;
case 22: romanNumeral = "XXII";
break;
case 23: romanNumeral = "XXIII";
break;
case 24: romanNumeral = "XXIV";
break;
case 25: romanNumeral = "XXV";
break;
case 26: romanNumeral = "XXVI";
break;
case 27: romanNumeral = "XXVII";
break;
case 28: romanNumeral = "XXVIII";
break;
case 29: romanNumeral = "XXIX";
break;
case 30: romanNumeral = "XXX";
break;
case 31: romanNumeral = "XXXI";
break;
case 32: romanNumeral = "XXXII";
break;
case 33: romanNumeral = "XXXIII";
break;
case 34: romanNumeral = "XXXIV";
break;
case 35: romanNumeral = "XXXV";
break;
case 36: romanNumeral = "XXXVI";
break;
case 37: romanNumeral = "XXXVII";
break;
case 38: romanNumeral = "XXXVIII";
break;
case 39: romanNumeral = "XXXIX";
break;
}
return romanNumeral;
}
}
Consider how the code would behave if userNum has a value of 40. The switch statement doesn't have a case that matches such a value, so it would do nothing. Which is what the compiler is complaining about: the variable romanNumeral is not initialized when it's declared, and might not be even after the switch - thus: "variable romanNumeral might not have been initialised."
Two simple fixes: (A) initialize at declaration, e.g. String romanNumeral = "?", or (B) add a default part to the switch, as:
switch(userNum)
{
// other cases first
default: romanNumeral = "?";
}
use default in your switch case. in java you must have initialize a variable before using it. in your code if there is a value where no case matches then the variable will not be initialized.
Add in a default case to your switch statement setting it to some error value. You are getting that warning because it is possible your switch matches none of that and romanNumeral will never get set before it's returned.
String romanNumeral makes a reference to a memory location, but doesn't initialize it (doesn't give it a value). Because you can provide a value of usernum that doesn't cause a value to be set for romanNumeral, you're getting an error. To avoid this, you can add a default case.
In Java, variables defined in some method are not automatically initialized.
Here you have two options:
1. Initialize it using
String romanNumeral = null (or something);
2. Use default in switch
default:
romanNumeral = null (or something);
The error just means that the variable still has no memory allocated in it. so, what you will do to remove the error is just to give it an initial value.This will do :
String romanNumeral = "";
It is important to initialize the variable, object instances or any data structure you use. Sometimes it gives the null error but sometimes it does not even give an error and can give wrong values.
Your question have been answered above but I would like to suggest a modification. Following this table, you can make a HashMap of the roman numbers:
Decimal value (v) Roman numeral (n)
1 I
4 IV
5 V
9 IX
10 X
40 XL
50 L
90 XC
100 C
400 CD
500 D
900 CM
1000 M
Using the hashmap you can calculate the roman number for particular integer.Check the code just to give you an idea to get started:
public static void main(String []args){
int c = 39;int temp =0;
String roman = "";
if(c<40 && C>10)
{
temp = c/10;
c = c%10;
for(int i=0;i<temp;i++)
{
roman = roman+map.get(10);
}
}
if(c<10 && c>5)
{
if(c==9)
{
roman = roman+map.get(9);
}else{
temp = c/5;
c = c%5;
if(temp==1)
roamn += map.get(5);
for(int i=0;i<c;i++)
{
roman = roman+map.get(1);
}
//again you will have to check a case for four the way I did for 9
}
}
}
System.out.println(roman);
}
Related
I very new beginner in Java
Please help!
I need to declare "chk" in order to let switch know where to go.
How can I declare in something like this in order to let the switch know I need to check all 4 output and display them accordingly, not just output 1:
CheckBox chk = (CheckBox) findViewById(R.id.chk1);
switch (chk.getId()) {
case R.id.chk1:
findViewById(R.id.output1).setVisibility(visible);
break;
case R.id.chk2:
findViewById(R.id.output2).setVisibility(visible);
break;
case R.id.chk3:
findViewById(R.id.output3).setVisibility(visible);
break;
case R.id.chk4:
findViewById(R.id.output4).setVisibility(visible);
break;
}
The switch Statement
Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).
The following code example, SwitchDemo, declares an int named month whose value represents a month. The code displays the name of the month, based on the value of month, using the switch statement.
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
I am trying to do the following for a Java switch method with a series of JUnit Asserts but am stuck on using "less than" and "greater than" for two cases (see string/int error below), and am not sure how to use the ">" and "<" in my cases.
Here is the exercise followed by my code, followed by the error.
/*
Create a method which uses a switch statement to return a String representing the int passed in as a parameter to the method:
• given 1 return "One"
• given 2 return "Two"
• given 3 return "Three"
• given 4 return "Four"
• given an integer > 4, return "Too big"
• given an integer < 1, return "Too small"
*/
#Test
public void switchIntExample() {
assertEquals("One", stringRepInt(1));
assertEquals("Two", stringRepInt(2));
assertEquals("Three", stringRepInt(3));
assertEquals("Four", stringRepInt(4));
assertEquals("Too big.", stringRepInt(>4));
// assertEquals("Too small.", stringRepInt(<4));
}
//Switch statement for above:
public String stringRepInt(int numberSize) {
String numVar = null;
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
//TODO: question on how to do LESS THAN and GREATER THAN:
// error line:
case (numVar > 4):
numVar = "Too big.";
break;
default:
break;
}
System.out.println(numVar);
return numVar;
}
ERROR:
Error:(293, 27) java: bad operand types for binary operator '>'
first type: java.lang.String
second type: int
case statements only support constant expressions (you cannot do less than, or greater than, in a case and you can't test numVar - the String - with less than). You can use an if and something like
public String stringRepInt(int numberSize) {
String numVar = null;
if (numberSize > 4) {
numVar = "Too big.";
} else {
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
default:
break;
}
System.out.println(numVar);
return numVar;
}
You should add it to the default section, so like this:
default:
numVar = "Too Big";
break;
The purpose of the default section is to deal with all cases not dealt with by the switch cases. You should be taking advantage of that (as #GreenMatt and #FredK mentioned in comments) by putting the 'if checks' in the default section, as follows:
public String stringRepInt(int numberSize) {
String numVar = null;
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
default:
if(numberSize > 4)
numVar = "Too big";
break;
}
System.out.println(numVar);
return numVar;
}
Further, you could add else if (numberSize < 1) numVar = "Too small"; under the if statement if you want to check for number's smallest than one. This is also important because it prevents your method from returning null. (Which currently happens if the user enters a value less than 1)
The resulting code is as follows:
public String stringRepInt(int numberSize) {
String numVar = null;
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
default:
if(numberSize > 4)
numVar = "Too big";
else
numVar = "Too small";
break;
}
System.out.println(numVar);
return numVar;
}
In the error line you are comparing String and int.
error line: case (numVar > 4): numVar = "Too big."; break;
you have declared numVar as String and comparing that with int value 4. Please correct that or I think you are trying to compare numberSize with value 4. Convert that String to int and compare it.
Sonar gives a major violation error ("Cyclomatic Complexity") for the following code. Following method is used to get the date in a special format, e.g. 14-02-3 (Year-month-weekid).
How can I overcome this violation?
private String finalDateForProject;
public String getFinalDateForProject() {
return finalDateForProject;
}
public void setFinalDateForProject(Integer year,Integer month, Integer weekId) {
String projectMonth;
switch (month) {
case 0: projectMonth = "01";
break;
case 1: projectMonth = "02";
break;
case 2: projectMonth = "03";
break;
case 3: projectMonth = "04";
break;
case 4: projectMonth = "05";
break;
case 5: projectMonth = "06";
break;
case 6: projectMonth = "07";
break;
case 7: projectMonth = "08";
break;
case 8: projectMonth = "09";
break;
case 9: projectMonth = "10";
break;
case 10: projectMonth = "11";
break;
case 11: projectMonth = "12";
break;
default: projectMonth = " ";
break;
}
String yearEdited = year.toString();
yearEdited = yearEdited.replace("20", "");
String projectTrendDate = yearEdited +"-"+projectMonth+"-W"+weekId.toString();
this.finalDateForProject =projectTrendDate;
}
One way to reduce cyclomatic complexity that I see is to replace the switch statement. Just create an array or HashMap that will map month index to number;
public void setFinalDateForProject(Integer year,Integer month, Integer weekId) {
String[] months = new String[] {"01", "02", "03", "04", "05", ...}
// Replace switch statement
String projectMonth = months[month];
// Rest of your code
...
}
Another way to solve this problem will be to replace mapping of numbers to strings with converting integer to String using String.format. Use something like:
String projectMonth = String.format("%02d", month + 1);
A simple way to think about it is, cyclomatic complexity increases the more "branches" you have in your code. So with your switch statement you have a whole lot of branches (13 in fact, if I'm counting right). The switch statement can be replaced with this:
if (month < 0 || month > 11) {
projectMonth = " ";
} else {
month++;
projectMonth = ((month < 10) ? "0" : "") + Integer.toString(month);
}
Note that this still has branches, namely the if/else and ternary ?. But these could probably be removed as well, a good alternative with an array is given in the other answer.
The question shouldn't be "How can I reduce the cyclomatic complexity?", but rather "What is the best way to write this function?". One answer is return String.format("%02d-%02d-W%2d", year-2000, month+1, weekId);.
I have to filter IP address of Ipv4(32 bit) , but when i use array index up to 32 bit {array[32 bit]} it give error. So i divided the ip to three parts as;
1-one part contain index value of 25 bit { array[25 bit]}
2- second part contain value of 5 bit and this value is decoded using 5 to 32 decoder.
3-The third part of two bit indicate 4 different array in which 5 bit decoded value is stored on 25 bit address location.
It gives an error on fourth short array.
when i reduce address to 24 bit and decode 5 bit to store in 8 different short array, here 3 bits select array out of 8, then it also give an error on eighth short array,
"Exception in thread "main" java.lang.OutOfMemoryError: Java heap space"
How can this problem is resolved?
Is there any other data structure like linkedlist, tree etc that can solve this problem?
import java.util.Scanner;
class IPAddress3 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter IP address to search from list:");
String ipAddress=input.nextLine();
//String ipAddress="171.255.100.23";
String[] octets = ipAddress.split("\\.");
StringBuilder sb = new StringBuilder();
for (String octet : octets) {
int number = Integer.parseInt(octet);
if(number>255)
{
System.out.println("Error:Invalid Ip address,\n" +
"Each octet should be less or equal to 255\n");
System.exit(0);
}
else{
String binaryPart = Integer.toBinaryString(number);
if (binaryPart.length() < 8) {
for (int i = binaryPart.length(); i < 8; i++) {
binaryPart = "0" + binaryPart;
}
}
sb.append(binaryPart);
}
}
String binaryForm = sb.toString();
System.out.println(binaryForm);
System.out.println("2 MSB: " + binaryForm.substring(0, 2));
System.out.println("5 bits: " + binaryForm.substring(2, 7));
System.out.println("25 LSB: " + binaryForm.substring(7));
String MSB2Bit=binaryForm.substring(0, 2);
String fivebits= binaryForm.substring(2, 7);
String twenty5bits=binaryForm.substring(8);
byte msb2Bit=Byte.parseByte(MSB2Bit);
byte data=Byte.parseByte(fivebits,2);
int address=Integer.parseInt(twenty5bits,2);
System.out.println("Data:\t"+data);
System.out.println("Address: "+address);
short[] Array0=new short[33554432];
short[] Array1=new short[33554432];
short[] Array2=new short[33554432];
short[] Array3=new short[33554432];//error in this line
/*
short[] Array0=new short[16777216];
short[] Array1=new short[16777216];
short[] Array2=new short[16777216];
short[] Array3=new short[16777216];
short[] Array4=new short[16777216];
short[] Array5=new short[16777216];
short[] Array6=new short[16777216];
short[] Array7=new short[16777210];// error here
/*
Array0[1677721]=127;
Array1[1677721]=127;
Array2[1677721]=127;
int thirty2BitWord = 0 ;// Array0[ad]=Array0[ad] | Arra0[ad];
int filterWord = 8;
switch(data)
{
case 0:
thirty2BitWord=1;
break;
case 1:
thirty2BitWord=2;
break;
case 2:
thirty2BitWord=4;
break;
case 3:
thirty2BitWord=8;
break;
case 4:
thirty2BitWord=16;
break;
case 5:
thirty2BitWord=32;
break;
case 6:
thirty2BitWord=64;
break;
case 7:
thirty2BitWord=128;
break;
case 8:
thirty2BitWord=256;
break;
case 9:
thirty2BitWord=512;
break;
case 10:
thirty2BitWord=1024;
break;
case 11:
thirty2BitWord=2048;
break;
case 12:
thirty2BitWord=4096;
break;
case 13:
thirty2BitWord=8192;
break;
case 14:
thirty2BitWord=16384;
break;
case 15:
thirty2BitWord=32768;
break;
case 16:
thirty2BitWord=65536;
break;
case 17:
thirty2BitWord=131072;
break;
case 18:
thirty2BitWord=262144;
break;
case 19:
thirty2BitWord=524288;
break;
case 20:
thirty2BitWord=1048576;
break;
case 21:
thirty2BitWord=2097152;
break;
case 22:
thirty2BitWord=4194304;
break;
case 23:
thirty2BitWord=8388608;
break;
case 24:
thirty2BitWord=16777216;
break;
case 25:
thirty2BitWord=33554432;
break;
case 26:
thirty2BitWord=67108864;
break;
case 27:
thirty2BitWord=134217728;
break;
case 28:
thirty2BitWord=268435456;
break;
case 29:
thirty2BitWord=536870912;
break;
case 30:
thirty2BitWord=1073741824;
break;
case 31:
thirty2BitWord=2147483647;
break;
}
if(msb2Bit==0)
{
filterWord=thirty2BitWord & Array0[address];
}
else if(msb2Bit==1)
{
filterWord=thirty2BitWord & Array1[address];
}
else if(msb2Bit==2)
{
filterWord=thirty2BitWord & Array2[address];
}
/* else
{
filterWord=thirty2BitWord & Array3[address];
}*/
byte filterbit;
if(filterWord==0)
{
filterbit=0;
System.out.println("No such address is found in blacklist, So Allow\n");
}
else
{
filterbit=1;
System.out.println("IP match, So block this address\n");
}
}
}
For the short run you can fix the heap size error by increasing the memory:
How to increase application heap size in Eclipse?
I havn't checked you code too much as this error is simply the VM running out of memory. There might be a better way doing this but if the program just needs more RAM this should do the trick!
The following code won't run and keeps throwing a Number Format Exception on the line the error is "Exception in thread "main" java.lang.NumberFormatException: For input string: "SAN 1905 1808+24 1512+17 1209+10 1708-06 2016-16 211831 211941 192652" ""
intAlt = Integer.parseInt(strAlt);
I'm not sure why this is happening and would appreciate any advice on the matter
private int getPos(String strAlt)
{
int intAlt;
int intPos =0;
intAlt = Integer.parseInt(strAlt);
switch (intAlt)
{
case 3:
intPos = 4;
break;
case 6:
intPos = 9;
break;
case 9:
intPos = 17;
break;
case 12:
intPos = 25;
break;
case 18:
intPos = 33;
break;
case 24:
intPos = 41;
break;
case 30:
intPos = 49;
break;
case 34:
intPos = 56;
break;
case 39:
intPos = 63;
break;
}
return intPos;
}
If you pass "SAN 1905 1808+24 1512+17 1209+10 1708-06 2016-16 211831 211941 192652" into getPos(String strAlt), it will execute:
intAlt = Integer.parseInt(strAlt);
Of course it will throw exception.
See this doc