Solving error for iterative program - java

i was trying to create an iterative program with user input, copied from this textbook of mine but on the returns i keep getting an error of: " Multiple markers at this line - The primitive type int of a does not have a field b -
Syntax error on token ",", . expected"
import java.util.Scanner;
public class Code3 {
public static void main (String [] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter A: ");
int a = scanner.nextInt();
System.out.println("Enter B: ");
int b = scanner.nextInt();
if (a==b)
return;
if (a>b)
return (a-b, b);
else
return (a, b-a);
}
}

public static void main (String [] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter A: ");
int a = scanner.nextInt();
System.out.println("Enter B: ");
int b = scanner.nextInt();
if (a>b) {
System.out.println("Results: " + (a-b) + ", " + b);
} else if(a < b) {
System.out.println("Results: " + a + ", " + (b-a));
}
}

Related

Why can I not do sum of a and b?

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
int a = sc.nextInt();
boolean aValid = sc.hasNextInt();
System.out.println(aValid);
System.out.println("Enter Second number");
int b = sc.nextInt();
boolean bValid = sc.hasNextInt();
System.out.println(bValid);
if(aValid && bValid){
System.out.println("Sum of number is "+(a+b));
}
else{
System.out.println("Enter integer number");
}
}
}
I try to get input of a and b and validate that a and b are integers. But it takes three input. It gives the sum of the first two numbers and gives the validity of the last two.
you need to place check integer statements before taking input
boolean aValid = sc.hasNextInt();
int a = sc.nextInt();
boolean bValid = sc.hasNextInt();
int b = sc.nextInt();
Running this code makes the error fairly obvious. Some additional debug statements, running the code in debug or testing would also make it clear.
Scanner.nextInt() will throw an exception if it gets a non integer.
Scanner.hasNextInt() on the other hand returns a boolean value to warn you in advance whether it has an integer or not - it does not take the value from the Scanner.
This code has a couple of tiny corrections that will achieve the outcome you stated.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a = 0;
int b = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
boolean aValid = sc.hasNextInt();
if (aValid) {
a = sc.nextInt();
} else {
sc.next(); //Discard the non-integer input.fr
}
System.out.println(aValid);
System.out.println("Enter Second number");
boolean bValid = sc.hasNextInt();
if (bValid) {
b = sc.nextInt();
}
System.out.println(bValid);
if (aValid && bValid) {
System.out.println("Sum of number is " + (a + b));
} else {
System.out.println("Enter integer numbers only");
}
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
int a = 0;
int b = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
boolean aValid = sc.hasNextInt();
if (aValid) {
a = sc.nextInt();
}
System.out.println(aValid);
System.out.println("Enter Second number");
boolean bValid = sc.hasNextInt();
if (bValid) {
b = sc.nextInt();
}
System.out.println(bValid);
if (aValid && bValid) {
System.out.println("Sum of number is " + (a + b));
} else {
System.out.println("Enter integer numbers only");
}
}
}

So my problem in this is that I cannot seem to add a void function in my code

I want to insert a void function in my code.
import java.util.*;
public class javellana {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input String: ");
String str = scan.nextLine();
System.out.println("Input character: ");
char str1 = scan.next().charAt(0);
int num = str.length();
int i;
for (i = num - 1; i >= 0; i--) {
if (str1 == str.charAt(i)) {
System.out.println("The character " + str1 + " you intput is " + i);
break;
}
}
}
}
That is my code and I want to add a void function starting in "for". I want the for loop to be in a void function but I can't seem to do it. How do I fix this?
public class javellana {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input String: ");
String str = scan.nextLine();
System.out.println("Input character: ");
char str1 = scan.next().charAt(0);
int num = str.length();
tt(num,str1,str);
}
static void tt(int num , char str1, String str)
{
for(int i = num - 1; i >= 0; i--) {
if (str1 == str.charAt(i)) {
System.out.println("The character " + str1 + " you intput is " + i);
break;
}
}
}
}
Apart from the code, what you wanna achieve from this is still
unclear.
You can add a void method as static and use it directly in main method.
public class javellana {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input String: ");
String str = scan.nextLine();
System.out.println("Input character: ");
char str1 = scan.next().charAt(0);
int num = str.length();
int i;
func(str, str1);
}
static void func(String str, char str1) {
int num = str.length();
for (int i = num - 1; i >= 0; i--) {
if (str1 == str.charAt(i)) {
System.out.println("The character " + str1 + " you intput is " + i);
break;
}
}
}
}
EDIT:
You can simply use System.out.println(str.lastIndexOf(str1)); line, instead of the entire for loop for your problem
public class javellana {
String str;
char str1;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input String: ");
str = scan.nextLine();
System.out.println("Input character: ");
str1 = scan.next().charAt(0);
func(); // call function here
}
static void func() {
int num = str.length();
for (int i = num - 1; i >= 0; i--) {
if (str1 == str.charAt(i)) {
System.out.println("The character " + str1 + " you intput is " + i);
break;
}
}
}
}
Try this for change
If
adding a void function
means adding(declaring) another method(function) in public static void main(String){};
then this is not allowed.
What you can do is; create an anonymous class or functional interface (Java 8). Which is not exactly what you want but somehow..
main() is static method, so only static method can be used from it.
Instead of using for loop, you can use String.lastIndexOf() method.
public static void main(String... args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Input String: ");
String str = scan.nextLine();
System.out.print("Input character: ");
char ch = scan.next().charAt(0);
lastIndexOf(str, ch);
}
}
private static void lastIndexOf(String str, char ch) {
int i = str.lastIndexOf(ch);
if (i >= 0)
System.out.println("The character " + ch + " you input is " + i);
}
You can't create a method within a method.
Currently, you're in main method.
But you can call as many methods you want from a method.
But there's some restriction. you can't call the nonstatic method within a static method.
Therefore the #pkgajulapalli answer is probably correct.

Won't accept char array in this quiz

I tried to convert it to char but I'm still getting a problem that it won't build properly, newbie here. But any help would do please
import java.util.Scanner;
public class PizzaChoice {
public static void main(String[] args){
//char sizes;
Scanner input = new Scanner(System.in);
final int NUMBER_OF_CHOICES = 4;
char[] pizzaSize = {'S', 'M', 'L', 'X'};
double[] prices = {6.99, 8.99, 12.50, 15.00};
char sizeChosen;
double pizzaPrice = 0.0;
boolean validChoice = false;
Scanner inputDevice = new Scanner(System.in);
System.out.print("Enter pizza size- S, M, L, or X: ");
sizeChosen = inputDevice.nextLine().charAt(0);
for(int s = 0; s < NUMBER_OF_CHOICES; ++s)
{
if(sizeChosen.equals(pizzaSize[s]))
{
validChoice = true;
pizzaPrice = prices[s];
}
}
if(validChoice)
System.out.println("The price for chosen size " +
sizeChosen + " is $" + pizzaPrice);
else
System.out.println("Sorry - Invalid Choice Entered");
}
}
Replace char for pizzaSize and sizeChosen by Character and it will work. See "Char cannot be dereferenced" error

Scanner debugging

I have some issue using Scanner
That's the problematic code:
public static void main(String[] args) {
System.out.println("Chose 1 or 2 = ");
Scanner scan = new Scanner(System.in);
byte a = scan.nextByte();
scan.close();
if (a==1) HW();
else if (a==2) {
System.out.print("Calculation program ... !\nInput Number 1st number = ");
Scanner Catch = new Scanner(System.in);
int x = Catch.nextInt();
System.out.println("");
System.out.print("Input Operand +,-,*,/ = ");
Scanner Catchc = new Scanner (System.in);
char z = Catchc.next().charAt(0);
System.out.println("");
System.out.print("Input 2nd number = ");
Scanner Catch2 = new Scanner (System.in);
int y = Catch2.nextInt();
Catch.close();
Catchc.close();
Catch2.close();
calc(x,y,z);
}
else System.out.println("Please input number 1 or 2 ");
}
}
Thats a simple calculator and i got no errors and the program didn't terminate but it do debug instead. It shows "no such element exception"
Calc method:
public static void calc(int x, int y, char z) {
int result;
result = 0;
switch (z) {
case '+': result = x + y;
case '-': result = x - y;
case '/': result = x / y;
case '*': result = x * y;
}
System.out.println("Result of " + x + " " + z + " " + y + " is..." + " " + result);
}
When working with Scanners, you should only create 1 and NEVER close them until your program is done. This is because closing a scanner closes the passed in InputStream, and this inputstream is the input of your program, so you program doesn't cant recieve anymore input after that points.
Rewrite your code to only create 1 scanner, and pass that to other functions:
public static void main(String[] args) { // TODO Auto-generated method stub
System.out.println("Chose 1 or 2 = ");
Scanner scan = new Scanner(System.in);
byte a = scan.nextByte();
if (a==1)
HW();
else if (a==2) {
System.out.print("Calculation program ... !\nInput Number 1st number = ");
int x = scan.nextInt();
System.out.println("");
System.out.print("Input Operand +,-,*,/ = ");
char z = scan.next().charAt(0);
System.out.println("");
System.out.print("Input 2nd number = ");
int y = scan.nextInt();
calc(x,y,z);
}
else
System.out.println("Please input number 1 or 2 ");
}

Add Problems In java

I want to take input of two variable as integer and than do addition with the two variables.
The ans will stored in another variable. The program will repeat after every addition end and will ask for user input of varibles and will do addition again.
My qus is taht how can i add all aditions ans again:
Exm:
Input a= 5
Input b=5
ans=10
Agin program will ask for
Input a= 6
Input b= 6
ans=12
now how can i take all " ans " value with program and do additions of all "ans"
Final Ans=10+12=22
code:
import java.io.*;
import java.util.Scanner;
public class math{
public void add()
{
Scanner keyboard = new Scanner(System.in);
int a;
int b;
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
int c=a+b;
System.out.println("\nans is :"+c);
math ob_m=new math();
ob_m.add();
}
public static void main(String args[])
{
math ob_main=new math();
ob_main.add();
}
}
The code just do addition one after another but i want that it will do one more task that ....
It all add all aditions reasuts also. how can i do it?
import java.io.*;
import java.util.Scanner;
public class Test {
int a;
int b;
int sum = 0;
public void add() {
Scanner keyboard = new Scanner(System.in);
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
sum = sum + (a + b);
System.out.println("\nans is :" + (a + b));
}
public static void main(String args[]) {
Test ob_main = new Test();
while (true) {
ob_main.add();
}
}
}
Just keep adding the intermediate sums to another variable, so at the end you get the final total.
Another alternative (though not preferable when simple solution is available) is to put these sums in a list and at the end iterate through the list and calculate the final total.
Also, do not use ob_m.add(); - just call add();
Store every answer in an additional variable. Then when you're done, sum all the answer variables
You can use a loop for repeating your action, and store each addition in a total sum?
Change
public void add() {
Scanner keyboard = new Scanner(System.in);
int a;
int b;
int total = 0;
for(int i = 0; i < 2; i++) {
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
int c = a+b;
total += c;
}
System.out.println("\nans is :"+total);
}
Have a total variable which you just keep adding c to.
I also changed your unneeded recursion into a while-loop.
public class math
{
public static void main(String args[])
{
int total = 0;
Scanner keyboard = new Scanner(System.in);
while (true)
{
System.out.print("\nEnter a (-999 to quit): ");
int a = keyboard.nextInt();
// terminating condition, modify appropriately
if (a == -999)
break; // break out of the while-loop
System.out.print("Enter b: ");
int b = keyboard.nextInt();
int c = a + b;
total += c;
System.out.println("\nans is: " + c);
}
System.out.println("total is: " + total);
}
}
have a field GrandSUM,
GrandSum = 0;
and after every addition, add ans to it.
GrandSum += ans;
at the end , GrandSum will have result you want.
Edit:
import java.io.*;
import java.util.Scanner;
public class math{
int GrandSum = 0;//added
public void add()
{
Scanner keyboard = new Scanner(System.in);
int a;
int b;
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
int c=a+b;
GrandSum += c;//added
System.out.println("\nans is :"+c);
}
public static void main(String args[])
{
math ob_main=new math();
ob_main.add();
//.....repeat as many times you want
ob_main.add();
System.out.println("grandsum: " + ob_main.GrandSum);
}
}
package farzi;
import java.util.ArrayList;
import java.util.Scanner;
public class dummy {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
ArrayList<Integer> sum = new ArrayList<Integer>();
String choice = "";
do{
System.out.println("enter the first number");
int a = keyboard.nextInt();
System.out.println("enter the second number");
int b = keyboard.nextInt();
int tempSum = a+b;
list1.add(a);
list2.add(b);
sum.add(tempSum);
System.out.println("Do you want to continue : type yes or no");
choice = keyboard.next();
}while(choice.toLowerCase().charAt(0)=='y');
System.out.println("here are the inputs with theri sum");
System.out.println("num1\t num2\t sum");
for(int i=0;i<list1.size();i++)
{
System.out.println(list1.get(i)+"\t"+list2.get(i)+"\t"+sum.get(i));
}
}
}

Categories

Resources