Taking multiple user entries Without using arrays java - java

I've just started a intro to programming class and I'm having serious trouble with this. I basically have to take a int, double, boolean, char and string from a user the amount of times they specify and compare them. I'm having trouble actually taking the inputs.
The Problem is:
Modify the program so that, instead of comparing only two sets (records) of values (e.g. first integer vs. second integer, first boolean vs.
second boolean, etc.), the program compares an arbitrary number of records. Your code must not use arrays at this stage and it should still
achieve this behavior using only two variables for each data type.
To get the user data I have tried this :
int numberUsers = Integer.parseInt(gt.getInputString("How many people are we comparing?"));
int dataPoints = 0;
while (dataPoints <= numberUsers) {
String rawInput = gt.getInputString("For person" + dataPoints
+ ", enter in the following format: Height,Hourly Rate,Satisfied with course,Last exam grade,name.");
String[] enteredData = rawInput.split(",");
int userHeight = Integer.parseInt(enteredData[0]);
double hourRate = Double.parseDouble(enteredData[1]);
boolean satisfiedCourse = Boolean.parseBoolean(enteredData[2]);
char userGrade = enteredData[3].charAt(0);
String userName = enteredData[4];
dataPoints++;
the problem I'm having is to start a new string input for users after the first is taken. Any help would be greatly appreciated.

In case the output of the program is supposed to be the max or min value for each data type, it is possible to do that with 2 variables for each type.
For instance, here's what I would do to find the max height and the max hour rate:
int maxUserHeight = Integer.MIN_VALUE;
double maxHourRate = Double.MIN_VALUE;
int dataPoints = 0;
while (dataPoints <= numberUsers) {
String rawInput = gt.getInputString("For person" + dataPoints
+ ", enter in the following format: Height,Hourly Rate,Satisfied with course,Last exam grade,name.");
String[] enteredData = rawInput.split(",");
int userHeight = Integer.parseInt(enteredData[0]);
if (userHeight > maxUserHeight)
maxUserHeight = userHeight;
double hourRate = Double.parseDouble(enteredData[1]);
if (hourRate > maxHourRate)
maxHourRate = hourRate;
boolean satisfiedCourse = Boolean.parseBoolean(enteredData[2]);
char userGrade = enteredData[3].charAt(0);
String userName = enteredData[4];
dataPoints++;
}

Related

How to compare & replace x10 variable with a String containing x10 inside

I've been trying to do:
double x10 = 2.4;
String str = "The value of a variable is x10";
int c = 0;
while(c<str.length) #Here digit means a valid Number
if(str.charAt[c]==digit && str.charAt[c+1]==digit){
str.charAt[c] = Double.toString(x10);
}
Desired Output:
The value of a variable is 2.4
Problem:
The problem is that it doesn't seems to be comparing 10 in a String,
so that it can replace the x10 in the string with the value of variable x10.
Is there any other way to achieve the desired goal???
it works fine with variable x(1-9) but when it exceeds x10 & greater it stucks.
Didn't found anything relevant to my problem.
Any help would be highly encouraged!
I assume you are in C#. You can use the Regex.Replace variant that takes a MatchEvaluator delegate. Assuming your values are in double[] values and that they substitutions are one off in value (e.g. "x1" corresponds to values[0]), you do:
var ans = Regex.Replace(str, #"x(\d+)", m => values[Convert.ToInt32(m.Groups[1].Value)-1].ToString());
After so many tries, in order to achieve the desired output. I finally figured it out the way to solve it.
String str = "x12",str2 = "x1";
if(str2.matches("x[0-9]{1}")==true){
int var = Integer.parseInt(str.substring(1,2));
System.out.println(var);
}else{
System.out.println("Not Found!");
}if(str.matches("x[0-9]{2}")==true){
int var = Integer.parseInt(str.substring(1,2));
int var2 = Integer.parseInt(str.substring(2,3));
var = var * 10 + var2;
System.out.println(var);
}else{
System.out.println("Not Found!");
}

How can I keep track of an int and hold the 0's

Java question,
Say I have a number such as 0000102 and the 0s are important, as in they need to be there.
How can I save this information in an int(or some other way that would allow me to increment it)
For example, after checking the number 0000102 it would then add one to it and check for 0000103
When I try saving it as in int it just reverts to 102 and gets rid of the 0's, and therefore doesn't match as I search through a database since it is no longer the same. Does anyone know of a way I can do this without it removing the 0's. Thanks
EDIT:
My final solution for addition with leading zeros was this function, it takes a string with leading 0's adds one to it, then returns the string
String nextNum(String s){
int number =0;
String newNum ="";
int len = s.length();
int newLength =0;
for(int i =0; i < s.length()-1; i++){
if (s.charAt(i) == '0')
newNum+="0";
else
break;
}
number = Integer.parseInt(s);
number++;
newNum += String.valueOf(number);
newLength = newNum.length();
if(newLength == len)
return newNum;
else
return newNum.substring(1); //incase number was 000099 it doesnt go to 0000100 it goes to 000100 instead
}
You can use string formatting by combining printf with "%0d" as follows:
String num = "000123";
Integer n = Integer.parseInt(num);
n++;
int len = num.length();
System.out.printf("%0" + len + "d", n); // 000124
// and if you want to store the result
// back into a string:
String res = String.format("%0" + len + "d", n);
System.out.println(res); // 000124
You would store the value as an int (without zeroes) but could convert it into a String with leading zeroes when you want to print or display it. Here is an example conversion method.
public String addZeroes(int value, int desiredLength) {
String valueString = value + "";
int valueLength = valueString.length();
for (int i = 0; i < desiredLength - valueLength; i++) {
valueString = "0" + valueString;
}
return valueString;
}
The number itself is separate from the representation of the number. The number associated with what we usually call "ten" is always the quantity that counts these: ||||||||||, but it has many possible string representations: "10", "0000010", "0x0a", "1010(2)"... (not all of these are valid Java representations, just various representations that humans are using)
Your number will always be stored in the computer in such a way that the quantity can be (mostly) accurately handled. The string representation is normally not stored; it is calculated each time. For example, when you do System.out.println(102), it is actually handled as System.out.println(Integer.toString(102, 10)).
Between 102 and "0000102", figure which one you want to store and which one you want to display, and convert appropriately when you need the other one.
You'll need to use a String.
The decimal numbers 000102 and 0102 and 102 (and for that matter, the hex number 0x66) are all the same integer value, there is no way to distinguish between them once you store them as an int.
If you want to preserve a specific character representation of your integer, then you need a string.
To increment the String you'll need to parse it to an Integer, and then reformat it.
String increment(String s) {
int n = Integer.parseInt(s, 10)
return ("%0" + s.length() + "d").format(n+1);
}
You say you need to keep track of the leading zeroes, but that's separate from the number itself. I would keep the number itself as an int, and keep a different variable with the required number of zeroes. This will let the number keep its semantic meaning of the number as a number (and allow incrementing, as you said), and when displaying it, pad or fill with zeroes when needed, based on the second value.

Something wrong in my coding in java with numbers and strings

I tried to develop a java program using netbeans in which a GUI accepts subject marks from five text fields and displays the total marks, percentage and the grade in their respective text fields.
The problem is I am getting errors while executing the GUI. I tried replacing int with double to hold decimal values of percentage but that didn't help. I am unable to find any errors and since I am a beginner i am unable to understand the errors given in the monitor by my netbeans. Please help.
ERRORS: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: " 34"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)
at NewJFrame.submit_buttonActionPerformed(NewJFrame.java:173)
at NewJFrame.access$000(NewJFrame.java:4)
at NewJFrame$1.actionPerformed(NewJFrame.java:60)
Here's the coding I've done.
int sub1_ = Integer.parseInt(sub1.getText());
int sub2_ = Integer.parseInt(sub2.getText());
int sub3_ = Integer.parseInt(sub3.getText());
int sub4_ = Integer.parseInt(sub4.getText());
int sub5_ = Integer.parseInt(sub5.getText());
// Here each subject holds a max. of 100 marks.
int a = sub1_+sub2_+sub3_+sub4_+sub5_;
total_marks.setText(""+a);
// Since each subject holds a max. of 100 marks, the total marks of five subjects sums up to 500.
int b = (a/500)*100;
percentage.setText(b+"%");
if(b<=100&&b>=91)
{grade.setText("A1");}
else if(b<=90&&b>=81)
{grade.setText("A2");}
else if(b<=80&&b>=71)
{grade.setText("B1");}
else if(b<=70&&b>=61)
{grade.setText("B2");}
else if(b<=60&&b>=51)
{grade.setText("C1");}
else if(b<=50&&b>=35)
{grade.setText("C2");}
else if(b<=34&&b>=0)
{grade.setText("D");}
else {grade.setText("");}
java.lang.NumberFormatException: For input string: " 34"
Trim the String of whitespace before using the parse methods.
try {
int sub1_ = Integer.parseInt(sub1.getText().trim());
int sub2_ = Integer.parseInt(sub2.getText().trim());
int sub3_ = Integer.parseInt(sub3.getText().trim());
int sub4_ = Integer.parseInt(sub4.getText().trim());
int sub5_ = Integer.parseInt(sub5.getText().trim());
} catch (NumberFormatException e) {
// invalid input
}
At some point you are trying to parse the integer " 34", the leading space is a problem for the parsing method.
You should either make sure your integer has no whitespace when you create it, or use the trim() function to remove leading and trailing whitespace,
In addition to the issues already reported, the line int b = (a/500)*100; should be int b = (a * 100) / 500; or, simpler, int b = a/5;. The division by 500 rounds down to an integer, so if a is less than 500 the result is zero.
In addition to the question asked, there is a way to reduce the clutter in your code.
For example, you have multiple if-statements that all do the same thing, but with different numbers.
In this case, you can just create a function.
private boolean inRangeOf(int value, int max, int min) {
return value <= max && value >= min;
}
You can then replace your conditions with calls to inRangeOf(x, a, b)
if( inRangeOf(b, 100, 91) ) {
grade.setText("A1");
}
else if( inRangeOf(b, 90, 81) ) {
grade.setText("A2");
}
else if( inRangeOf(b, 80, 71) ) {
grade.setText("B1");
}

Unexpected Type errors

I'm getting two small unexpected type errors which I'm having trouble trying to solve.
The errors occur at:
swapped.charAt(temp1) = str.charAt(temp2);
swapped.charAt(temp2) = temp1;
Any advice?
public class SwapLetters
{
public static void main(String[] args)
{
System.out.println("Enter a string: ");
String str = new String(args[0]);
String swapped = str;
char[] charArray = str.toCharArray();
System.out.println("Enter a position to swap: ");
int Swap1 = Integer.parseInt(args[1]);
System.out.println("Enter a second position to swap: ");
int Swap2 = Integer.parseInt(args[2]);
char temp1 = str.charAt(Swap1);
char temp2 = str.charAt(Swap2);
swapped.charAt(temp1) = str.charAt(temp2);
swapped.charAt(temp2) = temp1;
System.out.println("Original String = " + str);
System.out.println("Swapped String = " + swapped);
}
}
You can assign values to variables, not other values. Statements like 5 = 2 or 'a' = 'z' don't work in Java, and that's why you're getting an error. swapped.charAt(temp1) returns some char value you're trying to overwrite, it's not a reference to a particular position inside the String or a variable you can alter (also, mind that Java Strings are immutable so you can't really change them in any way after creation).
Refer to http://docs.oracle.com/javase/7/docs/api/java/lang/String.html for information on using String, it should have a solution for what you're trying to do.
Your code may even throw IndexOutOfBoundsException - if the index argument is negative or not
less than the length of this string. Check the length of each string.
The left side of your assignment cannot receive that value.
Description of String#charAt(int):
Returns the char value at the specified index
It returns the value of the character; assigning values to that returned value in the following lines is the problem:
swapped.charAt(temp1) = str.charAt(temp2);
swapped.charAt(temp2) = temp1;
Also, String#charAt(int) expects an index of a character within the String, not the character itself (i.e. chatAt(temp1) is incorrect), so your method will not work as expected even if you fix the former problem.
Try the following:
String swapped;
if(swap1 > swap2) {
swap1+=swap2;
swap2=swap1-swap2;
swap1-=swap2;
}
if(swap1!=swap2)
swapped = str.substring(0,swap1) + str.charAt(swap2) + str.substring(swap1, swap2) + str.charAt(swap1) + str.substring(swap2);

How to display a list of ints and display total cost

This is my current code:
public static void Costs(float[] args) {
Scanner Costs = new Scanner(System.in);
String Item1Cost;
System.out.print("Enter the cost of Item 1 £");
Item1Cost = Costs.next();
String Item2Cost;
System.out.print("Enter the cost of Item 2 £");
Item2Cost = Costs.next();
String TotalCost;
TotalCost = Item1Cost + ", " + Item2Cost;
System.out.println("The cost of each of your items in order is: " + TotalCost);
}
I am trying to change it so that it obtains an int form the user and displays all the prices, and also totals them.
When trying my self I used this, and I could get the 'costs' stored them in a string and display them but I can not make a total with this code. I was wondering if someone could give me a hand. I'm sure the answer is pretty simple, but I'm fairly new to java and I just cant think of a solution.
So what you're doing at the moment is String concatenation. This is where you simply stick two String objects on the end of one another, and create a new String from that. This happens because, in Java the + operator is overloaded. This means that it expresses different functionality depending on the type of the operands.
Example of overloaded operator
String str = "Hello ";
String str2 = "World.";
String sentence = str + str2; // Sentence equals "Hello World."
int num1 = 5;
int num2 = 7;
int total = num1 + num2; // Same operator, but total equals 12, not 57.
What you need to do in your example is cast the operands to the correct types, so that Java knows how to work on them. That is, it overloads + to the correct functionality.
Example
int item1Cost = costs.nextInt(); //Notice the java naming conventions.
int item2Cost = costs.nextInt();
System.out.println("Total cost: " + (item1Cost + item2Cost));
Or you can pull the value in as a String and perform some validation. This is a safer option because it means you can control program flow easier.
String item1CostStr = costs.nextLine();
int item1Cost = 0;
if(item1CostStr.matches("[0-9]+")) {
item1Cost = Integer.parseInt(item1CostStr);
}
to convert an string to an int and operate with it, you should use this method:
Integer.parseInt(string);
That method returns an int.
Hope it helps!
If you want the input as an integer, use scan.nextInt() instead. Then it should work just fine.
This is a weird line of code though:
TotalCost = Item1Cost + ", " + Item2Cost;
What is it supposed to do? This won't compile if you're using integers.
Sidenote: use the java naming conventions. Variable names should start with a lowercase letter.

Categories