The operator + is undefined for the argument type(s) java.util.Scanner - java.util.scanner

How to remove this error ? please anyone help
I'm getting an error "The operator + is undefined for the argument type(s) java.util.Scanner"
don't know why is it showing this?
package com.learn.java;
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args) {
System.out.println("Enter marks of MATHS");
Scanner math = new Scanner(System.in);
System.out.println(math.nextFloat());
System.out.println("Enter marks of ENGLISH");
Scanner eng = new Scanner(System.in);
System.out.println(eng.nextFloat());
System.out.println("Enter marks of SOCIALSCIENCES");
Scanner socialScience = new Scanner(System.in);
System.out.println(socialScience.nextFloat());
System.out.println("Enter marks of SCIENCE");
Scanner science = new Scanner(System.in);
System.out.println(science.nextFloat());
float avgMarks = averageCalculator(math, eng, socialScience, science);
System.out.println(avgMarks);
calculatePerformanceGrades(avgMarks);
}
private static float averageCalculator(Scanner math, Scanner eng,
Scanner socialScience, Scanner science) {
float averageMarks;
averageMarks=((math + eng + socialScience + science) / 4);//getting an error here(The operator + is undefined for the argument type(s) java.util.Scanner)
return averageMarks;
}
private static void calculatePerformanceGrades(float avgMarks) {
if (avgMarks < 40) {
System.out.println("Poor");
} else if (avgMarks >= 40 && avgMarks < 59) {
System.out.println("Average");
} else if (avgMarks >= 60 && avgMarks < 79) {
System.out.println("Good");
} else if (avgMarks >= 80 && avgMarks < 89) {
System.out.println("Very Good ");
} else if (avgMarks >= 90 && avgMarks <= 100) {
System.out.println("Excellent");
}
}
}
Please help to solve the issue.

You can't use scanner to add data and find an average later. You could just perform arithmetic operations on numbers i.e. integer, floating point numbers etc. Instead define your method to accept input data type like float (i would take double here instead)
private static float averageCalculator(float math, float eng, float socialScience, float science) {
....
}
While the input that you take from standard input i.e. Keyboard, you need to capture the value and send that value to your method averageCalculator like:
Scanner scanner= new Scanner(System.in);//define it once
float math = scanner.nextFloat();//store in a variable
System.out.println(math);
...

You are using scanner to perform arithmetic operations which cannot be done.
Instead pass float parameters to the method and do manipulations.
public static void main(String[] args) {
System.out.println("Enter marks of MATHS");
Scanner math = new Scanner(System.in);
float math1=(math.nextFloat());
System.out.println("Enter marks of ENGLISH");
Scanner eng = new Scanner(System.in);
float eng1 = eng.nextFloat();
System.out.println("Enter marks of SOCIALSCIENCES");
Scanner socialScience = new Scanner(System.in);
float socialScience1= socialScience.nextFloat();
System.out.println("Enter marks of SCIENCE");
Scanner science = new Scanner(System.in);
float science1= science.nextFloat();
float avgMarks = averageCalculator(math1, eng1, socialScience1, science1);
System.out.println(avgMarks);
calculatePerformanceGrades(avgMarks);
}
private static float averageCalculator(float math, float eng,
float socialScience, float science) {
float averageMarks;
averageMarks=((math + eng + socialScience + science) / 4);
return averageMarks;
}
private static void calculatePerformanceGrades(float avgMarks) {
if (avgMarks < 40) {
System.out.println("Poor");
} else if (avgMarks >= 40 && avgMarks < 59) {
System.out.println("Average");
} else if (avgMarks >= 60 && avgMarks < 79) {
System.out.println("Good");
} else if (avgMarks >= 80 && avgMarks < 89) {
System.out.println("Very Good ");
} else if (avgMarks >= 90 && avgMarks <= 100) {
System.out.println("Excellent");
}
}

Related

How I can make multiplayer in ranking system c# in unity

my code have no error but ranking position is not working properly
how I change in my project. I want to make RPS in game.
public int currentCheckPoint, lapCount;
public float distance;
private Vector3 checkPoint;
public float counter;
public int rank;
public GameObject panelcar;
public GameObject losepanel;
void Start()
{
currentCheckPoint = 1;
StartCoroutine(LevelFail());
}
// Update is called once per frame
void Update()
{
CalculateDistance();
}
void CalculateDistance()
{
distance = Vector3.Distance(transform.position, checkPoint);
counter = lapCount * 1000 + currentCheckPoint * 100 + distance;
}
private void OnTriggerEnter(Collider other)
{
if(other.tag == "CheckPoint")
{
currentCheckPoint = other.GetComponent<CurrentCheckPoint>().currentCheckPointNumber;
checkPoint = GameObject.Find("CheckPoint" + currentCheckPoint).transform.position;
}
if(other.tag == "Finish")
{
if(gameObject.name == "Player")
{
panelcar.SetActive(true);
Time.timeScale = 0f;
AudioListener.volume = 0f;
}
if (gameObject.name == "Red Car" || gameObject.name == "Orrange Car" || gameObject.name == "yellow Car" || gameObject.name == "Blue Car" || gameObject.name == "Tursh Car")
{
losepanel.SetActive(true);
Time.timeScale = 0f;
AudioListener.volume = 0f;
}
}
}

encoding and decoding a string

I need to write an application that fist converts a string to unicode and then add 2 to the unicode value to create a new string.
Basically, if the input is: password is RhYxtz, then the output should look like: rcuuyqtf ku TjAzvb
the following code is what I have so far:
public static void main(String[] args){
System.out.print ("Enter text: ");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
int length = text.length();
for(int i = 0; i < length; i ++){
char currentChar = text.charAt(i);
int currentChar2 = currentChar+2;
String s = String.format ("\\u%04x", currentChar2);
System.out.println ("Encoded message: " + s);
}
}
The problem is that I don't know how to convert the unicode back into a letter string and how to keep the format the same as the input. Could anyone help me? Thanks.
Unicode code points can be gathered in java 8 as:
public static String encryped(String s) {
int[] cps = s.codePoints()
.mapToInt((cp) -> cp + 2)
.toArray();
return new String(cps, 0, cps.length);
}
or in a loop with codePointAt in earlier versions.
Java char (2 bytes) are UTF-16, and their int value is not always a Unicode symbol aka code point.
Try this:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
System.out.print ("Enter text: ");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
int length = text.length();
String s = "";
for(int i = 0; i < length; i ++){
char currentChar = text.charAt(i);
if (currentChar == ' '){
s += currentChar;
} else {
s += (char) (currentChar + 2);
}
}
System.out.println ("Encoded message: " + s);
}
}
This should work for US ASCII letters:
StringBuilder buf = new StringBuilder(length);
for(int i = 0; i < length; i ++){
char currentChar = text.charAt(i);
if (currentChar < 128 && Character.isLetter(currentChar)) {
if (currentChar == 'y' || currentChar == 'z'
|| currentChar == 'Y' || currentChar == 'Z') {
buf.append((char) (currentChar + 2 - 26));
} else {
buf.append((char) (currentChar + 2));
}
} else {
buf.append(currentChar);
}
}
System.out.println(buf.toString());

How do I make so that when I input a value into a scanner if it is not an integer it won't give me an error?

I am writing a program that does simple math problems. What I am trying to do is to make it so that even if I input a string into the the scanner level it will not give me an error. The level is to choose the difficulty of the math problems. I have tried parseInt, but am at a loss of what to do now.
import java.util.Random;
import java.util.Scanner;
public class Test {
static Scanner keyboard = new Scanner(System.in);
static Random generator = new Random();
public static void main(String[] args) {
String level = intro();//This method intorduces the program,
questions(level);//This does the actual computation.
}
public static String intro() {
System.out.println("HI - I am your friendly arithmetic tutor.");
System.out.print("What is your name? ");
String name = keyboard.nextLine();
System.out.print("What level do you choose? ");
String level = keyboard.nextLine();
System.out.println("OK " + name + ", here are ten exercises for you at the level " + level + ".");
System.out.println("Good luck.");
return level;
}
public static void questions(String level) {
int value = 0, random1 = 0, random2 = 0;
int r = 0, score = 0;
int x = Integer.parseInt("level");
if (x==1) {
r = 4;
}
else if(x==2) {
r = 9;
}
else if(x==3) {
r = 50;
}
for (int i = 0; i<10; i++) {
random1 = generator.nextInt(r);//first random number.
random2 = generator.nextInt(r);//second random number.
System.out.print(random1 + " + " + random2 + " = ");
int ans = keyboard.nextInt();
if((random1 + random2)== ans) {
System.out.println("Your answer is correct!");
score+=1;
}
else if ((random1 + random2)!= ans) {
System.out.println("Your answer is wrong!");
}
}
if (score==10 || score==9) {
if (score==10 && x == 3) {
System.out.println("This system is of no further use.");
}
else {
System.out.println("Choose a higher difficulty");
}
System.out.println("You got " + score + " out or 10");
}
else if (score<=8 && score>=6) {
System.out.println("You got " + score + " out or 10");
System.out.println("Do the test again");
}
else if (score>6) {
System.out.println("You got " + score + " out or 10");
System.out.println("Come back for extra lessons");
}
}
}
The first error I see is that you tried to Integer.parseInt() a String "level" instead of the String variable named level
int x = Integer.parseInt("level");
should be
int x = Integer.parseInt(level);
Also, when defining level you can use keyboard.nextInt instead of keyboard.nextLine
String level = keyboard.nextInt();
Then, you wouldn't have to do an Integer.parseInt() operation later on

Java ME Calendar not displaying

I've been following this tutorial here: Link to tutorial. I can't seem to get the application displaying properly though. When I run the application I expect to see a screen like CalendarCanvas from tutorial, but I get this:
Here is my code, I'm using standard MIDP classes.
Class CreateCalendar:
import java.util.Date;
import java.util.Calendar;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
public class CreateCalendar
{
/**
* Array of strings which holds data for the month and day
* for the calendar application.
*/
static final String[] month_labels = new String[]
{
"January", "Febuary", "March", "April", "May", "June", "July", "August", "Sepetember", "October", "November", "Decemeber"
};
static final String[] weekdays_labels = new String[]
{
"Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun"
};
public int startWeekday = 0;
public int padding = 1;
public int borderWidth = 4;
public int borderColor = 0x009900;
/**
* Weekday Labels
*/
public Font weekdayFont = Font.getDefaultFont();
public int weekdayBackgroundColor = 0x009900;
public int weekdayColor = 0xffffff;
/**
* Month/Year Labels
*/
public Font headerFont = Font.getDefaultFont();
public int headerBackgroundColor = 0x009900;
public int headerColor = 0xffffff;
/**
* Cells Labels
*/
public Font font = Font.getDefaultFont();
public int foreColor = 0xffffff;
public int backgroundColor = 0x009900;
public int selectedBackgroundColor = 0xCCFF00;
public int selectedForegroundColor = 0xffffff;
/**
* Size properties
*/
int width = 0;
int height = 0;
int headerHeight = 0;
int weekHeight = 0;
int cellWidth = 0;
int cellHeight = 0;
/**
* Internal time properties
*/
long currentTimeStamp = 0;
Calendar calendar = null;
int weeks = 0;
public CreateCalendar(Date date)
{
calendar = Calendar.getInstance();
setDate(date);
initialize();
}
public Date getSelectedDate()
{
return calendar.getTime();
}
public void setDate(Date d)
{
currentTimeStamp = d.getTime();
calendar.setTime(d);
this.weeks = (int)Math.ceil(((double)getStartWeekday() + getMonthDays()) / 7);
}
public void setDate(long timestamp)
{
setDate(new Date(timestamp));
}
public void initialize()
{
this.cellWidth = font.stringWidth("MM") + 2 * padding;
this.cellHeight = font.getHeight() + 2 * padding;
this.headerHeight = headerFont.getHeight() + 2 * padding;
this.weekHeight = weekdayFont.getHeight() + 2 * padding;
this.width = 7 * (cellWidth + borderWidth) + borderWidth;
initHeight();
}
void initHeight()
{
this.height = headerHeight + weekHeight + this.weeks * (cellHeight + borderWidth) + borderWidth;
}
int getMonthDays()
{
int month = calendar.get(Calendar.MONTH);
switch (month)
{
case 3:
case 5:
case 8:
case 10:
return 30;
case 1:
int year = calendar.get(Calendar.YEAR);
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ? 29 : 28;
default:
return 31;
}
}
int getStartWeekday()
{
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, calendar.get(Calendar.MONTH));
c.set(Calendar.YEAR, calendar.get(Calendar.YEAR));
c.set(Calendar.DAY_OF_MONTH, 1);
return (c.get(Calendar.DAY_OF_WEEK) + 5) % 7;
}
public void KeyPressed(int key)
{
switch(key)
{
case Canvas.UP:
go(-7);
break;
case Canvas.DOWN:
go(7);
break;
case Canvas.RIGHT:
go(1);
break;
case Canvas.LEFT:
go(-1);
break;
}
}
void go(int delta)
{
int prevMonth = calendar.get(Calendar.MONTH);
setDate(currentTimeStamp + 864000000 * delta);
if(calendar.get(Calendar.MONTH) != prevMonth)
{
initHeight();
}
}
public void paint(Graphics g)
{
g.setColor(backgroundColor);
g.fillRect(0, 0, width, height);
g.setFont(headerFont);
g.setColor(headerColor);
g.drawString(month_labels[calendar.get(Calendar.MONTH)] + " " + calendar.get(Calendar.YEAR), width / 2, padding, Graphics.TOP | Graphics.HCENTER);
g.translate(0, headerHeight);
g.setColor(weekdayBackgroundColor);
g.fillRect(0, 0, width, weekHeight);
g.setColor(weekdayColor);
g.setFont(weekdayFont);
for(int i = 0; i < 7; i++)
{
g.drawString(weekdays_labels[(i + startWeekday) % 7], borderWidth + i * (cellWidth + borderWidth) + cellWidth / 2, padding, Graphics.TOP | Graphics.HCENTER);
}
g.translate(0, weekHeight);
g.setColor(borderColor);
for(int i = 0; i <= weeks; i++)
{
g.fillRect(0, i * (cellHeight + borderWidth), width, borderWidth);
}
for(int i = 0; i <=7; i++)
{
g.fillRect(i * (cellWidth + borderWidth), 0, borderWidth, height - headerHeight - weekHeight);
}
int days = getMonthDays();
int dayIndex = (getStartWeekday() - this.startWeekday + 7) % 7;
g.setColor(foreColor);
int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
for(int i = 0; i < days; i++)
{
int weekday = (dayIndex + i) % 7;
int row = (dayIndex + i) / 7;
int x = borderWidth + weekday * (cellWidth + borderWidth) + cellWidth / 2;
int y = borderWidth + row * (cellHeight + cellWidth) + padding;
if(i + 1 == currentDay)
{
g.setColor(selectedBackgroundColor);
g.fillRect(borderWidth + weekday * (cellWidth + borderWidth), borderWidth + row * (cellHeight + borderWidth), cellWidth, cellHeight);
g.setColor(selectedForegroundColor);
}
g.drawString("" + (i + 1), x, y, Graphics.TOP | Graphics.HCENTER);
if(i + 1 == currentDay)
{
g.setColor(foreColor);
}
}
g.translate(0, - headerHeight - weekHeight);
}
private Date getTime() {
throw new UnsupportedOperationException("Not yet implemented"); //TODO get current Time
}
Class CalFrontEnd (extends MIDlet):
public class CalFrontEnd extends MIDlet
{
public CreateCalendar calendar;
protected Display display;
protected Form mainForm;
public CalFrontEnd()
{
}
public void startApp()
{
calendar = new CreateCalendar(new Date());
calendar.headerFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_LARGE);
calendar.weekdayFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
calendar.weekdayBackgroundColor = 0xccccff;
calendar.weekdayColor = 0x0000ff;
calendar.headerColor = 0xffffff;
calendar.initialize();
display.getDisplay(this).setCurrent(
new intCalendar(this));
}
public void pauseApp()
{
}
public void destroyApp(boolean destroy)
{
notifyDestroyed();
}
}}
Code in the class CreateCalendar looks very problematic.
In prior question you mentioned few minor variable name differences done to code from tutorial, but from what is shown in your code snippet, this is not so.
To find a way to reuse tutorial code, most straightforward approach would be like as follows.
Copy the source code from tutorial - files CalendarWidget.java and CalendarCanvas.java
Copy as-is, only adjust the package statements if necessary.
Modify CalFrontEnd about as follows
if needed, add import statement for CalendarCanvas
replace current code in startApp with simplest invocation for CalendarCanvas, like this:
public void startApp() {
Display.getDisplay(this).setCurrent(
new CalendarCanvas(this));
}
Test the code, tune and fix it until your MIDlet shows what you would expect of CalendarCanvas
After above is done, proceed with modifying the code to further match your needs.
Don't forget to test the changes you make, to make sure that things indeed work as you expect.

How to parse a string to an integer without library functions?

I was recently asked this question in an interview:
"How could you parse a string of the form '12345' into its integer representation 12345 without using any library functions, and regardless of language?"
I thought of two answers, but the interviewer said there was a third. Here are my two solutions:
Solution 1: Keep a dictionary which maps '1' => 1, '2' => 2, etc. Then parse the string one character at a time, look up the character in your dictionary, and multiply by place value. Sum the results.
Solution 2: Parse the string one character at a time and subtract '0' from each character. This will give you '1' - '0' = 0x1, '2' - '0' = 0x2, etc. Again, multiply by place value and sum the results.
Can anyone think of what a third solution might be?
Thanks.
I expect this is what the interviewer was after:
number = "12345"
value = 0
for digit in number: //Read most significant digit first
value = value * 10 + valueOf(digit)
This method uses far less operations than the method you outlined.
Parse the string in oposite order, use one of the two methods for parsing the single digits, multiply the accumulator by 10 then add the digit to the accumulator.
This way you don't have to calculate the place value. By multiplying the accumulator by ten every time you get the same result.
Artelius's answer is extremely concise and language independent, but for those looking for a more detailed answer with explanation as well as a C and Java implementation can check out this page:
http://www.programminginterview.com/content/strings
Scroll down (or search) to "Practice Question: Convert an ASCII encoded string into an integer."
// java version
public static int convert(String s){
if(s == null || s.length() == 0){
throw new InvalidParameterException();
}
int ret = 0;
boolean isNegtive = false;
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if( i == 0 && (c == '-')){
isNegtive = true;
continue;
}
if(c - '0' < 0 || c - '0' > 10){
throw new InvalidParameterException();
}
int tmp = c - '0';
ret *= 10;
ret += tmp;
}
return isNegtive ? (ret - ret * 2) : ret;
}
//unit test
#Test
public void testConvert() {
int v = StringToInt.convert("123");
assertEquals(v, 123);
v = StringToInt.convert("-123");
assertEquals(v, -123);
v = StringToInt.convert("0");
assertEquals(v, 0);
}
#Test(expected=InvalidParameterException.class)
public void testInvalidParameterException() {
StringToInt.convert("e123");
}
#Rule
public ExpectedException exception = ExpectedException.none();
#Test
public void testInvalidParameterException2() {
exception.expect(InvalidParameterException.class);
StringToInt.convert("-123r");
}
Keep a dictionary which maps all strings to their integer counterparts, up to some limit? Doesn't maybe make much sense, except that this probably is faster if the upper limit is small, e.g. two or three digits.
You could always try a binary search through a massive look up table of string representations!
No-one said anything about efficiency... :-)
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int nod(long);
char * myitoa(long int n, char *s);
void main()
{
long int n;
char *s;
printf("Enter n");
scanf("%ld",&n);
s=myitoa(n,s);
puts(s);
}
int nod(long int n)
{
int m=0;
while(n>0)
{
n=n/10;
m++;
}
return m;
}
char * myitoa(long int n, char *s)
{
int d,i=0;
char cd;
s=(char*)malloc(nod(n));
while(n>0)
{
d=n%10;
cd=48+d;
s[i++]=cd;
n=n/10;
}
s[i]='\0';
strrev(s);
return s;
}
This is Complete program with all conditions positive, negative without using library
import java.util.Scanner;
public class StringToInt {
public static void main(String args[]) {
String inputString;
Scanner s = new Scanner(System.in);
inputString = s.nextLine();
if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
System.out.println("error!!!");
} else {
Double result2 = getNumber(inputString);
System.out.println("result = " + result2);
}
}
public static Double getNumber(String number) {
Double result = 0.0;
Double beforeDecimal = 0.0;
Double afterDecimal = 0.0;
Double afterDecimalCount = 0.0;
int signBit = 1;
boolean flag = false;
int count = number.length();
if (number.charAt(0) == '-') {
signBit = -1;
flag = true;
} else if (number.charAt(0) == '+') {
flag = true;
}
for (int i = 0; i < count; i++) {
if (flag && i == 0) {
continue;
}
if (afterDecimalCount == 0.0) {
if (number.charAt(i) - '.' == 0) {
afterDecimalCount++;
} else {
beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
}
} else {
afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
afterDecimalCount = afterDecimalCount * 10;
}
}
if (afterDecimalCount != 0.0) {
afterDecimal = afterDecimal / afterDecimalCount;
result = beforeDecimal + afterDecimal;
} else {
result = beforeDecimal;
}
return result * signBit;
}
}

Resources