Hi i have a txt file that have a number in bunch of rows and i get this error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
what can i add in my code to make it work it seems to be right to me but idont know why i get error
public static void main(String[] args) {
String input;
try {
Scanner scan = new Scanner(new File("andy.txt"));
while (scan.hasNextLine()) {
lineCounters++;
input = scan.nextLine();
putArray(sigFig(input));
}
calcPercentage();
makeGraph();
scan.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
here is my putArray
public static void putArray(char input) {
switch (input) {
case '1':
++digitCounters[0];
break;
case '2':
++digitCounters[1];
break;
case '3':
++digitCounters[2];
break;
case '4':
++digitCounters[3];
break;
case '5':
++digitCounters[4];
break;
case '6':
++digitCounters[5];
break;
case '7':
++digitCounters[6];
break;
case '8':
++digitCounters[7];
break;
case '9':
++digitCounters[8];
break;
}
}
It might be your putArray function which launches that exception. Can I have a look of it?
Related
**About the code: I am just making a simple code using a switch statement. All the switch cases work fine except the double-digit cases. I get an error saying :
year.java:37: error: unclosed character literal
case '10'
year.java:40: error: unclosed character literal
case '11':year.java:43: error: unclosed character literal
case '12'
Code :
import java.util.Scanner;
public class year {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char year;
System.out.println("Enter the number of the month ");
year = input.next().charAt(0);
switch(year){
case '1':
System.out.println("January");
break;
case '2':
System.out.println("Febraury");
break;
case '3':
System.out.println("March");
break;
case '4':
System.out.println("April");
break;
case '5':
System.out.println("May");
break;
case '6':
System.out.println("June ");
break;
case '7':
System.out.println("July");
break;
case '8':
System.out.println("August ");
break;
case '9':
System.out.println("September ");
break;
case '10':
System.out.println("October");
break;
case '11':
System.out.println("November");
break;
case '12'
System.out.println("December");
break;
default:
System.out.println("Invalid");
}
input.close();
}
}
I tried doing a few changes here and there but couldn't understand them and thus could not do so.
Your variable year is a char. A char can only be a single character.
Therefore when you try and do '11' or '12' you run into issues as these "chars" consist of more than one character.
The quick solution here would be to use a String instead of char, using input.next() without the .charAt(0). Then you would need to change your case statements to use double quotes instead of single quotes.
Alternatively, you could do Integer.parseInt(input.next()) and then switch on an int instead, as #Tom has suggested.
First of all, there is a Syntax error in case '12' it should be case '12':
(Also the code indention is bad. Poor indentation make it hard for debugging)
I suggest you convert this code to a String based one. Please check the complete example below.
Char can get one character only and char year; cause a bug, because in input values like 10, 11, 12 it won't work as expected
import java.util.Scanner;
public class year {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String year;
System.out.println("Enter the number of the month ");
year = input.nextLine();
switch(year){
case "1":
System.out.println("January");
break;
case "2":
System.out.println("Febraury");
break;
case "3":
System.out.println("March");
break;
case "4":
System.out.println("April");
break;
case "5":
System.out.println("May");
break;
case "6":
System.out.println("June ");
break;
case "7":
System.out.println("July");
break;
case "8":
System.out.println("August ");
break;
case "9":
System.out.println("September ");
break;
case "10":
System.out.println("October");
break;
case "11":
System.out.println("November");
break;
case "12":
System.out.println("December");
break;
default:
System.out.println("Invalid");
}
input.close();
}
}
In my approach below I have a text file of hex values that are passed into a string arraylist, I have a working method that converts a character array into binary titled 'hexToBin'.
I am currently stuck and my question is how would I pass each hex value in the arraylist as a character string so I can use my conversion method to convert hexadecimal values into binary.
I am not allowed to use java's automatic conversion methods or parse commands
hexadecimal text file ~
33CDAEFFAD
032DAE01AD
196CDAEFC0
21A00D0000
100CDAEFFA
F3ABCDEFAB
29A0EDF301
3ABCDEFABC
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
static void hexToBin(char hexdec[])
{
int i = 0;
while (hexdec[i] != '\u0000')
{
switch (hexdec[i])
{
case '0':
System.out.print("0000");
break;
case '1':
System.out.print("0001");
break;
case '2':
System.out.print("0010");
break;
case '3':
System.out.print("0011");
break;
case '4':
System.out.print("0100");
break;
case '5':
System.out.print("0101");
break;
case '6':
System.out.print("0110");
break;
case '7':
System.out.print("0111");
break;
case '8':
System.out.print("1000");
break;
case '9':
System.out.print("1001");
break;
case 'A':
System.out.print("1010");
break;
case 'B':
System.out.print("1011");
break;
case 'C':
System.out.print("1100");
break;
case 'D':
System.out.print("1101");
break;
case 'E':
System.out.print("1110");
break;
case 'F':
System.out.print("1111");
break;
default:
System.out.print("\nInvalid hexadecimal digit " + hexdec[i]);
}
i++;
}
}
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(new File("RAMerrors8x4c"));
ArrayList<String> values = new ArrayList<String>();
while(sc.hasNext())
{
values.add(sc.nextLine());
}
for(int i = 0; i < values.size(); i++)
{
try {
hexToBin(values.get(i).toCharArray());
}
catch (ArrayIndexOutOfBoundsException e){
System.out.print("");
}
}
}
}
I'm stuck at a question that requests me if the user insert something else instead "e" "x" nums between 1 to 10, then it's returning "incorrect"
here's the code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try{
int Num = 0;
Num = sc.nextInt();
String str = sc.nextLine();
switch (Num) {
case 1: case 2: case 3: case 4:
case 5: case 6: case 7: case 8:
case 9: case 10:
System.out.println("this is a volume");
break;
case : if((Num>10)||(Num <0))
System.out.println("this is incorrect");
break;
}
switch (str) {
case "e": case "E":
System.out.println("Shutting Down");
break;
case "x" : case "X":
System.out.println("Mute");
break;
case "a":case "b":case "c":case "d":case "f":case "g":case "h":case "i":case "j":
case "k":case "l":case "m":case "n":case "o":case "p":case "q":case "r":case "s":
case "t":case "u":case "v":case "w":case "y":case "z":
System.out.println("this is incorrect");
break;
default:
break;
}
}
catch(Exception e) {
System.out.println("stopped");
}
}
}
thank you
If I understand your question properly, as you did not specify how many time the user should enter the input. However, you can have a look at this example, take the idea of the approach and then create your own one.
import java.util.Scanner;
public class ParseInput {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Insert E for Shutdown, X for Mute and Numbers between 1 to 10 for Volume");
String input = in.nextLine().trim(); // read the entire line after removing spaces if any, then parse it
if(input.length()>0){ // that means the user entered something
try{
int volumeValue = Integer.parseInt(input); // if it's not a number, it will throw exception that will be handled in the catch block
if(volumeValue>=1 && volumeValue<=10){// then evaluate the value
System.out.println("This is a Volume");
}
else{
System.out.println("Incorrect Volume Value");
}
}catch(NumberFormatException e){ // if you reach this block that means it's not a number
if(input.equalsIgnoreCase("e")){ // to accept both uppercase and lowercase
System.out.println("Shutting Down");
}
else if(input.equalsIgnoreCase("x")){
System.out.println("Mute");
}
else{
System.out.println("Incorrect Input");
}
}
}
else{
System.out.println("You have NOT entered anything!");
}
}
}
Test
Insert E for Shutdown, X for Mute and Numbers between 1 to 10 for Volume
e -> Shutting Down
x -> Mute
5 -> This is a Volume
12 -> Incorrect Volume Value
ZzZ -> Incorrect Input
-> You have NOT entered anything!
Please try the below code
switch (Num)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
System.out.println("this is a volume");
break;
default:
{
if ((Num > 10) || (Num < 0))
{
System.out.println("this is incorrect");
}
break;
}
}
New to Java and I'm having troubles with my code, it's a switch statement within a while loop. I like to use letters or "char" instead of numbered cases "int" and I have 'q' to quit. Thanks for your input. This is the main code.
import java.util.Scanner;
import java.util.*;
public class supraCritters {
public static void main(String [] arguments) {
Critter nastybat = new Critter();
nastybat.health = 100;
nastybat.mood = 50;
nastybat.hunger = 25;
System.out.println("Your critter has just been born,");
System.out.println("here are the stats of your critter.");
nastybat.checkStats();
System.out.println("\nPlease choose a letter");
System.out.println("[c]heck stats \n[f]eed \n[p]lay \n[r]ead \n[t]rain");
System.out.println("[q]uit");
Scanner sChoice = new Scanner(System.in);
char choice = ' ';
while (choice != 'q') {
switch (choice) {
case 'c':
nastybat.checkStats();
break;
case 'f':
nastybat.feed();
break;
case 'p':
nastybat.play();
break;
case 'r':
nastybat.read();
break;
case 't':
nastybat.train();
break;
case 'q':
System.out.println("good bye");
break;
default:
System.out.println("invalid entry");
break;
}
choice = sChoice.next().charAt(0);
}
}
}
When I enter corresponding letter the loop doesn't show Input method or repeat and 'q' does nothing. Default displays "invalid entry" before input.
Code edited and still have problems.
The input is taken only once, the first time! Therefore the loop always returns the same result. You should duplicate the getting input code inside the loop!
Scanner sChoice = new Scanner(System.in);
char choice = '';
while (choice != 'q') {
switch (choice) {
case 'c':
nastybat.checkStats();
break;
.
.
.
.
.
choice = sChoice.next().charAt(0);
The first line gets input for the first switch run, and the one inside the loop gets the rest.
UPDATE:
The choice = sChoice.next().charAt(0); should be place at the final of the loop, if not, as #proskor says, when user hits 'q' the program will return an 'invalid entry'.
I finished the code and it seems to work. Testing out the methods the object can use now.
Final
import java.util.Scanner;
import java.util.*;
public class supraCritters {
public static void main(String [] arguments) {
Critter nastybat = new Critter();
nastybat.health = 100;
nastybat.mood = 50;
nastybat.hunger = 25;
System.out.println("Your critter has just been born,");
System.out.println("here are the stats of your critter.");
nastybat.checkStats();
Scanner sChoice = new Scanner(System.in);
char choice = ' ';
while (choice != 'q') {
switch (choice) {
case 'c': case 'C':
nastybat.checkStats();
break;
case 'f': case 'F':
nastybat.feed();
break;
case 'p': case 'P':
nastybat.play();
break;
case 'r': case 'R':
nastybat.read();
break;
case 't': case 'T':
nastybat.train();
break;
case 'q': case 'Q':
System.out.println("good bye");
break;
default:
System.out.println("invalid entry");
break;
}
System.out.println("\nPlease choose a letter");
System.out.println("[c]heck stats \n[f]eed \n[p]lay \n[r]ead \n[t]rain");
System.out.println("[q]uit");
choice = sChoice.next().charAt(0);
}
}
}
I am running into a problem where Scanner isn't blocking for user input during an indefinite while loop. I've tried using hasNextLine() and that hasn't worked. It just runs the loop infinitely calling displayMenu().
do {
displayMenu();
int response;
while (iStream.hasNextLine()) {
response = Integer.parseInt(iStream.nextLine());
switch (response) {
case 1:
decodeMessage(getPhrase());
break;
case 2:
encodeMessage(getPhrase());
break;
case 3:
displayAlphabet();
break;
case 4:
done = true;
System.out.println("Goodbye.");
break;
default:
done = false;
}
}
}
while (!done);
I've also tried not using hasNextLine() but I end up with a NoSuchElementException as it runs through perfectly the first time but on the second iteration, it doesn't block for user input.
do {
displayMenu();
int response = Integer.parseInt(iStream.nextLine());
switch (response) {
case 1:
decodeMessage(getPhrase());
break;
case 2:
encodeMessage(getPhrase());
break;
case 3:
displayAlphabet();
break;
case 4:
done = true;
System.out.println("Goodbye.");
break;
default:
done = false;
}
}
while (!done);
Any thoughts?
The following works fine for me:
private static void displayMenu ()
{
System.out.println ("Menu:");
System.out.println ("\t1: Decode message");
System.out.println ("\t2: Encode message");
System.out.println ("\t3: Display alphabet");
System.out.println ("\t4: Exit");
}
public static void main (String [] args)
{
Scanner scanner = new Scanner (System.in);
boolean done = false;
while (!done)
{
displayMenu();
switch (Integer.parseInt (scanner.nextLine ()))
{
case 1:
System.out.println ("Decoding...");
break;
case 2:
System.out.println ("Encoding...");
break;
case 3:
System.out.println ("Displaying alphabet...");
break;
case 4:
System.out.println("Exitting...");
done = true;
break;
default:
done = false;
}
}
}