Java - variable "st" might not have been initialized - java

I am getting this error "variable "st" might not have been initialized" in case 5 when i try to do a string count. I tried looking online for a solution, but couldn't find someone with the same problem using string tokenizer. Please could someone tell me why this is happening?
/**
*To change this license header,choose License Headers in Project Properties.
*To change this template file,choose Tools|Templates
*and open the template in the editor.
*/
package labone;
import java.util.Scanner;
import java.util.StringTokenizer;
public class LabOne {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Welcome To The String Editor!");
System.out.println("");
System.out.println("Please choose what you would like to do by choosing one of the options below:");
System.out.println("1. Input String");
System.out.println("2. Print Current String");
System.out.println("");
int userOption = 0;
String stringInput = new String();
while (userOption != 9) {
userOption = userInput.nextInt();
userInput.nextLine();
switch (userOption) {
case 1:
stringInput = userInput.nextLine();
System.out.println(stringInput);
break;
case 2:
System.out.println(stringInput);
break;
case 3:
stringInput = new StringBuilder(stringInput).reverse().toString();
System.out.println(stringInput);
break;
case 4:
StringTokenizer st = new StringTokenizer(stringInput);
System.out.println(stringInput);
break;
case 5:
System.out.println("Number of tokens:" + st.countTokens());
break;
default:
;
break;
}
}
// TODO code application logic here
}
}

Please could someone tell me why this is happening?
You initialize st locally in case 4. It is not visible in case 5.
Solution: initialize it outside the switch block.
Alternatively, as spotted by Thilo, you can initialize it in case 5, as it doesn't seem to be used anywhere else.
case 5:
StringTokenizer st = new StringTokenizer(stringInput);
System.out.println("Number of tokens:" + st.countTokens());
break;
You should be careful not to initialize so many variables locally though, as you can have the very same problem happen again.

Initialize the StringTokenizer outside the switch block. Dont do it in case 4.

You have initialize st in case 4 but not in case 5, You can corrected it in this way.
StringTokenizer st;
switch (userOption) {
case 1:
stringInput = userInput.nextLine();
System.out.println(stringInput);
break;
case 2:
System.out.println(stringInput);
break;
case 3:
stringInput = new StringBuilder(stringInput).reverse().toString();
System.out.println(stringInput);
break;
case 4:
st = new StringTokenizer(stringInput);
System.out.println(stringInput);
break;
case 5:
st = new StringTokenizer(stringInput);
System.out.println("Number of tokens:" + st.countTokens());
break;
default:
;
break;
}

declare it globally, declare it outside the switch block, where you declare your all variable.
Declare it here,
int userOption = 0;
String stringInput = new String();
StringTokenizer st; //add here
so your case 4 will be
case 4: st = new StringTokenizer(stringInput);
System.out.println(stringInput);
break;

you initialized st in case 4, just take the case when user enter option 5 before 4, in that case st is not initialized right. So the solution is to initialize st either in the main first and then use it in specific switch cases, or initialize it for case 5 as well.

case 4: StringTokenizer st = new StringTokenizer(stringInput);
System.out.println(stringInput);
break;
case 5: System.out.println("Number of tokens:" + st.countTokens());
break;
In the switch case, the variable, st declared in case 4 is available in locally for that case only. It will not be available outside the case block. If you need to access it, you need to declare it outside the switch block.

Related

I need a way to exit my infinity loop in java when the user inputs anything, but the loop pauses while its looking for inputs

I am making a clock and I obviously don't want the clock to pause while it's looking for inputs.
i first use the switch-case statement which changes the value of timezone_str and then the local time method prints it
So please tell me a way using which I can help the user exit my infinity loop (it's fine if it's not by inputting). || PLS NOTE: I USE BLUE J ||
Here is my code:-
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Scanner;
public class AnalogClock_Project {
public static void main(String[] args) {
int choose = 0;
boolean PutAnEndToThis = true;
String timezone_str = new String();
Scanner sc = new Scanner(System.in);
choose = sc.nextInt();
switch(choose) {
case 1:
timezone_str = "UTC";
break;
case 2:
timezone_str = "GMT";
break;
case 3:
timezone_str = "US/Central";
break;
case 4:
timezone_str = "PST";
break;
case 5:
timezone_str = "Asia/Kolkata";
break;
case 6:
timezone_str = "Japan";
break;
case 7:
timezone_str = "Europe/London";
break;
case 8:
timezone_str = "Hongkong";
break;
case 9:
timezone_str = "Australia/Sydney";
break;
case 10:
timezone_str = "Europe/Rome";
break;
case 11:
timezone_str = "US/Eastern";
break;
case 12:
timezone_str = "US/Hawaii";
break;
case 13:
timezone_str = "Africa/Cairo";
break;
case 14:
timezone_str = "America/Mexico_City";
break;
case 15:
timezone_str = "Asia/Riyadh";
break;
case 16:
timezone_str = "Europe/Moscow";
break;
case 17:
timezone_str = "Asia/Manila";
break;
}
System.out.print('\f');
Scanner sC = new Scanner(System.in);
while (PutAnEndToThis) {
LocalTime time = LocalTime.now(ZoneId.of(timezone_str));
System.out.print(time);
try{
Thread.sleep(500);
}
catch(InterruptedException ie) {}
System.out.print('\f');
}
System.out.print("\f thank you for using you clock \n hopefully you can get rich enough \n to buy a watch next time");
}
}
Start a separate Thread to print the time. Use Scanner to accept a value from the user. When the user enters a value, interrupt the Thread.
final String timezone_str = "UTC";
Thread thrd = new Thread(() -> {
while (true) {
LocalTime time = LocalTime.now(ZoneId.of(timezone_str));
System.out.print(time);
try {
Thread.sleep(1000);
}
catch (InterruptedException ie) {
break;
}
System.out.print('\f');
}
});
thrd.start();
Scanner in = new Scanner(System.in);
in.next();
thrd.interrupt();
The user needs to press some key on the keyboard and then press <ENTER>. As soon as she does, the Thread will terminate.
Note that I used an arbitrary value for timezone_str since it was not clear to me, from your question, how you assign a value to that variable.
Try to change 1=1 to a boolean variable and break the loop with it.
Example:
boolean key = true;
while (key)
{
LocalTime time = LocalTime.now(ZoneId.of(timezone_str));
System.out.print(time);
try{
Thread.sleep(100);
} catch(InterruptedException ie) {
//Do something to change key
}
//Do something to change key
}

Conditional wont be read in do while statement

For my program I am trying to have the loop run until the letter n is entered. But for some reason i keep receiving the error cannot find symbol in the condition for my loop. All help is greatly appreciated.
import java.io.*;
import java.util.*;
public class Prog213c
{
public static void main(String[] args) {
Scanner kbReader=new Scanner(System.in);
do{
System.out.println( "Enter student number");
int studentNumber = kbReader.nextInt();
System.out.println(" Enter credits ");
int credits = kbReader.nextInt();
switch (credits)
{
case 30:
System.out.println("Grade Level code = 2");
break;
case 29:
System.out.println("Grade Level code = 1");
break;
case 70:
System.out.println("Grade Level code = 3");
break;
case 103:
System.out.println("Grade Level code = 4");
break;
default: System.out.println("invalid number");
}
System.out.print("Do again(y/n)");
String answer = kbReader.next();
} while (answer == 'y'); // error received here
You have a few problems here:
String answer = kbReader.next();
} while (answer == 'y'); // error received here
Technically, answer is out of scope when you try to use - you can only use answer inside the loop itself. You should declare answer prior to starting your while loop so that it's in scope. Also, answer is a string and you're trying to "directly" compare it to a char.
This is also performing a case-sensitive comparison; while this isn't technically incorrect, it would be more user-friendly to accept accept either "Y" or "y".
Also, your switch statement won't work correctly. For example, case 30 will only be called if credits is exactly 30, which I assume isn't what you want.
You could do something like:
case 30:
case 31:
case 32: // ...
but that seems like a thoroughly painful way to do that. See also this question for more details.
This answer is particularly interesting and could be useful for your purposes. This is the code from that answer:
switch ((int) num/10) {
case 1:
System.out.println("10-19");
break;
case 2:
System.out.println("20-29");
break;
case 3:
System.out.println("30-39");
break;
case 4:
System.out.println("40-49");
break;
default:
break;
}
(Again, just to give credit where credit's due the above isn't my code, it was from the linked answer).
Also:
int studentNumber = kbReader.nextInt();
You never actually do anything with studentNumber, just prompt the user for it. Did you mean to do this?
Single quotes are character literals in Java. So you can't compare a
String with a char directly.
Your answer variable has to be declared before the do-while loop.
you have to use the equals method to compare strings.
answer.equals("y")
Problem 1:
since answer is a string object, this is not working (answer == 'y');
you can do "y".equals(answer) is you get the nextLine from the scanner
or if you need to work with chars
char x = kbReader.next().charAt(0);
while (x == 'y');
Problem 2:
answer must be declared before the do-while loop...
your final code can look like
Scanner kbReader = new Scanner(System.in);
char answer = 'y';
do {
System.out.println("Enter student number");
int studentNumber = kbReader.nextInt();
System.out.println(" Enter credits ");
int credits = kbReader.nextInt();
switch (credits) {
case 30:
System.out.println("Grade Level code = 2");
break;
case 29:
System.out.println("Grade Level code = 1");
break;
case 70:
System.out.println("Grade Level code = 3");
break;
case 103:
System.out.println("Grade Level code = 4");
break;
default:
System.out.println("invalid number");
}
System.out.print("Do again(y/n)");
answer = kbReader.next().charAt(0);
} while (answer == 'y');
Change your while condition to:
while ("y".equals(kbReader.next()));

Adding Elements in to a queue individually from text file

I would like to add a name to a queue (linked), one name at a time from a text file. If the user selects choice 1 then it should take the next name in from the lists.
Case 1 is not letting me input another choice if I want to add another name.
int choice = console.nextInt();
FileReader names = new FileReader("Customer.txt");
Scanner lookup = new Scanner(names);
Queue a = new Queue();
String customerName;
// This loop was just to verify that
while(lookup.hasNextLine() ){ // It was actually reading
customerName = lookup.next();
System.out.println(customerName);
}
while(true){
switch(choice){
case 1:
customerName = lookup.next();//For some reason its not giving me
a.enqueue(customerName); // The choice to enter another number
break; //even though I made the case while(true)
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
System.out.println(" Exiting......");
break;
default:
continue;
}
break;
}
The problem here is that there is a break after the switch statement. This is causing your code to jump out of the while loop after one pass of the switch statement.
The solution is to remove the break, as such:
while(true){
switch(choice){
case 1:
customerName = lookup.next();//For some reason its not giving me
a.enqueue(customerName); // The choice to enter another number
break; //even though I made the case while(true)
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
System.out.println(" Exiting......");
break;
default:
continue;
}
}

Java Switch Statement: creating a calculator error

I was wondering if anyone can see what is wrong with my code. It works except that the program is not acknowledging my switch statement - I searched lots of questions but as I am a novice I am clearly missing something.
import java.util.Scanner;
class Calmlr1 {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
String anotherOption = "y", operatorOpt= "a";
int no1=0, no2=0;
double result= 0;
System.out.println ("Welcome to the online calculator! Let's begin...");
while (anotherOption.equalsIgnoreCase ("y")) {
System.out.println ("Please enter your 1st number: ");
no1 = input.nextInt();
System.out.println ("Please confirm your operator:\n1 = +\n2 = - \n3 = *\n4 = /");
operatorOpt = input.next ();
System.out.println ("Please enter your 2nd number: ");
no2 = input.nextInt();
switch(no1) {
case 1:
result=no1+no2;
break;
case 2:
result=no1-no2;
break;
case 3:
result=no1*no2;
break;
case 4:
result=no1/no2;
default:
result = 0 ;
break;
}
System.out.println("Your total calculation is: "+result);
System.out.println("Would you like to do another sum? y/n ");
anotherOption=input.next();
}
}
}
You should be using switch(operatorOpt). Right now you are switching on the first number.
You also need to change:
int operatorOpt= 0;
operatorOpt = input.nextInt();
That is, if you want to keep your switch statement the same. Please also see #Daniel Imms answer for an additional bug fix.
Try adding a break at the end of case 4
case 4:
result=no1/no2;
break;
EDIT J L's answer is the main issue, but this is another problem that will break division.
Your switch should be on the operatorOpt and not on no1.
Also, you're missing a break in the case 4. So, if you want to do a division, you'll get 0 as result.
The input from the user for operatorOpt should be done with input.nextLine(). Or, if you want to keep the same switch statement, with input.nextInt().
It should be like this:
switch(operatorOpt)
{
case "+":
result=no1+no2;
break;
case "-":
result=no1-no2;
break;
case "*":
result=no1*no2;
break;
case "/":
result=no1/no2;
break;
default:
result = 0 ;
break;
}
Your switch statement should be on "operatorOpt" and not on "no1" as you suppose to check the operator and based on that you want to do the calculation. However, you must use JDK1.7 to use String in Switch statement since previous versions of JDK do not support String Switch.
Also, you should use "break" in case 4.
Your switch should be on the operatorOpt and not on no1.
You can use like this
switch(operatorOpt)
{
case "+":
result=no1+no2;
break;
case "-":
result=no1-no2;
break;
case "*":
result=no1*no2;
break;
case "/":
result=no1/no2;
break;
default:
result = 0 ;
break;
}

Switch statement in Java

Basically I need to take a letter A-Z and convert it to Leek(a combo of sign,#,letter that look like the A-Z characters. I'm only allow to use switch statements (switch,case,breaks) also I have to use the .next().charAt(0) method.
When I try to compile my program it comes up with multiple error all reading "can not find symbol" pointing at the a-z character I used in the case statement.
import java.util.Scanner;
public class dlin_Leet
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
char character;//input by user
String Leet;
System.out.print("Enter character to convert:");
String Leet = input.next();
char character = Leet.charAt(0);
switch (character)
{
case a: Leet = "4";
break;
case b: Leet = "I3";
break;
case c: Leet = "[";
break;
case d: Leet = ")";
break;
case e: Leet = "3";
break;
case f: Leet = "|=";
break;
case g: Leet = "&";
break;
case h: Leet = "#";
break;
case i: Leet = "1";
break;
case j: Leet = "J";
break;
case k: Leet = "|<";
break;
case l: Leet = "1";
}
System.out.println(Leet);
}
}
The character constants must be in into apostraphs:
case 'a': instead of case a:
Fix your code and I hope this is the only syntax error you have.
Also
- You are declaring variable "Leet" and "character" twice in the same block( Duplicate local variable)
case statement using char (which means single quote), it should be something like
switch (character)
{
case 'a': Leet = "4";
break;
case 'b': Leet = "I3";
break;
.........
}
your case should be a char like case 'a'
switch(character)
{
case 'a':
//do your stuff
}
and also you are declaring leet(String variable twice). just declare it one and use the same variable when you get input from the scanner
Using strings in switch case can only be used if you using JDK7 and even then you will have to have the values in quotes.
Like
case "a":

Categories