What i am striving to achieve: Given a simple equation, you should output the correct value for variable "x". The equation has two numbers greater than 0 and variable "x", and between these can be "+", "-" or "=". Numbers, variable "x", symbols "+", "-", "=" all separated by a space.
the problem: when i read the numbers they come out as strings instead of integers
I am very new to codeing and tried this but i don't get why when i use var and input a number it reads it as a string instead of an integer
import java.util.*;
public class Main {
public static void main(String[] args) {
int outpt;
Scanner scanner = new Scanner(System.in);
var sig1 = scanner.next();
var sig2 = scanner.next();
var sig3 = scanner.next();
var sig4 = scanner.next();
var sig5 = scanner.next();
if(sig2 == "=")
{
if(sig1 == (int)sig1)
{
if(sig3 == (int)sig3)
{
if(sig4 == "-")
{
outpt = sig3 - sig1;
System.out.println("");
System.out.println(outpt);
}
else
{
outpt = sig1 - sig3;
System.out.println("");
System.out.println(outpt);
}
}
else
{
if(sig4 == "-")
{
outpt = sig5 + sig1;
System.out.println("");
System.out.println(outpt);
}
else
{
outpt = sig1 - sig5;
System.out.println("");
System.out.println(outpt);
}
}
}
else
{
if(sig4 == "-")
{
outpt = sig3 - sig5;
System.out.println("");
System.out.println(outpt);
}
else
{
outpt = sig3 + sig5;
System.out.println("");
System.out.println(outpt);
}
}
}
else
{
if(sig5 == (int)sig5)
{
if(sig1 == (int)sig1)
{
if(sig2 == "+")
{
outpt = sig5 - sig1;
System.out.println("");
System.out.println(outpt);
}
else
{
outpt = sig1 - sig5;
System.out.println("");
System.out.println(outpt);
}
}
else
{
if(sig2 == "+")
{
outpt = sig5 - sig3;
System.out.println("");
System.out.println(outpt);
}
else
{
outpt = sig3 + sig5;
System.out.println("");
System.out.println(outpt);
}
}
}
else
{
if(sig2 == "+")
{
outpt = sig1 + sig3;
System.out.println("");
System.out.println(outpt);
}
else
{
outpt = sig1 - sig3;
System.out.println("");
System.out.println(outpt);
}
}
}
}
}
Sample Input 1:
5 + x = 15
Sample Output 1:
10
Sample Input 2:
x - 8 = 10
Sample Output 2:
18
Sample Input 3:
x = 20 - 15
Sample Output 3:
5
Instead of using 100 if statements try this. In my code I am taking whole equation as input and storing it in array and then saving the position of symbols and numbers in variables which I can later use the decide what operation I should perform
Here is the code
import java.util.Scanner;
public class AlgebraEquation {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the whole equation: ");
String equation = scan.nextLine();
scan.close();
String[] equationSplit = equation.split(" ");
// This code block is just to show how logic is working
for (int i = 0; i < equationSplit.length; i++) {
System.out.print(equationSplit[i] + ", ");
}
System.out.println();
int xPosition = -1, const1Pos = -1, const2Pos = -1, equalPos = -1, operatorPos = -1;
// Checking each index of array and saving position of characters
for (int i = 0; i < equationSplit.length; i++) {
if (equationSplit[i].equalsIgnoreCase("X")) {
xPosition = i;
} else if (equationSplit[i].equals("=")) {
equalPos = i;
} else if (equationSplit[i].matches("[-+*/]")) { // If character matches any of these "-+*/"
operatorPos = i;
} else {
// Checking if const1Pos is filled or not
if (const1Pos < 0) {
const1Pos = i;
} else {
const2Pos = i;
}
}
}
// This code block is just to show how logic is working
System.out.println(equationSplit[xPosition] + " Position: " + xPosition);
System.out.println(equationSplit[equalPos] + " Position: " + equalPos);
System.out.println(equationSplit[operatorPos] + " Position: " + operatorPos);
System.out.println(equationSplit[const1Pos] + " Position: " + const1Pos);
System.out.println(equationSplit[const2Pos] + " Position: " + const2Pos);
String operator = equationSplit[operatorPos];
switch (operator) {
case "+":
System.out.println("Addition");
// Do you calculation based on relative position of equal, const1Pos, and
// const2Pos
break;
case "-":
System.out.println("Subtraction");
break;
case "*":
System.out.println("Multiplication");
break;
case "/":
System.out.println("Division");
break;
}
}
}
Output
Enter the whole equation: 5 + x = 8 //(Enter Key Pressed)
5, +, x, =, 8,
x Position: 2
= Position: 3
+ Position: 1
5 Position: 0
8 Position: 4
Addition
this is the final code it came to
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.next();
String b = scanner.next();
String c = scanner.next();
String d = scanner.next();
String e = scanner.next();
if (b.equals("+") && a.equals("x")) {
System.out.println(Integer.parseInt(e) - Integer.parseInt(c));
} else if (b.equals("+") && c.equals("x")) {
System.out.println(Integer.parseInt(e) - Integer.parseInt(a));
} else if (b.equals("-") && a.equals("x")) {
System.out.println(Integer.parseInt(e) + Integer.parseInt(c));
} else if (b.equals("-") && c.equals("x")) {
System.out.println(Integer.parseInt(a) - Integer.parseInt(e));
} else if (d.equals("+") && c.equals("x")) {
System.out.println(Integer.parseInt(a) - Integer.parseInt(e));
} else if (d.equals("+") && e.equals("x")) {
System.out.println(Integer.parseInt(a) - Integer.parseInt(c));
} else if (d.equals("-") && c.equals("x")) {
System.out.println(Integer.parseInt(a) + Integer.parseInt(e));
} else if (d.equals("-") && e.equals("x")) {
System.out.println(Integer.parseInt(c) - Integer.parseInt(a));
} else if (b.equals("+") && e.equals("x")) {
System.out.println(Integer.parseInt(c) + Integer.parseInt(a));
} else if (d.equals("+") && a.equals("x")) {
System.out.println(Integer.parseInt(c) + Integer.parseInt(e));
} else if (b.equals("-") && e.equals("x")) {
System.out.println(Integer.parseInt(a) - Integer.parseInt(c));
} else if (d.equals("-") && a.equals("x")) {
System.out.println(Integer.parseInt(c) - Integer.parseInt(e));
}
}
}
Related
Have a task to get N numbers from console, find the longest and the shortest ones and their length. The task is not difficult and works correctly, but I decided to make a check, if the console input corresponds the conditions of the task:
Are there only Integer numbers.
Are the exactly N numbers, not more/less.
I decided to write a boolean method isInputCorrect(), which would take the Scanner and check if the input is correct, but it doesn't work correctly.
public static void main(String[] args) {
int n = 5;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Hello, please enter " + n + " integer numbers:");
while (!isInputCorrect(sc,n)){
System.out.println("Wrong! Try again:");
sc.next();
}
} while (!isInputCorrect(sc, 5));
String scLine = sc.nextLine();
String[] arr = scLine.split("\\s+");
String maxLengthNum = arr[0];
String minLengthNum = arr[0];
for (int i = 1; i < arr.length; i++){
if (maxLengthNum.length() < arr[i].length()){
maxLengthNum = arr[i];
}
if (minLengthNum.length() > arr[i].length()){
minLengthNum = arr[i];
}
}
String equalMaxNum = "";
String equalMinNum = "";
int countMax = 0;
int countMin = 0;
for (String s : arr){
if (maxLengthNum.length() == s.length()){
countMax += 1;
equalMaxNum += s + " ";
}
if (minLengthNum.length() == s.length()){
countMin += 1;
equalMinNum += s + " ";
}
}
if (countMax > 1){
System.out.println("The longest numbers are: " + equalMaxNum + " Their length is: " + maxLengthNum.length());
}
else {
System.out.println("The longest number is: " + maxLengthNum + " Its length is: " + maxLengthNum.length());
}
if (countMin > 1){
System.out.println("The shortest numbers are: " + equalMinNum + " Their length is: " + minLengthNum.length());
}
else {
System.out.println("The shortest number is: " + minLengthNum + " Its length is: " + minLengthNum.length());
}
}
public static boolean isInputCorrect(Scanner sc, int n){
boolean flag = true;
for (int i = 0; i < n; i++){
if (sc.hasNextInt()){
sc.next();
}else {
flag = false;
break;
}
}
return flag;
}
EDIT
This code still doesn't work. I realize, that the problem is in isDigit(). And exactly in regular conditions in last if statement. It is something like this:
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else {
for (String s : arr) {
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")) {
flag = true;
}
} else if (s.matches("[0-9]*")) {
flag = true;
} else {
flag = false;
}
}
}
return flag;
}
This method takes the console input as a string, then it checks, how many numbers(strings) does it contain, are there any negative numbers and so on. But it can be applied only for substrings(words without whitespace). In my case it can be applied to arr[i].
So I modified it to split String into array[] and tried to check every single element. I've got:
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else {
for (String s : arr) {
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")) {
flag = true;
}
} else if (s.matches("[0-9]*")) {
flag = true;
} else {
flag = false;
}
}
}
return flag;
}
but it returnes true even when input is:
1 3213 w 15 3
I can't understand, what is the problem? The full code is:
public static void main(String[] args) {
int n = 5;
boolean validInput = false;
String input;
do {
System.out.println("Please enter " + n + " integer numbers:");
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
if (isDigit(input, n)) {
validInput = true;
} else {
System.out.println("Wrong input! Try again: ");
}
}
while (!validInput);
String[] arr = input.split("\\s+");
String maxLengthNum = arr[0];
String minLengthNum = arr[0];
for (int i = 1; i < arr.length; i++){
if (maxLengthNum.length() < arr[i].length()){
maxLengthNum = arr[i];
}
if (minLengthNum.length() > arr[i].length()){
minLengthNum = arr[i];
}
}
String equalMaxNum = "";
String equalMinNum = "";
int countMax = 0;
int countMin = 0;
for (String s : arr){
if (maxLengthNum.length() == s.length()){
countMax += 1;
equalMaxNum += s + " ";
}
if (minLengthNum.length() == s.length()){
countMin += 1;
equalMinNum += s + " ";
}
}
if (countMax > 1){
System.out.println("The longest numbers are: " + equalMaxNum + " Their length is: " + maxLengthNum.length());
}
else {
System.out.println("The longest number is: " + maxLengthNum + " Its length is: " + maxLengthNum.length());
}
if (countMin > 1){
System.out.println("The shortest numbers are: " + equalMinNum + " Their length is: " + minLengthNum.length());
}
else {
System.out.println("The shortest number is: " + minLengthNum + " Its length is: " + minLengthNum.length());
}
}
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else {
for (String s : arr) {
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")) {
flag = true;
}
} else if (s.matches("[0-9]*")) {
flag = true;
} else {
flag = false;
}
}
}
return flag;
}
SOLVED
Thanks to everybody, your help was really usefull. I finally found the problem
It was in isDigit() method. It was checking out every element of array, and switched a flag according to the last result. I wrote "break" to stop the further checking if there was at least one false flag in loop.
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else{
for (String s: arr){
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")){
flag = true;
}
else {
flag = false;
break;
}
}
else {
if (s.matches("[0-9]*")){
flag = true;
}
else {
flag = false;
break;
}
}
}
}
return flag;
}
You may use regular expressions to verify that the input contains only integer numbers:
int n = 5;
// ... your current code
String scLine = sc.nextLine();
if (!scLine.matches("\\d+(?:\\s+\\d+)*")) {
throw new IllegalArgumentException("input contained non-integers");
}
String[] arr = scLine.split("\\s+");
if (arr.length != n) {
throw new IllegalArgumentException("found " + arr.length + " number inputs but expected " + n + ".");
}
you can check if input string has only numbers as below
public boolean isDigit(String input) {
if (input == null || input.length() < 0)
return false;
input = input.trim();
if ("".equals(input))
return false;
if (input.startsWith("-")) {
return input.substring(1).matches("[0-9]*");
} else {
return input.matches("[0-9]*");
}
}
EDIT:
allowing user to re-enter untill valid number is entered
boolean validInput = false;
do
{
System.out.println("Enter the number ");
// get user input
String input sc.nextLine();
if(isDigit(input))
validInput = true;
else
System.out.println("Enter valid Number");
}
while (!validInput );
i have a exercice to do in Java. I need to create a World Cup tournament and the restriction is that the program will restart until my favourite team win. However, if my team didn't win after 20 times, the program stop
The problem is when I try to put the second restriction (20 times max) with a for after the while (true), I always get an infinite loop.
//Q1
String[] teams16 = {"Uruguay", "Portugal", "France", "Argentina", "Brazil", "Mexico",
"Belgium", "Japan", "Spain", "Russia", "Croatia", "Denmark", "Sweden", "Switzerland",
"Colombia", "England"};
//data
Scanner keyboard = new Scanner(System.in);
Random result = new Random();
System.out.print("Enter your favourite team: ");
String team = keyboard.nextLine();
boolean teamwc = false;
// choice of the favourite team
for (int i = 0 ; i < 16 ; i++ ) {
if (teams16[i].equalsIgnoreCase(team)) {
teamwc = true;
}
}
if(teamwc == false) {
System.out.println("Your team is not in the Round of 16 ");
}
// the tournament begins (ROUND OF 16)
while (true) {
if (teamwc == true) {
int z = 0;
String[] winnerof16 = new String[8];
int a = 0;
System.out.print("ROUND OF 16:");
for (int i = 0; i < 16 ; i+=2) {
int score1 = result.nextInt(5);
int score2 = result.nextInt(5);
if (score1 > score2) {
winnerof16 [a] = teams16[i];
}
else if (score1 < score2) {
winnerof16[a] = teams16[i+1];
} else if (score1 == score2) {
Random overtime = new Random();
int ot = overtime.nextInt(2);
if (ot == 0) {
score1++;
winnerof16[a] = teams16[i];
} else if (ot == 1) {
score2++;
winnerof16[a]=teams16[i+1];
}
}
System.out.print("["+teams16[i] +"]"+ " " + score1+":"+score2 + " " + "["+teams16[i+1]+"]" + " ");
a++;
}
System.out.println();
String[] winnerof8 = new String[4];
int b = 0;
System.out.print("QUARTER-FINALS:");
for (int k = 0 ; k < 8 ; k+=2) {
int score3 = result.nextInt(5);
int score4 = result.nextInt(5);
if (score3 > score4) {
winnerof8[b]=winnerof16[k];
}
else if (score3 < score4) {
winnerof8[b] = winnerof16[k+1];
} else if (score3 == score4) {
Random overtime2 = new Random();
int ot2 = overtime2.nextInt(2);
if (ot2 == 0) {
score3++;
winnerof8[b]=winnerof16[k];
} else if (ot2 == 1) {
score4++;
winnerof8[b]=winnerof16[k+1];
}
}
System.out.print("["+winnerof16[k] +"]"+ " " + score3+":"+score4 + " " + "["+winnerof16[k+1]+"]" + " ");
b++;
}
System.out.println();
String[] winnerof4 = new String[2];
int c = 0;
System.out.print("SEMI-FINALS:");
for (int l = 0 ; l < 4 ; l+=2) {
int score5 = result.nextInt(5);
int score6 = result.nextInt(5);
if (score5 > score6) {
winnerof4[c]=winnerof8[l];
}
else if (score5 < score6) {
winnerof4[c] = winnerof8[l+1];
} else if (score5 == score6) {
Random overtime3 = new Random();
int ot3 = overtime3.nextInt(2);
if (ot3 == 0) {
score5++;
winnerof4[c]=winnerof8[l];
} else if (ot3 == 1) {
score6++;
winnerof4[c]=winnerof8[l+1];
}
}
System.out.print("["+winnerof8[l] +"]"+ " " + score5+":"+score6 + " " + "["+winnerof8[l+1]+"]" + " ");
c++;
}
System.out.println();
String[] winnerof2 = new String[1];
int d = 0;
System.out.print("FINALS:");
for (int m = 0 ; m < 2 ; m+=2) {
int score7 = result.nextInt(5);
int score8 = result.nextInt(5);
if (score7 > score8) {
winnerof2[d]=winnerof4[m];
}
else if (score7 < score8) {
winnerof2[d] = winnerof4[m+1];
} else if (score7 == score8) {
Random overtime4 = new Random();
int ot4 = overtime4.nextInt(2);
if (ot4 == 0) {
score7++;
winnerof2[d]=winnerof4[m];
} else if (ot4 == 1) {
score8++;
winnerof2[d]=winnerof4[m+1];
}
}
System.out.print("["+winnerof4[m] +"]"+ " " + score7+":"+score8 + " " + "["+winnerof4[m+1]+"]" + " ");
System.out.println();
}
System.out.println("Tournament: " + z + " The WINNER is: " + winnerof2[d]);
z++;
if (winnerof2[d].equalsIgnoreCase(team)) {
break;
}
}
}
}
}
This is my code before I put the second restriction.
Is there a problem with my code ? How can I put the second restriction ? Thank you
The infinite loop is due to this 2:
while (true) { // it will quit while loop only when an exception raised
if (teamwc == true) { // after this you nowhere assign teamwc == false therefore it is always true
instead of direct assigning True to while loop, use a boolean variable or a condition to quit somewhere:
t = true
while(t):
OR
while n>0:
I'm trying to implement a DiceThrowingGame which works fine. I have 2 classes currently which are "Player" and "Game". The code for the Game class is as below:
package dice.throwing.game;
import java.util.Scanner;
public class Game {
private int winningPoints;
private Player player1, player2;
private boolean gameSetup;
private final String defaultWinningScore = "200";
public Game() {
this.setWinningPoints(200);
this.gameSetup = false;
}
private int readScore(Scanner scanner) {
String score = "";
try {
score = scanner.nextLine();
if (score.isEmpty()) {
score = this.defaultWinningScore;
}
} catch (Exception e) {
}
return Integer.parseInt(score);
}
private Player createPlayer(Scanner scanner) {
String name = null;
do {
try {
name = scanner.nextLine();
if (name.isEmpty()) {
System.err.println("Name cannot be empty. Try again: ");
}
} catch (Exception e) {
}
} while (name.isEmpty());
return new Player(name);
}
private void startGame(Scanner scanner) {
System.out.println("Enter first player's name: ");
player1 = createPlayer(scanner);
System.out.println("Enter second player's name: ");
player2 = createPlayer(scanner);
System.out.println("Maximum score to win (<Enter> to use default 200): ");
this.setWinningPoints(this.readScore(scanner));
this.gameSetup = true;
}
private void playOneRound() {
int p1r1, p1r2, p2r1, p2r2;
p1r1 = (int) (1 + ((Math.random() * 10) % 6));
p1r2 = (int) (1 + ((Math.random() * 10) % 6));
p2r1 = (int) (1 + ((Math.random() * 10) % 6));
p2r2 = (int) (1 + ((Math.random() * 10) % 6));
int p1Points, p2Points;
boolean p1Bonus = false, p2Bonus = false;
p1Points = p1r1 + p1r2;
p2Points = p2r1 + p2r2;
if (p1r1 == p1r2) {
p1Points *= 2;
p1Bonus = true;
}
if (p2r1 == p2r2) {
p2Points *= 2;
p2Bonus = true;
}
player1.setTotalPoints(player1.getTotalPoints() + p1Points);
player2.setTotalPoints(player2.getTotalPoints() + p2Points);
System.out.print(player1.getName() + " rolled " + p1r1 + " + " + p1r2 + ", and scored " + p1Points + " points");
if (p1Bonus)
System.out.println(" (BONUS!)");
else
System.out.println();
System.out.print(player2.getName() + " rolled " + p2r1 + " + " + p2r2 + ", and scored " + p2Points + " points");
if (p2Bonus)
System.out.println(" (BONUS!)");
else
System.out.println();
}
private void leaderBoard() {
int p1Points = player1.getTotalPoints();
int p2Points = player2.getTotalPoints();
if (p1Points == p2Points)
System.out.println("Both players have the same score (" + p1Points + ") at the moment");
else {
System.out.print(player1.getName() + "'s current score is " + p1Points);
if (p1Points > p2Points)
System.out.println(" <--- CURRENT LEADER!");
else
System.out.println();
System.out.print(player2.getName() + "'s current score is " + p2Points);
if (p1Points < p2Points)
System.out.println(" <--- CURRENT LEADER!");
else
System.out.println();
}
}
private void gameHelp() {
System.out.println("<ENTER SOME HELP TEXT HERE>");
}
private boolean isGameOver() {
int player1Points = player1.getTotalPoints();
int player2Points = player2.getTotalPoints();
if(player1Points == player2Points &&
player1Points > this.winningPoints) {
System.out.println("Game Over! It's a draw!");
return true;
} else if(player1Points > this.winningPoints && player1Points > player2Points) {
System.out.println("Game Over! " + player1.getName() + " is the winner!");
return true;
} else if(player2Points > this.winningPoints && player2Points > player1Points) {
System.out.println("Game Over! " + player2.getName() + " is the winner!");
return true;
}
return false;
}
private void eventLoop() {
Scanner scanner = new Scanner(System.in);
int choice = 0;
boolean exit = false;
while (!exit) {
System.out.println("Welcome to my Dice-and-Roll Game!");
System.out.println("==============================");
System.out.println("(1) Start a new game");
System.out.println("(2) Play one round");
System.out.println("(3) Who is leading now?");
System.out.println("(4) Display Game Help");
System.out.println("(5) Exit Game");
System.out.println("Choose an option: ");
try {
choice = Integer.parseInt(scanner.nextLine());
if (choice < 1 || choice > 5) {
System.err.println("Error : Choose an option between 1 and 5");
choice = 0;
}
} catch (NumberFormatException e) {
System.err.println("Error : Choose an option between 1 and 5");
choice = 0;
}
if (!this.gameSetup && (choice == 2 || choice == 3)) {
System.err.println("Error : Players have not been setup");
choice = 0;
}
switch (choice) {
case 1:
this.startGame(scanner);
break;
case 2:
this.playOneRound();
break;
case 3:
this.leaderBoard();
break;
case 4:
this.gameHelp();
break;
case 5:
exit = true;
}
if(this.gameSetup && this.isGameOver()) {
System.out.println("Exiting now.. See you later!");
exit = true;
}
}
scanner.close();
}
public static void main(String[] args) {
Game game = new Game();
game.eventLoop();
}
public int getWinningPoints() {
return winningPoints;
}
public void setWinningPoints(int winningPoints) {
this.winningPoints = winningPoints;
}
}
But I want to move the DiceThrowing part of the code to another class called "Dice" which is this part:
private void playOneRound() {
int p1r1, p1r2, p2r1, p2r2;
p1r1 = (int) (1 + ((Math.random() * 10) % 6));
p1r2 = (int) (1 + ((Math.random() * 10) % 6));
p2r1 = (int) (1 + ((Math.random() * 10) % 6));
p2r2 = (int) (1 + ((Math.random() * 10) % 6));
Confused on whether to put the whole playOneRound() method or just the Math.Random line?
To keep responsibilities and abstractions separate:
I would have a method Dice.getNumber() which would return the result of
(int) (1 + ((Math.random() * 10) % 6));
You could also have a 2nd method that would return an array of dice throws with a nbOfThrows parameter.
Then the playOneRound() would involve the throw of the dice as many times as the games rules allow.
Input from the Java commandline: "4 + 6 + 5 - 5".
Wanted outcome: "is 10".
Actual outcome: "is 5".
class Calculator
{
int v_in1, v_in2, v_in3, v_in4, v_answer, result;
String v_sign1, v_sign2, v_sign3;
public Calculator()
{
}
public void count(String[] args)
{
for(int i = 0; i < args.length; i++)
{
//System.out.print(args[i]+ " ");
if(i == 0 || i % 2 == 0)
{
v_in1 = Integer.parseInt(args[i]);
//System.out.print(v_in1 + " ");
}
switch(args[i])
{
case "+": {
v_answer += v_in1;
break;
}
case "-": {
v_answer -= v_in1;
break;
}
}
}
System.out.print("is " + v_answer);
}
}
There might be some additional problems e.g too many variable declared etc, but what I'm concerned about it the for- if- switch part, I'm unable to pin- point the problem.
Thank you :)
The problem is that you are applying the operation to the previous number, not to the next to come. Instead you should memorize the operator and update the result when you see a number, e.g. like this:
int sign = +1, result = 0;
for (String arg : args) {
switch (arg) {
case "+":
sign = +1;
break;
case "-":
sign = -1;
break;
default:
result += sign * Integer.parseInt(arg);
}
}
This is happening because your last integer wont be taken into account as it is just stored in v_in1, but since there is no +,- so it doesnt get added or subtracted. Try this:
for(int i = 0; i < args.length; i++)
{
//System.out.print(args[i]+ " ");
if(i == 0 || i % 2 == 0)
{
v_in1 = Integer.parseInt(args[i]);
//System.out.print(v_in1 + " ");
}
switch(args[i])
{
case "+":
{
v_answer = v_in1 + Integer.parseInt(args[i+1]) + v_answer;
i++;
break;
}
case "-":
{
v_answer = v_in1 - Integer.parseInt(args[i+1]) + v_answer;
i++;
break;
}
}
}
I do not know all requirements for this task, but I recommend to convert the whole expression to postfix notation, then parse it using stack to evaluate the result.
I took a look at your method, and I recommend you simplify your code (something like this for long count(String[] args))
long result = 0; // Note, this shadows your Object's result. I'm not sure why you
// had hard-coded fields like that. I don't think you need them.
// Also, this returns a long.
boolean negative = false;
for (String arg : args) {
String oper = arg.trim();
if (oper.equals("+")) { // Is it a plus sign?
negative = false;
} else if (oper.equals("-")) { // Is it a minus sign?
negative = !negative; // - a negative value is addition
} else {
try {
int i = Integer.parseInt(oper); // Parse the integer
if (negative) {
i = -i;
negative = false;
}
result += i; // add the result
} catch (NumberFormatException nfe) {
System.err.println(oper + " is not +, - or a number");
}
}
}
return result;
This is what worked in the exercise.
class Calculator
{
int v_answer = 0;
int v_in1 = 0;
public Calculator()
{
}
public void count(String args[])
{
System.out.println();
System.out.print("Result of the calculation ");
for(int i = 0; i < args.length; i++)
{
System.out.print(args[i]+ " ");
if(i % 2 == 0)
{
v_in1 = Integer.parseInt(args[i]);
}
if(i == 0)
{
v_answer += Integer.parseInt(args[0]);
}
if(args[i].equals("+"))
{
v_answer += Integer.parseInt(args[i+1]);
}
else if(args[i].equals("-"))
{
v_answer -= Integer.parseInt(args[i+1]);
}
}
System.out.print("is " + v_answer);
System.out.println();
}
}
I need to convert hexadecimal to decimal using different methods. When I enter numbers that are correct hexadecimal numbers, my program displays the decimal value and says that the number is valid. However, when I enter incorrect hexadecimal values, my program crashes.
Here is my code:
import java.io.*;
import java.util.Scanner;
public class pg3a {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
String hex;
char choice = 'y';
boolean isValid = false;
do {
System.out.print("Do you want to enter a hexadecimal number? ");
System.out.print("y or n?: ");
choice = keyboard.next().charAt(0);
switch(choice){
case 'y':
System.out.print("Enter a hexadecimal number: #");
hex = keyboard.next();
hex = hex.toUpperCase();
int hexLength = hex.length();
isValid = valid(hex);
Integer value = Integer.parseInt(hex,16);
System.out.println("The value: " + value);
if (isValid) {
System.out.println(hex + " is valid");
}
break;
case 'n':
System.out.print("Quit");
}
}while (choice != 'n');
}
public static boolean valid (String validString) {
int a = 0;
if (validString.charAt(0) == '-') {
a = 1;
}
for (int i=a; i< validString.length(); i++) {
if (!((validString.charAt(i) >= 'A' && validString.charAt(i) <= 'F')|| (validString.charAt(i) >= 0 && validString.charAt(i) <= 9)))
{
return false;
}
}
return true;
}
public static long convert (String hexValue) {
long decimal = 0;
boolean isNegative = false;
int a = 0;
if (hexValue.charAt(0) == '-') {
isNegative = true;
a = 1;
}
for (int i = a; i<hexValue.length(); i++) {
decimal = decimal*16;
if (hexValue.charAt(i) >= '0' && hexValue.charAt(i) <= '9') {
decimal += hexValue.charAt(i) - '0';
}
else if (hexValue.charAt(i) >= 'a' && hexValue.charAt(i) <= 'f') {
decimal += hexValue.charAt(i) - 'a' + 10;
}
}
if (isNegative == true) {
decimal *= -1;
}
return decimal;
}
}
why is it crashing and how can I fix it so that it displays "invalid" when incorrect hexadecimal digits are entered?
If you enter an invalid hex number, Integer.parseInt() will throw NumberFormatException. Change your code like this:
...
isValid = valid(hex);
if (isValid) {
Integer value = Integer.parseInt(hex,16);
System.out.println("The value: " + value);
System.out.println(hex + " is valid");
}
...
do {
System.out.print("Do you want to enter a hexadecimal number? ");
System.out.print("y or n?: ");
choice = keyboard.next().charAt(0);
int base = 10;
switch(choice)
{
case 'y':
System.out.print("Enter a hexadecimal number: #");
hex = keyboard.next();
hex = hex.toUpperCase(); //I'm not sure if this step is necessary
try {
Integer value = Integer.parseInt(hex, 16);
System.out.println("Valid hex format");
System.out.println("Hex: " + hex);
System.out.println("Decimal: " + value);
}
catch (NumberFormatException e) {
System.out.println("Invalid hex format");
System.out.println("Input: " + hex);
}
break;
case 'n':
System.out.print("Quit");
break
}
} while (choice != 'n');
Now you can delete all your helper methods
Add Integer value = Integer.parseInt(hex,16); inside if statement and print invalid in else block.
if (isValid) {
Integer value = Integer.parseInt(hex,16);
System.out.println("The value: " + value);
System.out.println(hex + " is valid");
}
else{
System.out.println("invalid");
}
Updated:
Change your valid method as follows:
public static boolean valid(String validString) {
int a = 0;
if (validString.charAt(0) == '-') {
a = 1;
}
for (int i = a; i < validString.length(); i++) {
// if (!((validString.charAt(i) >= 'A' && validString.charAt(i) <= 'F') || (validString.charAt(i) >= 0 && validString.charAt(i) <= 9))) {
// return false;
// }
char ch=validString.charAt(i);
if(!(Character.isDigit(ch) || (Character.isLetter(ch) && ((ch-'A')<=5))) ){
return false;
}
}
return true;
}