While and Switch Statement Problem

Switch will not recognize string

Page 1 of 1

2 Replies - 2254 Views - Last Post: 03 November 2010 - 02:59 PM Rate Topic: -----

#1 blamp  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 03-November 10

While and Switch Statement Problem

Posted 03 November 2010 - 01:55 PM

I am trying to write a some code that will tally the number of grades in a separate text file. I was instructed to use a switch statement inside the loop to read the data. The problem I have is the code i have written so far only recognizes the data as the default case, and seems to be in an infinite loop which crashes JCreator every time I run it. I was hoping someone could give me kick in the right direction.
/**
 * @(#)LoopSwitch.java
 *
 *
 * @author 
 * @version 1.00 2010/10/31
 */


import java.io.File;
import java.util.Scanner;

public class LoopSwitch {

public static void main(String[] args) throws Exception {
char grade;
int countA = 0;
int countB = 0;
int countC = 0;
int countD = 0;
int countF = 0;
int countOther = 0;
Scanner in = new Scanner(new File("letter_grades.txt"));
while (in.hasNextLine())
		{
			grade = in.nextLine();
		switch (grade)
{
	case 'A':
		++countA;
		break;
	case 'B':
		++countB;
		break;
	case 'C':
		++countC;
		break;
	case 'D':
		++countD;
		break;
	case 'F':
		++countF;
		break;
	default:
		++countOther;
		break;
	count++;									
}
		}
	System.out.println("A's: " +countA);
System.out.println("B's: " +countB);
System.out.println("C's: " +countC);
System.out.println("D's: " +countD);
System.out.println("F's: " +countF);
System.out.println("Other's: " +countOther);	
}
}  


Here is the data file letter_grades.txt
F
A
B
C
D
E
F
A
B
C
F
A
B
C
D
E
F
A
B
C
F
A
B
C
D
E
F
A
B
C
No errors when i try to run it by the way.
Thanks in advance!

Is This A Good Question/Topic? 0
  • +

Replies To: While and Switch Statement Problem

#2 TheRaiderNation  Icon User is offline

  • D.I.C Head

Reputation: 11
  • View blog
  • Posts: 81
  • Joined: 11-January 10

Re: While and Switch Statement Problem

Posted 03 November 2010 - 02:15 PM

After your default statement why is there a count++? I don't see that declared anywhere, or it used anywhere either
Was This Post Helpful? 1
  • +
  • -

#3 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10825
  • View blog
  • Posts: 40,363
  • Joined: 27-December 08

Re: While and Switch Statement Problem

Posted 03 November 2010 - 02:59 PM

The Scanner nextLine() method returns a String, not a char. So you'll want to use the charAt() method from the nextLine() so you can run a char through the switch block, not a String. Unless you are using Java 7, you cannot use Strings with a switch() block. Also, 'A' (as a char) != "A" (as a String).
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1