import java.util.Scanner;
public class ComparingNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int FirstNum = Integer.valueOf(scanner.nextLine());
int SecondNum = Integer.valueOf(scanner.nextLine());
if (FirstNum > SecondNum) {
System.out.println(FirstNum + " is greater than " + SecondNum + ".");
} else if (FirstNum < SecondNum) {
System.out.println(FirstNum + " is smaller than " + SecondNum + ".");
} else {
System.out.println(FirstNum + " is equal to " + SecondNum + ".");
}
}
}
Line 9: Name 'FirstNum' must match pattern '^[a-z][a-zA-Z0-9]$'.
Line 10: Name 'SecondNum' must match pattern '^[a-z][a-zA-Z0-9]$'.
What is the issue with my variable names?. I am a beginner so a simple answer will be greatly appreciated.
Java variable names should be camelCase. Variable names should be firstNum and secondNum.
Related
im not too sure how you add a loop statement to this. I want it to be a while loop that makes it do that the calculations repeat after finishing. I've tried but it just keeps on giving me errors. ive tried doing While statements but just will not work im not sure how you set it up as my teacher did not explain very well
import com.godtsoft.diyjava.DIYWindow;
public class Calculator extends DIYWindow {
public Calculator() {
// getting number one
double number1 = promptForDouble("Enter a number");
//getting number2
int number2 = promptForInt("Enter an integer");
//getting what to do with operation
print("What do you want to do with these numbers?\nAdd\tSubtract\tMultiply\tDivide");
String operation = input();
//declaring variable here so the same one can be used
double answer = 0;
switch(operation) {
case "add":
answer = number1 + number2;
print(number1 + " + " + number2 + " = " + answer);
break;
case "subtract":
answer = number1 - number2;
print(number1 + " - " + number2 + " = " + answer);
break;
case "multiply":
answer = number1 * number2;
print(number1 + " * " + number2 + " = " + answer);
break;
case "divide":
try {
answer = number1 / number2;
}
catch(ArithmeticException e) {
print("A number cannot be divided by 0.");
}
print(number1 + " / " + number2 + " = " + answer);
break;
}
double double1 = promptForDouble("Enter a number");
double double2 = promptForDouble("Enter another number");
double double3 = promptForDouble("Enter one last number");
print("What do you want to do with these numbers?\nAdd\tSubtrack\tMultiply\tDivide");
String operation2 = input();
double answer2 = 0;
switch(operation2) {
case "add":
answer2 = double1 + double2 + double3;
print(double1 + " + " + double2 + " + " + double3 + " = " + answer2);
break;
case "subtract":
answer2 = double1 - double2 - double3;
print(double1 + " - " + double2 + " - " + double3 + " = " + answer2);
break;
case "multiply":
answer2 = double1 * double2 * double3;
print(double1 + " * " + double2 + " * " + double3 + " = " + answer2);
break;
case "divide":
try {
answer2 = double1 / double2 / double3;
}
catch(ArithmeticException e) {
print("A number cannot be divided by 0.");
}
print(double1 + " / " + double2 + " / " + double3 + " = " + answer2);
break;
}
want it to loop after the code on top
}
private double promptForDouble(String prompt) {
double number1 = 0;
print(prompt);
String number = input();
try {
number1 = Double.parseDouble(number);
}
catch(NumberFormatException e){
print("That is not a number. Please enter a number.");
number1 = promptForDouble(prompt);
}
return number1;
}
private int promptForInt(String prompt) {
int number2 = 0;
print(prompt);
String number = input();
try {
number2 = Integer.parseInt(number); }
catch(NumberFormatException e) {
print("That is not an integer. Enter an integer.");
number2 = promptForInt(prompt); }
return number2;
}
public static void main(String[] args) {
new Calculator();
}
}
Put this in your main method:
while (true)
{
Thread.sleep(1000); // optional, make some deplay for more nature
new Calculator();
}
Or you can wrap all body blocks of the constructor inside the above while statement.
This question already has answers here:
Java: Ternary with no return. (For method calling)
(6 answers)
Closed 4 years ago.
In userInput.equals("0") ? part both resulting expressions return void type. Why then it tells me that the expression returns String?
import java.util.Scanner;
public class BaseConverter {
private static final int SENTINEL = 0;
public static void main(String args[]) {
askInput();
}
private static void askInput() {
Scanner reader = new Scanner(System.in);
String userInput;
System.out.println("This is converter");
System.out.println("0 to stop");
while(true) {
System.out.print("Enter hex: ");
userInput = reader.nextLine();
userInput.equals("0") ? break : System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
}
}
}
You must switch from ternary operator to if/else statement
if(userInput.equals("0")) {
break;
} else {
System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
}
This code can be reduced to:
if(userInput.equals("0")) {
break;
}
System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
You cannot use the ternary operator like that, instead do this:
if(userInput.equals("0")) break;
System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
In your case, it's better to use use do{} while() loop like this :
do {
System.out.print("Enter hex: ");
userInput = reader.nextLine();
System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
} while (!userInput.equals("0"));
Which mean, repeat until userInput should equal to 0, you don't need to use break in this case.
For a better solution, you still need to use try and catch to avoid NumberFormatException :
do {
System.out.print("Enter hex: ");
userInput = reader.nextLine();
try {
System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal");
} catch (NumberFormatException e) {
System.out.println("Incorrect Number");
}
} while (!userInput.equals("0"));
For my current programming project I am supposed to format my testOne & testTwo like "000". While the average is supposed to be "000.0". I have used DecimalFormat to no avail. Furthermore for my letterGradeArray the letter won't display even though the letter grade is in the actual array. Here is my code:
import java.util.Scanner;
//import java.text.NumberFormat;
import java.text.DecimalFormat;
public class GradeArray
{
#SuppressWarnings({ "unused", "resource" })
public static void main(String[] args)
{
//Setup all the variables
Scanner scan = new Scanner(System.in);
int[] testOne = new int[4]; // Students’ test one grades
int[] testTwo = new int[4]; // Students’ test two grades
double[] average = new double[4]; // Students’ average grades
double z = 002.00;
char letterGrade = 0;
char[] letterGradeArray = new char[4];
DecimalFormat fmt1 = new DecimalFormat("000");
DecimalFormat fmt2 = new DecimalFormat("000.0");
//Begin asking for scores
System.out.println("For test 1,");
for (int i=0;i<testOne.length;i++)
{
System.out.print("Enter score " + (i + 1) + ":");
testOne[i] = scan.nextInt();
fmt1.format(testOne[i]);
}
System.out.println("\nFor test 2,");
for (int i=0;i<testTwo.length;i++)
{
System.out.print("Enter score " + (i + 1) + ":");
testTwo[i] = scan.nextInt();
fmt1.format(testTwo[i]);
}
//Compute average
for(int i=0;i<average.length;i++)
{
{
average[i] = (testOne[i]+testTwo[i])/z;
fmt2.format(average[i]);
}
}
//Compute letter grade
for(int i=0;i<average.length;i++)
{
if (average[i]>= 90 )
{
letterGrade = 'A';
} else if (average[i] >= 80) {
letterGrade = 'B';
} else if (average[i] >= 70) {
letterGrade = 'C';
} else if (average[i] >= 60) {
letterGrade = 'D';
} else {
letterGrade = 'F';
}
//Put the letterGrade into the letterGradeArray
for(int x=0;i<letterGradeArray[x];x++)
{
letterGradeArray[x]=letterGrade;
}
}
//Print it out
System.out.println("Test 1 Test 2 Average Grade");
System.out.println("______ ______ _______ _____");
System.out.println(testOne[0] + " " + testTwo[0] + " " + average[0] +" " + letterGradeArray[0]);
System.out.println(testOne[1] + " " + testTwo[1] + " " + average[1] +" " + letterGradeArray[1]);
System.out.println(testOne[2] + " " + testTwo[2] + " " + average[2] +" " + letterGradeArray[2]);
System.out.println(testOne[3] + " " + testTwo[3] + " " + average[3] +" " + letterGradeArray[3]);
}
}
If anyone has any ideas on how to make this code cleaner do tell me, I feel with all the fors it is clunky.
You are calling fmt1.format(testOne[i]); but you are not doing anything with the result. Calling format returns a String, it does not affect the thing being passed as a parameter, so when you later print testOne[0] etc. you are printing the plain, original, values.
If you want the formatted values you will have to assign the return of .format() to something, keep it around, and print it instead of the original integer values. For example, patterned after how the rest of your code works...
String[] formattedOne = new String[4];
// ... later
formattedOne[i] = fmt1.format(testOne[i]);
// ... still later
System.out.println(formattedOne[0] + " " ..........
import java.util.Random;
import java.util.Scanner;
public class LotteryGame{
public static void main(String[] args) {
int NUM_DIGITS = 6;
int[] userDigits = new int[NUM_DIGITS];
int[] lotteryNumbers = new int[NUM_DIGITS];
int sameNum;
generateNumbers(lotteryNumbers);
getUserData(userDigits);
sameNum = compareArrays(lotteryNumbers, userDigits);
System.out.println("Winning numbers: " + lotteryNumbers[0] + " "
+ lotteryNumbers[1] + " " + lotteryNumbers[2] + " "
+ lotteryNumbers[3] + " " + lotteryNumbers[4] + " " + lotteryNumbers[5] + " ");
System.out.println("Your numbers: " + userDigits[0] + " "
+ userDigits[1] + " " + userDigits[2] + " " + userDigits[3]
+ " " + userDigits[4] + " " + userDigits[5] +" ");
System.out.println("Number of matching digits: " + sameNum);
if (sameNum == 6) {
System.out.println("First prize!!!");
}
if (sameNum == 5) {
System.out.println("Second prize!!!");
}
if (sameNum == 0) {
System.out.println("No matching numbers, you lost.");
}
}
public static void generateNumbers(int[] lotteryNumbers) {
Random randNum = new Random();
lotteryNumbers[0] = randNum.nextInt(59);
lotteryNumbers[1] = randNum.nextInt(59);
lotteryNumbers[2] = randNum.nextInt(59);
lotteryNumbers[3] = randNum.nextInt(59);
lotteryNumbers[4] = randNum.nextInt(59);
lotteryNumbers[5] = randNum.nextInt(59);
return lotteryNumbers[5];
}
public static void getUserData(int[] userDigits) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter first digit: ");
userDigits[0] = keyboard.nextInt();
System.out.print("Enter second digit: ");
userDigits[1] = keyboard.nextInt();
System.out.print("Enter third digit: ");
userDigits[2] = keyboard.nextInt();
System.out.print("Enter fourth digit: ");
userDigits[3] = keyboard.nextInt();
System.out.print("Enter fifth digit: ");
userDigits[4] = keyboard.nextInt();
System.out.print("Enter sixth digit: ");
userDigits[5] = keyboard.nextInt();
return userDigits[5];
}
public static int compareArrays(int[] userDigits, int[] lotteryNumbers) {
int sameNum = 0;
for (int i = 0; i < 6; i++) {
for (int x = 0; x < 5; x++) {
if (lotteryNumbers[i] == userDigits[x]) {
sameNum++;
}
}
}
return sameNum;
}
}
When I compile I get the following errors-
LotteryGame.java:51: error: incompatible types: unexpected return value
return lotteryNumbers[5];
^
LotteryGame.java:72: error: incompatible types: unexpected return value
return userDigits[5];
^
2 errors
Can any of you help me with these compilation errors? I'm trying to get this to work. The user is supposed to input 6 numbers, and the program is supposed to pick randomly 6 numbers. Using these numbers, the program will compare the numbers with echoed input.
generateNumbers and getUserData are void functions, meaning they don't return anything, so you can't return anything from them.
You probably want to declare them as functions returning int instead:
public static int generateNumbers(int[] lotteryNumbers)
Univerio is correct in answering your original question.
Looking at your test code you might consider removing the return statement on those two functions since you are just populating both arrays.
My program is not allowing me to enter user input if i do not enter a number and i want to go through the program again, it think its due to a hanging token somewhere but i cannot seem to find it.
import java.util.Scanner;
public class LessonTwo {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
char answer = ' ';
do {
System.out.print("Your favorite number: ");
if (userInput.hasNextInt()) {
int numberEntered = userInput.nextInt();
userInput.nextLine();
System.out.println("You entered " + numberEntered);
int numEnteredTimes2 = numberEntered + numberEntered;
System.out.println(numberEntered + " + " + numberEntered
+ " = " + numEnteredTimes2);
int numEnteredMinus2 = numberEntered - 2;
System.out.println(numberEntered + " - 2 " + " = "
+ numEnteredMinus2);
int numEnteredTimesSelf = numberEntered * numberEntered;
System.out.println(numberEntered + " * " + numberEntered
+ " = " + numEnteredTimesSelf);
double numEnteredDivide2 = (double) numberEntered / 2;
System.out.println(numberEntered + " / 2 " + " = "
+ numEnteredDivide2);
int numEnteredRemainder = numberEntered % 2;
System.out.println(numberEntered + " % 2 " + " = "
+ numEnteredRemainder);
numberEntered += 2; // *= /= %= Also work
numberEntered -= 2;
numberEntered++;
numberEntered--;
int numEnteredABS = Math.abs(numberEntered); // Returns the
int whichIsBigger = Math.max(5, 7);
int whichIsSmaller = Math.min(5, 7);
double numSqrt = Math.sqrt(5.23);
int numCeiling = (int) Math.ceil(5.23);
System.out.println("Ceiling: " + numCeiling);
int numFloor = (int) Math.floor(5.23);
System.out.println("Floor: " + numFloor);
int numRound = (int) Math.round(5.23);
System.out.println("Rounded: " + numRound);
int randomNumber = (int) (Math.random() * 10);
System.out.println("A random number " + randomNumber);
} else {
System.out.println("Sorry you must enter an integer");
}
System.out.print("Would you like to try again? ");
answer = userInput.next().charAt(0);
}while(Character.toUpperCase(answer) == 'Y');
System.exit(0);
}
}
Yes you are right you need to consume the characters first after the user inputted character in the nextInt before allowing the user to input data again
just add this in your else block and it will work:
else {
System.out.println("Sorry you must enter an integer");
userInput.nextLine(); //will consume the character that was inputted in the `nextInt`
}
EDIT:
change this:
answer = userInput.next().charAt(0);
to:
answer = userInput.nextLine().charAt(0);