How can I use throw exception in this context? - java

So for this assignment, it asks the user to enter a phone number, then it splits the number up into a category of each set of integers. What I'm attempting to do is to throw a simple exception that if they do not enter the parenthesis for the area code that it throws the exception but doesn't crash the program and asks them to re-enter using the correct format
public class App{
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
String inputNum;
String token1[];
String token2[];
String areaCode;
String preFix;
String lineNum;
String fullNum;
System.out.print("Enter a phone number in (123) 123-4567 format: ");
inputNum = input.nextLine();
System.out.println();
token1 = inputNum.split(" ");
areaCode = token1[0].substring(1, 4);
if (token1[0].substring(0, 3) != "()"){
throw new Exception("Enter a phone number in (123) 123-4567 format: ");
}
token2 = token1[1].split("-");
preFix = token2[0];
lineNum = token2[1];
fullNum = "(" + areaCode + ")" + " " + preFix + "-" + lineNum ;
System.out.print("Area code: " + areaCode + "\n");
System.out.print("Prefix: " + preFix + "\n");
System.out.print("Line number: " + lineNum + "\n");
System.out.print("Full number: " + fullNum);
}
}

No need to throw. Just keep asking in a loop.
String areaCode;
String preFix;
String lineNum;
while (true) {
System.out.print("Enter a phone number in (123) 123-4567 format: ");
String inputNum = input.nextLine();
System.out.println();
String [] token1 = inputNum.split(" ");
if (token1.length == 2 && token1[0].length() == 5
&& token1[0].charAt(0) == '(' && token1[0].charAt(4) == ')') {
areaCode = token1[0].substring(1, 4);
String [] token2 = token1[1].split("-");
if (token2.length == 2 && token2[0].length() == 3 && token2[1].length() == 4) {
preFix = token2[0];
lineNum = token2[1];
// If we reach this line all is ok. Exit the loop.
break;
}
}
}
String fullNum = "(" + areaCode + ")" + " " + preFix + "-" + lineNum ;
System.out.print("Area code: " + areaCode + "\n");
System.out.print("Prefix: " + preFix + "\n");
System.out.print("Line number: " + lineNum + "\n");
System.out.print("Full number: " + fullNum);

Related

Code for Simple Arithmetic

I am new to programming, first year college of BSIT and we were tasked to code a SimpleArithmetic where it will ask your name first and after that you will be asked to enter the first and the second integer.
After giving what is asked it must show "Hello (the name that was entered)" then what follows next is the sum, difference, product and the mod of the two integers and lastly it will show "Thank You!".
I tried a lot of codes but I will not run, so can someone help me? I would appreciate it really because I really want to learn how would that happen.
This was my code
public class SimpleArithmetic{
public static void main(String[] args){
//1: Declare name as symbol
//2: num 1, num 2, sum, difference, product, mod to 0;
System.out.print("Enter your name: ");
name = in.next(); // <---- HERE
System.out.printf("\nEnter first integer: ");
System.out.printf("\nEnter second integer: ");
System.out.printf("\nnum 1 + num 2");
System.out.printf("\nnum 1 - num 2");
System.out.printf("\nnum 1 * num 2");
System.out.printf("\nnum 1 % num 2");
System.out.print("Hello \n + name");
System.out.println("num 1" + "+" + "is" + "sum");
System.out.println("num 1" + "-" + "is" + "difference");
System.out.println("num 1" + "*" + "is" + "product");
System.out.println("num 1" + "%" + "is" + "mod");
System.out.print("Thank You!");
}
}
The bold one was the error when I tried to compile the java file
Use the class Scanner as below to read input:
Scanner scanner = new Scanner(System.in); // Init scanner
String name = scanner.nextLine(); // Reads a full line
int a = scanner.nextInt(); // Reads one integer
int b = scanner.nextInt(); // Reads another integer
Check documentation here if you like to know more about the class Scanner.
Basically Scanner is a useful class to read input from a stream (System.in) in that case. From javadoc
A simple text scanner which can parse primitive types and strings
using regular expressions.
The following will work for you...
package com.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SimpleArithmetic{
public static void main(String[] args){
try{
//1: Declare name as symbol
//2: num 1, num 2, sum, difference, product, mod to 0;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = in.readLine(); // <---- HERE
System.out.printf("\nEnter first integer: ");
String str1 = in.readLine();
int number1 = Integer.parseInt(str1);
System.out.printf("\nEnter second integer: ");
String str2 = in.readLine();
int number2 = Integer.parseInt(str2);
System.out.print("Hello \n "+ name);
System.out.println("num 1" + "+" + "is" + (number1 + number2));
System.out.println("num 1" + "-" + "is" + (number1 - number2));
System.out.println("num 1" + "*" + "is" + (number1 * number2));
System.out.println("num 1" + "%" + "is" + (number1 % number2));
System.out.print("Thank You!");
}catch(Exception e)
{
e.printStackTrace();
}
}
}
Remove all the double qoutes on variables.
change System.out.print("Hello \n + name"); to
System.out.print("Hello \n + name);
System.out.println("num 1" + "+" + "is" + "sum"); to System.out.println("num 1" + "+" + "is" + sum);
System.out.println("num 1" + "-" + "is" + "difference"); to `System.out.println("num 1" + "-" + "is" + difference);`
System.out.println("num 1" + "*" + "is" + "product"); to System.out.println("num 1" + "*" + "is" + product);
System.out.println("num 1" + "%" + "is" + "mod"); to `System.out.println("num 1" + "%" + "is" + mod);`
Use Scanner and try catch block:
There is no declaration of variables which is listed in assignment comments.
You should have done something similar to this:
import java.util.Scanner;
public class SimpleArithmetic {
int num1 = 0, num2 = 0, sum = 0, difference = 0, product = 0, mod = 0;
String name = null;
Scanner in = null;
public static void main(String[] args) {
SimpleArithmetic sa = new SimpleArithmetic();
try {
sa.doSimpleArithmetic();
} catch (Exception e) {
e.printStackTrace();
}
}
void doSimpleArithmetic() throws Exception {
in = new Scanner(System.in);
System.out.print("Enter your name: ");
name = in.nextLine();
System.out.printf("\nEnter first integer: ");
num1 = Integer.parseInt(in.nextLine());
System.out.printf("\nEnter second integer: ");
num2 = Integer.parseInt(in.nextLine());
sum = num1 + num2;
difference = num1 - num2;
product = num1 * num2;
mod = num1 / num2;
System.out.println("\n" + "Hello " + name + "\n");
System.out.println(num1 + " + " + num2 + " is :" + sum);
System.out.println(num1 + " - " + num2 + " is :" + difference);
System.out.println(num1 + " * " + num2 + " is :" + product);
System.out.println(num1 + " % " + num2 + " is :" + mod);
System.out.println("\n" + "Thank You!");
in.close();
}
}
try {
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine(); // <---- HERE
System.out.printf("\nEnter first integer: ");
int nnum1=Integer.parseInt(in.nextLine());
System.out.printf("\nEnter second integer: ");
int nnum2=Integer.parseInt(in.nextLine());
System.out.println("Hello \n" + name);
System.out.println("num 1" + "+" + "is " + (nnum1 + nnum2));
System.out.println("num 1" + "-" + "is " + (nnum1 - nnum2));
System.out.println("num 1" + "*" + "is " + (nnum1 * nnum2));
System.out.println("num 1" + "%" + "is " + (nnum1 % nnum2));
System.out.print("Thank You!");
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
System.out.println("Please enter valid number");
e.printStackTrace();
}

java user input assigned to variable can't be an integer to be divided?

So I can't get the variables to be divisible, I need to be able to do this, otherwise I don't know of a way to finish building the lock that I want to build.
It uses 20 inputted numbers, and then arranges them into a Algebra2/calculus system of equations, and then solves for the "s", "a", "f", and "e" it starts by removing "e" from the equation by substituting.
I would greatly appreciate help, I'm open to ideas as well, because sofar I have 25 of these to build, and this is only 1/3 of the first one.
In short, how do I divide variables?
import java.util.Scanner;
public class Lock
{
public static void main(String[] args) {
Scanner user_input = new Scanner (System.in);
String num_a;
System.out.print("Enter the first number: ");
num_a = user_input.next();
String num_b;
System.out.print("Enter the second number: ");
num_b = user_input.next();
String num_c;
System.out.print("Enter the third number: ");
num_c = user_input.next();
String num_d;
System.out.print("Enter the fourth number: ");
num_d = user_input.next();
String num_e;
System.out.print("Enter the fifth number: ");
num_e = user_input.next();
String num_f;
System.out.print("Enter the sixth number: ");
num_f = user_input.next();
String num_g;
System.out.print("Enter the seventh number: ");
num_g = user_input.next();
String num_h;
System.out.print("Enter the eigth number: ");
num_h = user_input.next();
String num_i;
System.out.print("Enter the ninth number: ");
num_i = user_input.next();
String num_j;
System.out.print("Enter the tenth number: ");
num_j = user_input.next();
String num_k;
System.out.print("Enter the eleventh number: ");
num_k = user_input.next();
String num_l;
System.out.print("Enter the twetlth number: ");
num_l = user_input.next();
String num_m;
System.out.print("Enter the thirteenth number: ");
num_m = user_input.next();
String num_n;
System.out.print("Enter the fourteenth number: ");
num_n = user_input.next();
String num_o;
System.out.print("Enter the fifteenth number: ");
num_o = user_input.next();
String num_p;
System.out.print("Enter the sixteenth number: ");
num_p = user_input.next();
String num_q;
System.out.print("Enter the seventeenth number: ");
num_q = user_input.next();
String num_r;
System.out.print("Enter the eighteenth number: ");
num_r = user_input.next();
String num_s;
System.out.print("Enter the nineteenth number: ");
num_s = user_input.next();
String num_t;
System.out.print("Enter the twentieth number: ");
num_t = user_input.next();
System.out.println(num_a + "s + " + num_b + "a + " + num_c + "f + " + num_d + "e = " + num_e);
System.out.println(num_f + "s + " + num_g + "a + " + num_h + "f + " + num_i + "e = " + num_j);
System.out.println(num_k + "s + " + num_l + "a + " + num_m + "f + " + num_n + "e = " + num_o);
System.out.println(num_p + "s + " + num_q + "a + " + num_r + "f + " + num_s + "e = " + num_t);
System.out.println(num_a + "s + " + num_b + "a + " + num_c + "f + " + num_d + "[(" + num_t + " " + num_p + "s + " + num_q + "a " + num_r + "f) / " + num_s + "] =" + num_e);
System.out.println(num_f + "s + " + num_g + "a + " + num_h + "f + " + num_i + "[(" + num_t + " " + num_p + "s + " + num_q + "a " + num_r + "f) / " + num_s + "] =" + num_j);
System.out.println(num_k + "s + " + num_l + "a + " + num_m + "f + " + num_n + "[(" + num_t + " " + num_p + "s + " + num_q + "a " + num_r + "f) / " + num_s + "] =" + num_o);
// THIS creates the fourth equation items/order to be substituted into the other first three equations.
int t = num_t;
int s = num_s;
int num_ts = (t / s);
num_ts =
num_ps = (num_p / num_s);
num_qs = (num_q / num_s);
num_rs = (num_r / num_s);
// THIS is the Fourth equation being substituted into the First Equation
num_dts = (num_d * num_ts);
num_dps = (num_d * num_ps);
num_dqs = (num_d * num_qs);
num_drs = (num_d * num_rs);
// THIS is the Fourth equation being substituted into the Second Equation
num_its = (num_i * num_ts);
num_ips = (num_i * num_ps);
num_iqs = (num_i * num_qs);
num_irs = (num_i * num_rs);
// THIS is the fourth equation being substituted into the Third Equation
num_nts = (num_n * num_ts);
num_nps = (num_n * num_ps);
num_nqs = (num_n * num_qs);
num_nrs = (num_n * num_rs);
System.out.println(num_a + "s + " + num_b + "a + " + num_c + "f + " + num_dts + " " + num_dps + "s + " + num_dqs + "a " + num_drs + "f = " + num_e);
System.out.println(num_f + "s + " + num_g + "a + " + num_h + "f + " + num_its + " " + num_ips + "s + " + num_iqs + "a " + num_irs + "f = " + num_j);
System.out.println(num_k + "s + " + num_l + "a + " + num_m + "f + " + num_nts + " " + num_nps + "s + " + num_nqs + "a " + num_nrs + "f = " + num_o);
}
}
You can't add, subtract, divide, or multiply String variables. You have to make your variables into ints in order to do that. Also, you can use an array to hold your variables, since there is so many of them.
String, Integer, Float, are not the same types. you can't apply operators like / or * on String for instance. + is special because it has a definition for String, which means concatenate.
Since you need to do some operations on the user inputs, you can read them directly as int:
System.out.print("Enter the first number: ");
int num_a = user_input.nextInt();
System.out.print("Enter the second number: ");
int num_b = user_input.nextInt();
Then you can do
int num_ab = a / b;
Note that if a < b, then num_ab will be 0, since this is an integer. You may want to do something like
float num_ab = (float)a / b;
Now, this code is quite tedious. If you accept to handle indices instead of letters for the variables, you can initialise them in a loop, e.g.
Scanner in = new Scanner(System.in);
int[] numbers = new int[20];
int index = 0;
while (index < numbers.length) {
System.out.println("Enter the "+(index+1)+"th number");
int n = in.nextInt();
numbers[index] = n;
index++;
}
System.out.println(Arrays.toString(numbers));
And use the array of numbers
// arrays start at 0
int num_ab = numbers[0] / numbers[1];
And if you want to be able to access the variables through names, you can define constants
static final int a = 0;
static final int b = 1;
static final int c = 2;
//...
int num_ab = numbers[a] / numbers[b];
But in your case, it may be handy to store initial variables and computed ones in some place where you can retrieve them for further computations:
// the store for all the variables and their value
static Map<String, Integer> vars = new HashMap<>();
// the function to read in the store
static Integer var(String name) {
return vars.get(name);
}
The store is initialised by a loop:
Scanner in = new Scanner(System.in);
// The 20 variables...
String alpha = "abcdefghijklmnopqrst";
for (char c : alpha.toCharArray()) {
String varName = String.valueOf(c);
System.out.println("Enter the value for "+ varName);
int n = in.nextInt();
vars.put(varName, n);
}
System.out.println(vars.toString());
int num_ab = var("a")/var("b");
// Store ab for further computation
vars.put("ab", num_ab);
System.out.println("ab is " + var("ab");

Finding median word length of text file with multiple lines

I have a text file, and I want to find the middle word of the whole file and print the number of characters it has. I can do this for one line:
System.out.println("'" + str[tok / 2] + "'");
But I don't know how to point to a certain line. Here is all of my code:
import java.io.*;
import java.text.*;
import java.util.*;
public class AmendClassify {
public static void main(String[] args) {
try {
System.out.println("Please enter the file name:");
Scanner sc = new Scanner(System.in);
String file = sc.next();
file = file + ".txt";
Scanner s = new Scanner(new FileReader(file));
System.out.println("You are scanning '" + file + "'");
PrintWriter output = new PrintWriter(new FileOutputStream("output.txt"));
double lineNum = 0;
double wordCount = 0;
double charCount = 0;
int tok = 0;
String str[] = null;
DecimalFormat df = new DecimalFormat("#.#");
String line = null;
while (s.hasNextLine()) {
line = s.nextLine();
lineNum++;
str = line.split((" "));
tok = str.length;
for (int i = 0; i < str.length; i++) {
if (str[i].length() > 0) {
wordCount++;
}
}
charCount += (line.length());
}
double density = (charCount / wordCount);
System.out.println("'" + str[tok / 2] + "'"); // middle word of the 1st/last line
gap();
System.out.println("Number of lines: " + lineNum);
System.out.println("Number of words: " + wordCount);
System.out.println("Number of characters: " + charCount);
gap();
System.out.println("The DENSITY of the text is: " + df.format(density));
System.out.println();
int critical;
System.out.println("Do you want to alter the critical value(Y/N)");
String answer = sc.next();
if (answer.equals("y") || answer.equals("Y")) {
System.out.println("Please enter a value: ");
critical = sc.nextInt();
} else {
critical = 6;
}
//So...
if (density > critical) {
System.out.println("NAME: '" + file + "'" + ", DENSITY: " + df.format(density) + ", TYPE: " + "Heavy");
} else {
System.out.println("NAME: '" + file + "'" + ", DENSITY: " + df.format(density) + ", TYPE: " + "Light");
}
System.out.print("--FINISHED--");
s.close();
output.close();
sc.close();
} //end of try
catch (FileNotFoundException e) {
System.out.println("Please enter a valid file name");
}
} // end of main
public static void gap() {
System.out.println("------------------------------");
}
}
A text file I have used to test is
Hello my name is Harry. This line contains 83 characters, 15 words, and 1 line(s).
This is the second line.
This is the third line.
This is the fourth line.
Since this looks like a homework assignment I'd recommend reading the entire file into a String and then removing all new-line characters with replaceAll() if need be (depending how you read the entire file into a String). You then would effectively have a single line ... so your existing code would work (taking into account that the middle word would actually be the word to the left of the middle if the file has an even number of words).
Note that this is not an optimal solution though. Don't use it at work.

How can I use a while to continuously ask for input from a user and exit the program when "quit" is typed without using system.exit()?

I am currently taking an AP Computer Science class in my school and I ran into a little trouble with one of my projects! The project requires me to create a calculator that can evaluate an expression and then solve it. I have got most of that down, but I ran into a little trouble because my teacher asked me to use a while loop to continuously ask for input and display the answer, and I am stuck on that. To end the program the user has to type in "quit" and I can't use system.exit() or any cheating thing like that, the program has to just run out of code. Does anyone have any tips?
import java.util.*;
public class Calculator {
public static void main(String[] args) {
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
next();
}
public static void next() {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
next3(expression);
}
public static void next3(String expression) {
while (!expression.equals("quit")) {
next2(expression);
next();
}
}
public static void next2(String expression) {
if (OperatorFor2OperandExpressions(expression).equals("+")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) + SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("*")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) * SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("-")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) - SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("/")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) / SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("^")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + Math.pow(FirstOperandFor2OperandExpressions(expression),SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("|")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.abs(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("v")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sqrt(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("~")) {
double x = 0.0;
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + (Math.round(OperandFor1OperatorExpressions(expression))+ x));
}
else if (OperatorFor1OperandExpressions(expression).equals("s")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sin(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("c")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.cos(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("t")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.tan(OperandFor1OperatorExpressions(expression)));
}
}
public static double FirstOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static double SecondOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[2];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static String OperatorFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
return OperandOrOperator;
}
public static String OperatorFor1OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
return OperandOrOperator;
}
public static double OperandFor1OperatorExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static boolean QuitFunction(String expression) {
if (expression.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
return false;
}
else {
return true;
}
}
}
Take a look at this code. I think this might help you in the right direction. It's similar to what you have already written except it eliminates the need for method calls in your while loop.
Scanner input = new Scanner(System.in);
while (!input.hasNext("quit")) {
String expression = input.nextLine(); // gets the next line from the Scanner
next2(expression); // process the input
}
// once the value "quit" has been entered, the while loop terminates
System.out.println("Goodbye");
Writing it this way drastically cleans up your code and prevents a new declaration of Scanner kb = new Scanner(System.in); each time an input is processed.

Having trouble with program output an printf [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I am writing a program where it takes a file and tries to use data from the file in order to create an output.
this is the program:
import java.util.Scanner;
import java.io.*;
public class WebberProjectTest
{
public static void main(String[] args) throws IOException
{
Scanner scanner = new Scanner(new File("portlandvip.txt"));
while (scanner.hasNext())
{
String firstName = scanner.next();
String lastName = scanner.next();
Integer number = scanner.nextInt();
String ticketType = scanner.next();
if(ticketType == "Court")
{
Integer a = 75 * number;
System.out.println(" " + firstName + " " + lastName + " " + a);
scanner.nextLine();
}
if(ticketType == "Box")
{
Integer a = 50 * number;
System.out.println(" " + firstName + " " + lastName + " " + a);
scanner.nextLine();
}
if(ticketType == "Club")
{
Integer a = 40 * number;
System.out.println(" " + firstName + " " + lastName + " " + a);
scanner.nextLine();
}
}
}
}
This is the data file:
Loras Tyrell 5 Club
Margaery Tyrell 8 Box
Roslin Frey 2 Box
Sansa Stark 2 Club
Jon Snow 5 Club
Edmure Tully 3 Box
Joffrey Baratheon 20 Court
Stannis Baratheon 4 Club
Jaime Lannister 2 Box
Cersei Lannister 1 Court
Beric Dondarrion 8 Court
Balon Greyjoy 16 Box
Olenna Tyrell 4 Court
Mace Tyrell 5 Box
Tyrion Lannister 2 Club
Sandor Clegane 2 Court
Gregor Clegane 6 Club
Samwell Tarly 3 Club
Petyr Baelish 6 Court
The purpose of this program is to that the input File and output for example.
Input: Loras Tyrell 5 Court
Output: Loras Tyrell $375.00
However, when i run the program, nothing happens. I have a few ideas on why this is happening, but i dont know how to fix it, any help would be appreciated.
I also have another question about printf statements. I altered the program so that it prints correctly, but now i have to change the println statements to printf statements. this is what i changed the program to look like now:
import java.util.Scanner;
import java.io.*;
public class WebberProjectTest
{
public static void main(String[] args) throws IOException
{
Scanner scanner = new Scanner(new File("portlandvip.txt"));
while(scanner.hasNext())
{
String line = scanner.nextLine();
String[] words = line.split(" ");
if(words[3].equals("Court"))
{
int a = 75 * Integer.parseInt(words[2]);
System.out.printf(" " + words[0] + " " + words[1] + " $%.2f\n ", a);
}
if(words[3].equals("Box"))
{
int a = 50 * Integer.parseInt(words[2]);
System.out.printf(" " + words[0] + " " + words[1] + " $%.2f\n", a);
}
if(words[3].equals("Club"))
{
int a = 40 * Integer.parseInt(words[2]);
System.out.printf(" " + words[0] + " " + words[1] + " $%.2f\n", a);
}
}
}
}
and this is what prints out:
Loras Tyrell Loras Tyrell $java.util.IllegalFormatConversionException: f != java.lang.Integer
at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
at java.util.Formatter$FormatSpecifier.printFloat(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at java.io.PrintStream.printf(Unknown Source)
at WebberProjectTest.main(WebberProjectTest.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
I dont know what i did wrong in the printf statement, thank you for any assistance.
Try reading line at once and then split the elements.. Something like this
while(inp.hasNext()) {
String line = inp.nextLine();
String[] words = line.split(" ");
if(words[3].equals("Court")) {
int a = 75 * Integer.parseInt(words[2]);
System.out.println(" " + words[0] + " " + words[1] + " " + a);
}
// ....other if conditions
if(inp.hasNext()) //to skip over empty line
inp.nextLine();
}
Strings should be compared with the equals() method instead of the == operator. e.g.,
ticketType.equals("Court") //instead of ==> ticketType == "Court"
Try this code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class test {
/**
* #param args
*/
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File("test.txt"));
while (scanner.hasNext()){
String string = scanner.useDelimiter("\n").next();
if(!string.equals(" ") && !string.equals("\n") && !string.equals("") && !string.equals("\r") ){
StringTokenizer st = new StringTokenizer(string," ");
String firstName = "";
String lastName = "";
Integer number = 0;
String ticketType = "";
while (st.hasMoreElements()) {
firstName = st.nextElement().toString();
lastName = st.nextElement().toString();
number = Integer.parseInt(st.nextElement().toString());
ticketType = st.nextElement().toString().trim();
System.out.println(" " + firstName + " " + lastName + " " + number + " " +ticketType);
}
if(ticketType.equalsIgnoreCase("Court"))
{
Integer a = 75 * number;
System.out.println(" " + firstName + " " + lastName + " " + a);
}
else if(ticketType.equalsIgnoreCase("Box"))
{
Integer a = 50 * number;
System.out.println(" " + firstName + " " + lastName + " " + a);
}
else if(ticketType.equalsIgnoreCase("Club"))
{
Integer a = 40 * number;
System.out.println(" " + firstName + " " + lastName + " " + a);
}
}//if(!string.equals(" "))
}//while
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories