Input mismatch int - java

I have a this small code:
Scanner vloz = new Scanner(System.in);
int cisla = 0;
int i = 0;
while(i < 10){
try {
System.out.println("Vloz cislo " + i + ":");
int cislo = Integer.parseInt(vloz.nextLine());
++i;
cisla = cisla + cislo;
}
catch(InputMismatchException exception){
System.out.println("Nevlozil si cislo!");
}
}
float priemer = cisla / i;
System.out.println("Priemer cisel je " + priemer + ".");
}
}
but always when I run it and type other charakters then int, program crash and did not run through "catch".
The goal of the program is when the other then int is typed show error message, do not add to int i and give another option to the user to add the intenger.

You need to be catching a NumberFormatException rather than an InputMismatchException like so:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner vloz = new Scanner(System.in);
int cisla = 0;
int i = 0;
while(i < 10){
try {
System.out.print("Vloz cislo " + i + ":");
int cislo = Integer.parseInt(vloz.nextLine());
i++;
cisla = cisla + cislo;
} catch(NumberFormatException exception) {
System.out.println("Nevlozil si cislo!");
}
}
float priemer = cisla / i;
System.out.println("Priemer cisel je " + priemer + ".");
}
}
Try it here!

You catch the wrong exception. The method parseInt(String s) throws a NumberFormatException not a InputMismatchException. Change your catch clause to catch(NumberFormatException exception).

import java.util.*;
public class demo{
public static void main (String []args ){
Scanner vloz = new Scanner(System.in);
int cisla = 0;
int i = 0;
while(i < 10){
try {
System.out.println("Vloz cislo " + i + ":");
int cislo = Integer.parseInt(vloz.nextLine());
++i;
cisla = cisla + cislo;
}
catch(InputMismatchException exception){
System.out.println("Nevlozil si cislo!");
}
}
float priemer = cisla / i;
System.out.println("Priemer cisel je " + priemer + ".");
}
}
I'm not sure why it crashed but this code works. I think you may have forgotten to import.java.*;

Related

How to find factorial and show result of counting in console?

public class Car {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println(n+"!="+factorial(n));
}
public static int factorial(int num) {
return (num == 0) ? 1 : num * factorial (num - 1);
}
}
how make this code to text in console 3! = 1*2*3 = 6?
Don't use recursion for this. Besides, it isn't really efficient or necessary.
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int fact = 1;
String s = n + "! = 1";
for (int i = 2; i <= n; i++) {
fact *= i;
s += "*" + i;
}
s += " = ";
System.out.println(s + fact);
There can be many ways to do it e.g. you can build the required string or print the trail while calculating the factorial. In the following example, I have done the former.
As an aside, you should check the input whether it is a positive integer.
import java.util.Scanner;
public class Car {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = in.nextInt();
if (n >= 0) {
StringBuilder strFact = new StringBuilder();
int fact = factorial(n, strFact);
if (strFact.length() > 0) {
// Delete the last '*'
strFact.deleteCharAt(strFact.length() - 1);
System.out.println(n + "!= " + strFact + " = " + fact);
} else {
System.out.println(n + "!= " + fact);
}
} else {
System.out.println("This is an invalid input.");
}
}
public static int factorial(int num, StringBuilder strFact) {
int fact;
if (num == 0) {
fact = 1;
} else {
fact = num * factorial(num - 1, strFact);
strFact.append(num + "*");
}
return fact;
}
}
A sample run:
Enter an integer: 3
3!= 1*2*3 = 6

Using variables form other classes in java

I am trying to use two int variables from other classes in another class and then add them together into another variable and print the result. When I try this though, I always get a result of zero like the values are not being brought over into the new class and I can't figure out what the problem is.
Here is some example code:
class1
public static int finished = (match2.totalpoints + match3.iq);
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
System.out.println("");
System.out.println("When taking the quiztest you have only two seconds before making each guess");
match2 m = new match2();
System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + finished + " POINTS");
}
}
EDIT: class2
public class match2 {
public static int totalpoints;
int a;
int b;
int c;
int d;
int e;
int f;
String guess;
String group;
String countdown[] = {
"3...",
"2...",
"1...",
""
};
String memorize[] = {
""
};
public match2() throws InterruptedException
{
int x = set2();
int y = set3();
int z = set4();
total(x, y, z);
System.out.println("For the next part of your IQ ASSesment\njust type back the words in CAPSLOCK in CAPSLOCK");
System.out.println("");
match3 n = new match3();
}
public void set1() throws InterruptedException
{
//Scanner s = new Scanner(System.in);
for (int i = 0; i < countdown.length; i++)
{
Thread.sleep(750);
System.out.println(countdown[i]);
}
}
public int set2() throws InterruptedException
{
Random r = new Random();
Scanner s = new Scanner(System.in);
System.out.println("press ENTER for your first set...");
s.nextLine();
set1();
int rv = 0;
a = r.nextInt(9) + 1;
b = r.nextInt(9) + 1;
c = r.nextInt(9) + 1;
d = r.nextInt(9) + 1;
group = "" + a + b + c + d;
System.out.println(group);
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
guess = "" + s.nextLine();
if(guess.equals(group))
{
System.out.println("nice +1 bruh");
rv = 1;
}
else if(!guess.equals(group))
{
System.out.println("almost");
}
return rv;
}
public int set3() throws InterruptedException
{
Random r = new Random();
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("press ENTER for your next set...");
s.nextLine();
set1();
int rv = 0;
a = r.nextInt(9) + 1;
b = r.nextInt(9) + 1;
c = r.nextInt(9) + 1;
d = r.nextInt(9) + 1;
f = r.nextInt(9) + 1;
group = "" + a + b + c + d + f;
System.out.println(group);
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
guess = s.nextLine();
if(group.equals(guess))
{
rv = 1;
System.out.println("good");
}
else if(!guess.equals(group))
{
System.out.println("almost");
}
return rv;
}
public int set4() throws InterruptedException
{
Random r = new Random();
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("press ENTER for your final set...");
s.nextLine();
set1();
int rv = 0;
a = r.nextInt(9) + 1;
b = r.nextInt(9) + 1;
c = r.nextInt(9) + 1;
d = r.nextInt(9) + 1;
e = r.nextInt(9) + 1;
f = r.nextInt(9) + 1;
group = "" + a + b + c + d + f + e;
System.out.println(group);
System.out.println("");
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
guess = "" + s.nextLine();
if(group.equals(guess))
{
rv = 1;
System.out.println("great");
}
else if(!group.equals(guess))
{
System.out.println("eeeh buzer sound");
}
return rv;
}
public int total(int x, int y, int z)
{
System.out.println("");
int totalpoints = (x + y + z);
if(totalpoints == 3)
{
System.out.println("YOU GOT THEM ALL");
}
if(totalpoints <= 2 && totalpoints >= 1)
{
System.out.println("YOU MISSED A TOTAL OF " + (3 - totalpoints));
}
if(totalpoints == 0)
{
System.out.println("HA! YOU MISSED THEM ALL");
}
return totalpoints;
}
}
EDIT: class3
public class match3 {
public static int iq;
String countupdown [] = {
"READY...",
"SET.....",
""
};
String memorize [] = {
""
};
public match3() throws InterruptedException
{
int mem1 = memory1();
int mem2 = memory2();
int mem3 = memory3();
totalMemory(mem1, mem2, mem3);
}
public void methodCountdown() throws InterruptedException
{
for(int i = 0; i < countupdown.length; i++)
{
Thread.sleep(1000);
System.out.println(countupdown[i]);
}
}
public int memory1() throws InterruptedException
{
int rv = 1;
Scanner s = new Scanner(System.in);
System.out.println("Press ENTER when ready");
s.nextLine();
methodCountdown();
String a = word1();
String b = word2();
System.out.println("The " + a + " ate the " + b);
String wordgroup = "" + a + " " + b;
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
String wordguess = "" + s.nextLine();
if(wordgroup.equals(wordguess))
{
System.out.println("awesome cock muncher a match");
rv = 1;
}
else if(!wordgroup.equals(wordguess))
{
System.out.println("nope");
}
return rv;
}
public int memory2() throws InterruptedException
{
int rv = 0;
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("Press ENTER for your next set");
s.nextLine();
methodCountdown();
String a = word1();
String c = word3();
System.out.println("The " + a + " drove the " + c);
String wordgroup = "" + a + " " + c;
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
String wordguess = "" + s.nextLine();
if(wordgroup.equals(wordguess))
{
System.out.println("awesome cock muncher a match");
rv = 1;
}
else if(!wordgroup.equals(wordguess))
{
System.out.println("nope");
}
return rv;
}
public int memory3() throws InterruptedException
{
int rv = 0;
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("Press ENTER for your next set");
s.nextLine();
methodCountdown();
String a = word1();
String d = word4();
System.out.println("The " + a + " visited the " + d);
String wordgroup = "" + a + " " + d;
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
String wordguess = "" + s.nextLine();
if(wordgroup.equals(wordguess))
{
System.out.println("awesome cock muncher a match");
rv = 1;
}
else if(!wordgroup.equals(wordguess))
{
System.out.println("nope");
}
return rv;
}
public static String word1()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "DOG";
}
else if(cv == 2)
{
word = "CAT";
}
else if(cv == 3)
{
word = "BIRD";
}
return word;
}
public static String word2()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "FOOD";
}
else if(cv == 2)
{
word = "MUD";
}
else if(cv == 3)
{
word = "GRAINS";
}
return word;
}
public static String word3()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "TRAM";
}
else if(cv == 2)
{
word = "BUS";
}
else if(cv == 3)
{
word = "BICYCLE";
}
return word;
}
public static String word4()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "MALL";
}
else if(cv == 2)
{
word = "PARK";
}
else if(cv == 3)
{
word = "POOL";
}
return word;
}
public void totalMemory(int mem1, int mem2, int mem3)
{
int iq = (mem1 + mem2 + mem3);
System.out.println("");
if(iq == 3)
{
System.out.println("YOU GOT THEM ALL");
}
else if(iq <= 2 || iq >= 1)
{
System.out.println("YOU MISSED A TOTAL OF " + (3 - iq));
}
else if(iq == 0)
{
System.out.println("HA! YOU MISSED THEM ALL");
}
}
}
total points is a variable from match2 class and iq from match3 class. Any help with any methods I could use to make this happen would be much appreciated. Thank You
Well ... besides the fact you are not following any code convention, Like class names should start with a capital letter and public static final fields (like totalpoints and iq) should be all Uppercase (code conventions, you are not sharring match2 and match3 codes, without it we can't understand what is happening inside those classes.
But you can do a simple test and assign a value to match2.totalpoints and match3.iq and you are going to see the summing of these two values being printed by the last system.out you put.
good luck and good Java studies!
Are the int variables you're trying to use inside child classes of your main parent class? Did you extend the child classes in your main parent class?
Class #1:
public int firstVar(int someNum) {
//code here
return someNum;
}
Class #2:
public int secondVar(int otherNum) {
//code here
return otherNum;
}
Class #3 Class with Main Method -
public class mainClass extends class#1; //etc
//code here and finally print out the finished number
You could try extending one of the classes that has an int you need into another one of the classes with the other int you need and then just extending that second class into your main, OR you could try completely redefining your classes and just placing all the ints you need into one separate class and then extending that single one into your main.
So I finally got it to work. The problem, I guess, was that I was trying to add together the variables from the other classes(match2 and match3) outside the main function within the class(match1) I was trying to add them together. All I did was move the expression adding the variables together from the top to inside the main function like this:
public static int finished;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
System.out.println("");
System.out.println("When taking the quiztest you have only two seconds before making each guess");
match2 m = new match2();
finished = (match2.totalpoints + match3.iq);
System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + finished + " POINTS");
}
}
Thanks for all the help from everyone.
Smth. like this. You have lot's of code duplication
public class MatchRunner {
public static void main(String... args) throws InterruptedException {
new MatchRunner().start();
}
public void start() throws InterruptedException {
System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
System.out.println();
System.out.println("When taking the quiztest you have only two seconds before making each guess");
int totalPoints = new Match2().getTotalPoints();
System.out.println("For the next part of your IQ Assesment");
System.out.println("just type back the words in CAPSLOCK in CAPSLOCK");
int iq = new Match3().getIQ();
System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + (totalPoints + iq) + " POINTS");
}
}
public class Match2 {
public int getTotalPoints() throws InterruptedException {
try (Scanner scan = new Scanner(System.in)) {
int totalPoints = calc(scan, "first", "nice +1 try", "almost");
totalPoints += calc(scan, "next", "good", "almost");
totalPoints += calc(scan, "final", "great", "eeeh buzer sound");
printTotalPoints(totalPoints);
return totalPoints;
}
}
private static void countdown() throws InterruptedException {
for (int i = 5; i > 0; i--) {
Thread.sleep(750);
System.out.println(i + "...");
}
}
private static int calc(Scanner scan, String strSet, String strEqual, String strNotEqual) throws InterruptedException {
System.out.println("press ENTER for your " + strSet + " set...");
Random random = new Random();
scan.nextLine();
countdown();
int sum = 0;
for (int i = 0; i < 4; i++)
sum += random.nextInt(9) + 1;
System.out.println(sum);
for (int i = 0; i < 10; i++)
System.out.println();
int guess = scan.nextInt();
System.out.println(guess == sum ? strEqual : strNotEqual);
return guess == sum ? 1 : 0;
}
private static void printTotalPoints(int totalPoints) {
System.out.println();
if (totalPoints == 3)
System.out.println("YOU GOT THEM ALL");
else if (totalPoints <= 2 && totalPoints >= 1)
System.out.println("YOU MISSED A TOTAL OF " + (3 - totalPoints));
else if (totalPoints == 0)
System.out.println("HA! YOU MISSED THEM ALL");
}
}
public class Match3 {
public int getIQ() throws InterruptedException {
try (Scanner scan = new Scanner(System.in)) {
Random random = new Random();
Supplier<String> getWord1 = () -> getWord(random, "DOG", "CAT", "BIRD");
Supplier<String> getWord2 = () -> getWord(random, "FOOD", "MUD", "GRAINS");
Supplier<String> getWord3 = () -> getWord(random, "TRAM", "BUS", "BICYCLE");
Supplier<String> getWord4 = () -> getWord(random, "MALL", "PARK", "POOL");
int iq = calc(scan, getWord1, getWord2, "ate the");
iq += calc(scan, getWord1, getWord3, "drove the");
iq += calc(scan, getWord1, getWord4, "visited the");
printIq(iq);
return iq;
}
}
private static void countdown() throws InterruptedException {
System.out.println("READY...");
Thread.sleep(1000);
System.out.println("SET...");
Thread.sleep(1000);
}
public int calc(Scanner scan, Supplier<String> wordOne, Supplier<String> wordTwo, String strMsq) throws InterruptedException {
System.out.println("Press ENTER when ready");
scan.nextLine();
countdown();
String a = wordOne.get();
String b = wordTwo.get();
System.out.println("The " + a + ' ' + strMsq + ' ' + b);
String wordGroup = a + ' ' + b;
for (int i = 0; i <= 10; i++)
System.out.println();
String wordGuess = scan.nextLine();
System.out.println(wordGroup.equals(wordGuess) ? "awesome cock muncher a match" : "nope");
return wordGroup.equals(wordGuess) ? 1 : 0;
}
private static String getWord(Random random, String one, String two, String three) {
int cv = random.nextInt(3) + 1;
if (cv == 1)
return one;
if (cv == 2)
return two;
if (cv == 3)
return three;
return "";
}
public void printIq(int iq) {
System.out.println();
if (iq == 3)
System.out.println("YOU GOT THEM ALL");
else if (iq <= 2 || iq >= 1)
System.out.println("YOU MISSED A TOTAL OF " + (3 - iq));
else if (iq == 0)
System.out.println("HA! YOU MISSED THEM ALL");
}
}

How do I place code in IPO format?

I have written code for a program but I have not used methods in my code, and I was wondering how I would implement methods in the code?
I know the basic structure should have the Input, Processing, and Output.
It's all here:
import java.io.*;
public class Question {
public static void main(String[] args) throws IOException {
String name = null;
float mark, total, average, totalAverage = 0;
int totalNumberOfPeople = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println ("Average Calc.\n");
do {
total = 0;
System.out.print("Name: ");
try {
name = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
if(!name.equalsIgnoreCase("end")) {
totalNumberOfPeople++;
System.out.println("Enter marks for " + name + ".");
for(int i=1; i <= 5; i++) {
System.out.print("Enter mark #" + i + " of 5: ");
try {
mark = Float.parseFloat(br.readLine());
}
catch(NumberFormatException nfe) {
mark = 0;
}
catch (IOException e) {
mark = 0;
}
total = total + mark;
}
average = (float)total / 5;
System.out.println("\nThe average of the 5 marks entered is " + average);
totalAverage = totalAverage + average;
}
}
while(!name.equalsIgnoreCase("end"));
System.out.println("Total number of people = " + totalNumberOfPeople);
System.out.println("Final average = " + totalAverage / totalNumberOfPeople );
}
}
You may try to separate in methods like this :
import java.io.*;
public class Question {
public static void main(String[] args) throws IOException {
String name = null;
float mark, total, average, totalAverage = 0;
int totalNumberOfPeople = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println ("This program will calculate the average of five marks for each person.\n");
do {
total = 0;
name = readName(name, br);
if(!name.equalsIgnoreCase("end")) {
totalNumberOfPeople++;
total = getMarksForStudent(name, total, br);
totalAverage = calculateAverage(total, totalAverage);
}
}
while(!name.equalsIgnoreCase("end"));
printOutput(totalAverage, totalNumberOfPeople);
}
private static float getMarksForStudent(String name, float total, BufferedReader br) {
float mark;
System.out.println("\nPlease enter 5 marks for " + name + ".");
for(int i=1; i <= 5; i++) {
System.out.print("Enter mark #" + i + " of 5: ");
mark = getMark(br);
total = total + mark;
}
return total;
}
private static float calculateAverage(float total, float totalAverage) {
float average;
average = (float)total / 5;
System.out.println("\nThe average of the 5 marks entered is " + average);
totalAverage = totalAverage + average;
System.out.println("============================================================");
return totalAverage;
}
private static void printOutput(float totalAverage, int totalNumberOfPeople) {
System.out.println("============================================================");
System.out.println("Total number of people = " + totalNumberOfPeople);
System.out.println("The overall average for all the people entered = " + totalAverage / totalNumberOfPeople );
}
private static float getMark(BufferedReader br) {
float mark;
try {
mark = Float.parseFloat(br.readLine());
}
catch(NumberFormatException nfe) {
mark = 0;
}
catch (IOException e) {
mark = 0;
}
return mark;
}
private static String readName(String name, BufferedReader br) {
System.out.print("Please enter student name <or enter 'end' to exit> : ");
try {
name = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return name;
}
}

Speeding up Pythogrean triple calculator

So far my code runs fine, but I need a way to speed it up. When the user enters max_values to be 25000 it takes about 1.81 seconds and I need it to be less than one second. I tried my best to optimize my triples method but I don't know what else to do.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Pythagorean {
public static void triples(int max_values){
int x = 0;
for(int c = 5; c <= max_values; c++){
int cTwo = c * c;
int b = c - 1;
for (int a = 0;a <= cTwo - b*b;a++){
if (a*a + b*b == cTwo){
x++;
System.out.println(x + ") " + a + " " + b + " " +c);
}
}
}
}
public static void main(String[] args){
System.out.println("--- Pythagorean Triple Generator ---");
System.out.println();
Scanner input = new Scanner(System.in);
int max_value = 0;
System.out.print("Enter max value for c: ");
try{
max_value = input.nextInt();
} catch (InputMismatchException ime) {
input.nextLine();
System.err.println("Error: Input is not an integer.");
System.exit(1);
}
input.close();
long start = System.currentTimeMillis();
triples(max_value);
double elapsed = (System.currentTimeMillis() - start)/ 1000.0;
System.out.println("Searching complete...");
System.out.printf("Elpased time: %.3f\n", elapsed);
}
}
This just ran in 0.999 seconds on my PC.
It uses a single StringBuilder to collect all the output, then does just one println at the end.
public static void triples(final int max_values)
{
int x = 0;
final StringBuilder sb = new StringBuilder(24000);
for (int c = 5; c <= max_values; c++)
{
final int cTwo = c * c;
final int b = c - 1;
final int bTwo = b * b;
final int cTwoLessB = cTwo - bTwo;
for (int a = 0; a <= cTwoLessB; a++)
{
if (a * a + bTwo == cTwo)
{
x++;
sb.append(x);
sb.append(") ");
sb.append(a);
sb.append(" ");
sb.append(b);
sb.append(" ");
sb.append(c);
sb.append("\n");
}
}
}
System.out.println(sb.toString());
}
The bottleneck is most likely System.out.println. Writing to the console often takes time.
for (int a = 0;a <= cTwo - b*b;a++){
if (a*a + b*b == cTwo){
x++;
System.out.println(x + ") " + a + " " + b + " " +c);//Do you really need this?
}
}
Maybe you could store it in a collection and do the printing after the loop is done (or use Stringbuilder as suggested).
Some optimizations:
int multiplyB = b*b ;//multiplication can also be slow.
for (int a = 0;a <= cTwo - multiplyB;a++){
if (a*a + multiplyB == cTwo){
++x;//use preincrement operator
str.append(x ).append(") ").append(a).append( " ").append(b).append(" ").append(c).append("\n");
}
}

beginner lexical analyzer in java

I am writing a lexical analyzer. I know it's super simple. It runs but whenever enter an input, the program treats it as invalid characters (even when they are supposed to be valid). What did I do wrong?
import java.util.*;
import java.util.Scanner;
public class LAnalyze{
public static int i;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String s;
System.out.println("Input something to lexically analyze: ");
s = input.next( );
int j = 1;
if( s.charAt(i)!='a'||s.charAt(i)!='b'||s.charAt(i)!='c'||s.charAt(i)!='d'||s.charAt(i)!='e'||s.charAt(i)!='f'||
s.charAt(i)!='g'||s.charAt(i)!='h'||s.charAt(i)!='i'||s.charAt(i)!='j'||s.charAt(i)!='k'||s.charAt(i)!='l'||
s.charAt(i)!='m'||s.charAt(i)!='n'||s.charAt(i)!='o'||s.charAt(i)!='p'||s.charAt(i)!='q'||s.charAt(i)!='r'||
s.charAt(i)!='s'||s.charAt(i)!='t'||s.charAt(i)!='u'||s.charAt(i)!='v'||s.charAt(i)!='w'||s.charAt(i)!='x'||
s.charAt(i)!='y'||s.charAt(i)!='z'||s.charAt(i)!='A'||s.charAt(i)!='B'||s.charAt(i)!='C'||s.charAt(i)!='D'||
s.charAt(i)!='E'||s.charAt(i)!='F'||s.charAt(i)!='G'||s.charAt(i)!='H'||s.charAt(i)!='I'||s.charAt(i)!='J'||
s.charAt(i)!='K'||s.charAt(i)!='L'||s.charAt(i)!='M'||s.charAt(i)!='N'||s.charAt(i)!='O'||s.charAt(i)!='P'||
s.charAt(i)!='Q'||s.charAt(i)!='R'||s.charAt(i)!='S'||s.charAt(i)!='T'||s.charAt(i)!='U'||s.charAt(i)!='V'||
s.charAt(i)!='W'||s.charAt(i)!='X'||s.charAt(i)!='Y'||s.charAt(i)!='Z'||s.charAt(i)!='0'||s.charAt(i)!='1'||
s.charAt(i)!='2'||s.charAt(i)!='3'||s.charAt(i)!='4'||s.charAt(i)!='5'||s.charAt(i)!='6'||s.charAt(i)!='7'||
s.charAt(i)!='8'||s.charAt(i)!='9'||s.charAt(i)!='-'||s.charAt(i)!='_'||s.charAt(i)!=' ') {
for (int i = 0; i < s.length(); i++) {
System.out.println("Token " + j + " = " + (s.charAt(i)));
j++;
}
}
else {
System.out.println("Invalid character(s) entered.. Program terminated!\n");
System.exit(0);
}
}
}
It would seem that it is impossible to get the results you say you are getting from this code. Your if statement is wrong. As it currently stands, it will always be true. A character will always be not equal to some character or not equal to another character. All of the != should be ==. I would also print out the bad character in the else part that reports it:
System.out.println("bad character " + s.charAt(i) +
" decimal value: " + (int) s.charAt(i));
Scanner does lexing on its own, that is, it returns tokens, not the whole string. I think you should use Console and get everything that was typed:
Console console = System.console();
s = console.readLine("Input something to lexically analyze: ");
import java.util.*;
public class Main {
static int i;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String s = "";
while (true) {
System.out.println("Input something to lexically analyze: ");
s = input.nextLine();
analize(s);
}
}
public static void analize(String s) {
String t = "-1234567890_ abcdefjhijklmnopqrstuvwxyzABCDEFJHIJKLMNOPQRSTUVWXYZ";
char[] tt = t.toCharArray();
char[] cc = s.toCharArray();
int z = 1, i = 0, j = 0;
for (i = 0; i < cc.length; i++) {
for (j = 0; j < tt.length; j++) {
if (cc[i] == tt[j]) {
System.out.println("Token " + z + " = '" + cc[i] + "'");
z++;
break;
}
}
if (j > tt.length - 1) {
System.out.println("Invalid character " + (i + 1) + " ('" + cc[i] + "') entered...");
}
}
}
}

Categories